類型.jpg
前言
今天學習的這個函數(shù)在lua中絕對很常用,用來查詢當前變量是什么類型,有點反射機制的意思。那么知道變量是什么類型有什么用呢?比如我們必須知道一個變量是table類型,才能通過key來訪問table中的值,否則是要出問題的!
內(nèi)容
type
- type(v)
- 解釋:這個函數(shù)只有一個參數(shù),調(diào)用后會返回這個參數(shù)類型所對應(yīng)的字符串,這些類型字符串包括"nil", "number", "string", "boolean", "table", "function", "thread" 和 "userdata"。另外這個參數(shù)是必須給的,不然會報錯誤:"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定義函數(shù)
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
- 運行結(jié)果
base_type.png
總結(jié)
- 在lua的編程中要盡可能的使用局部變量,比如例子中的
local information
。 - 通過對表information各個變量的類型進行打印,我們逐漸明白了
type
函數(shù)的用法。 -
type
函數(shù)通常會被封裝起來,類似于例子中的isnil
和istable
函數(shù),這樣使用起來更加方便。 - 還有一點需要注意的是"userdata"和"lightuserdata"類型只能在C/C++中創(chuàng)建,并且在使用type函數(shù)時統(tǒng)一返回"userdata"。