Lua点滴程序员首页投稿(暂停使用,暂停投稿)

Lua base type()

2017-09-02  本文已影响176人  AlbertS
类型.jpg

前言

今天学习的这个函数在lua中绝对很常用,用来查询当前变量是什么类型,有点反射机制的意思。那么知道变量是什么类型有什么用呢?比如我们必须知道一个变量是table类型,才能通过key来访问table中的值,否则是要出问题的!

内容


type


usage

-- 定义一个局部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

总结

上一篇 下一篇

猜你喜欢

热点阅读