Lua 数据类型
Lua - 数据类型
Section titled “Lua - 数据类型”Lua 是一种动态类型语言。这意味着变量本身没有固定的类型;相反,类型与它们持有的值相关联。值可以存储在变量中、作为参数传递给函数,以及作为结果返回。
Lua 有八种基本数据类型:
| 值类型 (Value Type) | 描述 (Description) |
|---|---|
| nil | 表示没有有效的值。它只有一个可能的值:nil。未显式初始化的变量默认为 nil。在条件语境中,nil 计算为 false。 |
| boolean | 包括 true 和 false 两个值。用于条件逻辑。注意:在 Lua 中,只有 false 和 nil 被认为是假值(falsy);所有其他值(包括 0 和空字符串)都被认为是真值(truthy)。 |
| number | 表示数值。在 Lua 5.3 之前,所有数字都是双精度浮点数。Lua 5.3 引入了整型子类型,但 type() 对整数和浮点数都返回 “number”。Lua 会在适当的地方自动处理转换。 |
| string | 表示不可变的字符序列。字符串可以用单引号('...')、双引号("...")或长方括号([[...]] 用于多行字符串)括起来。 |
| function | 表示函数。函数在 Lua 中是一等公民(first-class citizens),意味着它们可以存储在变量中、作为参数传递,以及作为结果返回。它们可以用 Lua 或 C 编写。 |
| userdata | 表示任意的 C 数据。允许 C 代码将自定义数据类型提供给 Lua 使用。有两种类型:完整 userdata(full userdata,由 Lua 管理内存)和 轻量 userdata(light userdata,只是一个 C 指针)。 |
| thread | 表示独立的执行线程,用于实现协程(coroutines)。协程允许协作式多任务,而非抢占式操作系统级线程。 |
| table | Lua 中唯一的数据结构机制。表是关联数组(associative arrays,也称为映射表 maps 或字典 dictionaries),可以用来表示普通数组、集合、记录、图、树、对象等。它们可以将除 nil 以外的任何值作为键或值(使用 nil 作为键或将 nil 赋值给某个键相当于移除该键值对)。 |
type() 函数
Section titled “type() 函数”Lua 提供了一个内置函数 type(),它返回一个字符串,描述给定值的类型。以下是一些示例:
print(type("What is my type?")) --> stringprint(type(10)) --> numberprint(type(3.14)) --> numberprint(type(true)) --> booleanprint(type(print)) --> function (print is a global function)-- print 是一个全局函数print(type(type)) --> function (type is also a function)-- type 也是一个函数print(type(nil)) --> nil
local myTable = {}print(type(myTable)) --> table
local co = coroutine.create(function() end)print(type(co)) --> thread
-- For an undefined variable, its value is nil-- 对于未定义变量,其值为 nilprint(type(undefinedVariable)) --> nil (assuming undefinedVariable has not been assigned a value)-- nil(假设 undefinedVariable 未被赋值)
-- The type of the result of type(X) is always string-- type(X) 结果的类型始终是 stringprint(type(type(123))) --> string (because type(123) is "number", and type("number") is "string")-- string(因为 type(123) 是 "number",而 type("number") 是 "string")以上代码的输出:
stringnumbernumberbooleanfunctionfunctionniltablethreadnilstring请记住,未显式初始化的变量默认为 nil。初学者一个常见的陷阱是误认为 0 或空字符串 "" 在条件中是 false;在 Lua 中,它们都被认为是 true。只有 false 和 nil 在布尔上下文中计算为 false。理解这些类型对于有效的 Lua 编程至关重要。