类型和值


Lua 是动态类型语言,变量不要类型定义。Lua 中有 8 个基本类型分别为:nil、boolean、 number、string、userdata、function、thread 和 table。函数 type 可以测试给定变量或者值 的类型。
 
print(type("Hello world"))
print(type(10.4*3))
print(type(print))
print(type(type))
print(type(true))
print(type(nil))
print(type(type(X)))
--> string
--> number
--> function
--> function
--> boolean
--> nil
 
--> string 
 
                    
变量没有预定义的类型,每一个变量都可能包含任一种类型的值。
print(type(a))
a = 10
print(type(a))
a = "a string!!"
print(type(a))
a = print
a(type(a))

--> nil ('a' is not initialized) --> number

--> string
-- yes, this is valid!
--> function

注意上面最后两行,我们可以使用 function 像使用其他值一样使用(更多的介绍参 考第六章)。一般情况下同一变量代表不同类型的值会造成混乱,最好不要用,但是特殊 情况下可以带来便利,比如 nil。

Lua 中特殊的类型,他只有一个值:nil;一个全局变量没有被赋值以前默认值为 nil;

给全局变量负 nil 可以删除该变量。

Booleans

两个取值 false 和 true。但要注意 Lua 中所有的值都可以作为条件。在控制结构的条 件中除了 false 和 nil 为假,其他值都为真。所以 Lua 认为 0 和空串都是真。

原文地址:https://www.cnblogs.com/AbelChen1991/p/3831177.html