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的字符串和其它对象都是自动内存管理机制所管理的对象,不需要担心字符串的内存分配和释放。在Lua中,字符串可以高效的处理长字符串。当字符串是多行存在时,可以使用“[[]]”符号来界定一个多行字符串,同时,Lua不会解释其中的转义序列。例如:
local page = [[ <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>xxxx</title> </head> <body> </body> </html> ]] print(page)