Lua学习笔记之类型与值学习笔记之类型与值
本文详细的总结了Lua中的类型与值,对于实际编程中容易出错的地方也进行了详细的总结,十分的全面实用。
有需要的小伙伴可以参考下。
基础介绍基础介绍
Lua是一种动态类型的语言。在语言中没有类型定义的语法,每个值都带有其自身的类型信息。在Lua中有8种基本类型,分别
是:
nil(空)类型
boolean(布尔)类型
number(数字)类型
string(字符串)类型
userdata(自定义类型)
function(函数)类型
thread(线程)类型
table(表)类型
以上是Lua中的8中基本类型,我们可以使用type函数,判断一个值得类型,type函数返回一个对应类型的字符串描述。例如:
local iValue = 10
local fValue = 10.2
local strValue = "Hello World"
local funcValue = print
local bValue = true
local nilValue = nil
local tbValue = {}
if type(iValue) == "number" then
print("It is a number")
end
if type(fValue) == "number" then
print("It is a number")
end
if type(strValue) == "string" then
print("It is a string")
end
if type(funcValue) == "function" then
print("It is a function")
end
if type(bValue) == "boolean" then
print("It is a boolean")
end
if type(nilValue) == "nil" then
print("It is a nil")
end
if type(tbValue) == "table" then
print("It is a table")
end
nil(空)
nil是一种类型,它只有一个值nil。一个全局变量在第一次赋值前的默认值就是nil,将nil赋予一个全局变量等同于删除它。Lua
将nil用于表示一种“无效值”的情况,即没有任何有效值得情况。
boolean(布尔)(布尔)
boolean类型有两个可选值:false和true。一定需要注意的是,在Lua中只有false和nil是“假”的,而除此之外的都是“真”,这和
其它语言有所区别的。我之前有一个同事,就吃过这个亏。
number(数字)(数字)
number类型用于表示双精度浮点数。Lua没有整数类型,而Lua中的数字可以表示任何32位整数。
string(字符串)(字符串)
Lua中的字符串通常表示“一个字符序列”。Lua完全采用8位编码。Lua的字符串是不可变的值。不能像C语言中那样直接修改字
符串的某个字符,而是应该根据修改要求来创建一个新的字符串。Lua的字符串和其它对象都是自动内存管理机制所管理的对