Lua的tables实现了关联数组,关联数组指不仅可以通过数字下标检索数据,还可以通过别的类型的值检索数据.Lua中除了nil以外的类型都可以作为tables的索引下标.另外tables没有固定的大小,你可以根据需要动态的调整他的大小.tables是Lua主要的也是唯一的数据结构,我们可以通过他实现传统数组, 符号表, 集合, 记录(pascal), 队列, 以及其他的数据结构.Lua的包也是使用tables来描述的,io.read意味着调用io包中的read函数,对Lua而言意味着使用字符串read作为key访问io表.
a =
{} --
create a table and store its reference in `a'
k = "x"
a[k] =
10 -- new entry, with
key="x" and value=10
a[20] = "great" -- new entry, with key=20
and value="great"
print(a["x"])
--> 10
k = 20
print(a[k])
--> "great"
a["x"] = a["x"] + 1 --
increments entry "x"
print(a["x"])
--> 11
a.x和a[x]的区别,前者表示访问域为字符串"x"的表中元素,后者表示以变量为x作为索引下标访问表中元素。
a =
{}
x = "y"
a[x] =
10
-- put 10 in field "y"
print(a[x]) -->
10 -- value of field "y"
print(a.x) -->
nil -- value of field "x" (undefined)
print(a.y) -->
10 -- value of field "y"
可以使用任意数字作为下标,这样就可以把table当作传统数组来使用了,可以使用任意数字作为数组的开始,lua的默认起始数字是1而不是0(c语言是0)