1.table 可以用来实现 array,dictionary,object,module,package 等 。
2.table 是 Lua 中唯一使用引用传递的数据结构。
3.table 是 hash table ,底层由 C 语言的 array 和 list 实现。
4.table 中 key - value 可以是任何类型( key 不可为nil ),table 可以拥有不同的 key( value )类型。
5.table 的遍历
pairs ,直到遇到 value 为 nil 停止,或完整遍历。
ipairs ,从 key 1开始,逐次累加1(1,2,3,4 ...),任一个 key 不存在,或存在但 value 为 nil 则停止,或完整遍历。
6.table 的长度
Functions:
table.concat (table [, sep [, start [, end]]])
table.insert (table, [pos,] value)
table.maxn (table)
table.remove (table [, pos])
table.sort (table [, comp])
Work as an array:
-- array initialization
local attributes = {"name", "age", "sex"}
-- [1] = "name" [2] = "age" [3] = "sex"
-- array add elements at the end
attributes[4] = "family"
attributes[5] = "address"
table.inset(attributes, "school")
-- [1] = "name" [2] = "age" [3] = "sex" [4] = "family" [5] = "address" [6] = "school"
-- array modify specific element
attributes[4] = "hobby"
-- [1] = "name" [2] = "age" [3] = "sex" [4] = "hobby" [5] = "address" [6] = "school"
-- array access to elements
print(attributes[1], attributes[2], attributes[3])
Work as a dictionary:
-- dictionary initialization
local statedAttributes = {
["name"] = true,
["age"] = true,
["sex"] = false
}
-- dictionary add elements
statedAttributes["family"] = false
statedAttributes["address"] = true
-- dictionary modify element
statedAttributes["family"] = true
Work as an object: