
類型.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函數通常會被封裝起來,類似于例子中的isnil和istable函數,這樣使用起來更加方便。 - 還有一點需要注意的是"userdata"和"lightuserdata"類型只能在C/C++中創(chuàng)建,并且在使用type函數時統(tǒng)一返回"userdata"。