lua基础之lua表结构:
http://www.lua.org/pil/2.5.html
1.在lua中,nil不是0,也不是空字符串"",索引值从1开始。
a = {}
a["x"] = 10
b = a --"b" refers to the same table as "a"
print(b["x"]) ---10
b["x"] = 20
print(a["x"]) ---20
a = nil --now only "b" refers to the table
b = nil --now there are no references left to the table
--此时lua内存管理将删除表并重新利用它的内存。
2.表中可以存储不同类型的索引,可以动态增长其存储长度。
a = {} --empty table
--create 1000 new entries
for i = 1, 1000 do a[i] = i*2 end
print(a[9]) -->18
a["x"] = 10
print(a["x"]) -->10
print(a["y"]) --> nil 未初始化的值为nil,并且如果需要删除一个全局变量,直接给其赋值nil即可。
3.除了索引之外,也可以使用a.name指代a[“name”]。
a.x = 10 ---same as a["x"] = 10
print(a.x) --same as print(a["x"])
print(a.y) --same as print(a["y"])
初学者容易混淆a.x和a[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"
print(a.y) --->10 --value of field "y"
有点绕!a.name的时候记得name是字符串“name”。
4.数字索引
-- read 10 lines storing them in a table
for i = 1,10 do
a[i] = io.read()
end
-- 打印
--the array ends with its first nil element
for i, line in ipairs(a) do
print(line)
end