• 表构造函数
• 表使用情况
• 表格作为数组
• 表格作为记录

## 表构造函数

{[key1] = value1, [key2] = value2, …}

{key1 = “value1”, key2 = “value2”, key3 = “value3”}

{} 简单地指定一个空表。

local t1 = {} – set t1 to an empty table local t2 = {key1 = “value1”, key2 = “value2”, key3 = “value3”}

## 表格使用

local t = {} – sets t to an empty table t[“k1”] = “v1” – creates an entry for key “k1” and value “v1” v1 = t[“k1”] – sets v1 to the value for key “k1” = “v1” t[“k1”] = “new_v1” – sets the value for key “k1” to “new_v1”

## 表格作为数组

{value1, value2, value3, … }

length 运算符 # 返回连续索引从 1 开始的数组中元素的数量。示例：

local a = {“value1”, “value2”, “value3”} local length = #a – sets length to the length of array a = 3

local sparse_array = {} – set up an empty array sparse_array[1] = “value1” – add an element at index 1 sparse_array[99] = “value99” – add an element at index 99

local m = `{`{1, 2, 3}, {4, 5, 6}, {7, 8, 9} } local v22 = m[2][2] – sets v22 to 5

## 表格作为记录

local person = {name = “John Smith”, phone = “777-777-7777”} local name = person.name – sets name to “John Smith”

local people = { {name = “John Smith”, phone = “777-777-7777”}, {name = “Jane Doe”, phone = “888-888-8888”} … }

name = 人[2].name — 将名称设置为 “Jane Doe”