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++中创建,并且在使用type函数时统一返回"userdata"。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容