Lua base type()

類型.jpg

前言

今天學習的這個函數在lua中絕對很常用,用來查詢當前變量是什么類型,有點反射機制的意思。那么知道變量是什么類型有什么用呢?比如我們必須知道一個變量是table類型,才能通過key來訪問table中的值,否則是要出問題的!

內容


type

  • type(v)
  • 解釋:這個函數只有一個參數,調用后會返回這個參數類型所對應的字符串,這些類型字符串包括"nil", "number", "string", "boolean", "table", "function", "thread" 和 "userdata"。另外這個參數是必須給的,不然會報錯誤:"bad argument #1 to 'type' (value expected)"。

usage

  • 首先我們新建一個文件將文件命名為typefunctest.lua然后編寫代碼如下:
-- 定義一個局部table
local information =
{
    name = "AlbertS",
    age = 22,
    married = false,
    test = function () print("test") end,
    weight = 60.2,
}

print("phone type:", type(information.phone))
print("name type:", type(information.name))
print("age type:", type(information.age))
print("married type:", type(information.married))
print("test type:", type(information.test))
print("weight type:", type(information.weight))


-- 利用type定義函數
function isnil(var)
    return type(var) == "nil"
end

function istable(var)
    return type(var) == "table"
end


print("\nuse function:")
if isnil(information.phone) then
    print("information.phone is nil")
end

if istable(information) then
    print("my age is", information.age)
end
  • 運行結果
base_type.png

總結

  • 在lua的編程中要盡可能的使用局部變量,比如例子中的local information。
  • 通過對表information各個變量的類型進行打印,我們逐漸明白了type函數的用法。
  • type函數通常會被封裝起來,類似于例子中的isnilistable函數,這樣使用起來更加方便。
  • 還有一點需要注意的是"userdata"和"lightuserdata"類型只能在C/C++中創(chuàng)建,并且在使用type函數時統(tǒng)一返回"userdata"。
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容