不要在 lua 的 table 中使用 nil 值,如果一个元素要删除,直接 remove,不要用 nil 去代替。
local table1 = {a=1,"2",c="3","4","5"}
print("size:"..#table1)
print("size:"..table.getn(table1))
print(table1["a"])
print(table1[1])
print(table1.c)
print(table1[2])
print("concat:")
print(table.concat(table1,','))
table.insert(table1,1,'0')
table.insert(table1,6)
print(table.concat(table1,','))
print("remove:")
--remove 1
table.remove(table1,#table1)
print(table.concat(table1,','))
--最大下标
print("max []")
print(table.maxn(table1))
size:3
size:3
1
2
3
4
concat:
2,4,5
0,2,4,5,6
remove:
0,2,4,5
max []
4
table = {"a","b",c="c",["d"]="4"}
--下标是从1开始的
print(table[1])
print(table.c)
print(table["d"])
print("empty table:")
emptyTable = {}
emptyTable.a = "a"
emptyTable.b = 1
emptyTable["c"] = 3
print(emptyTable.a)
print(emptyTable.b)
print(emptyTable.c)
--not exist
print(emptyTable.x)
print("remove element:")
emptyTable.b = nil
print(emptyTable.b)
print("iter table:")
for i in pairs(emptyTable) do
print(i)
end
print("用分号用来分割不同类型的表元素")
a = {x=10, y=45; "one", "two", "three";["d"]=4,["e"]=5}
print(a.x)
print(a["d"])
print(a[1])
a
c
4
empty table:
a
1
3
nil
remove element:
nil
iter table:
a
c
用分号用来分割不同类型的表元素
10
4
one
local t =
{
a = 1,
b = 2,
"abc",
c = 3,
arr = {1,"b",3},
["ip"] = "127.0.0.1"
}
print(t.a)
print(t[1])
print(t.arr[2])
print(t["ip"])
1
abc
b
127.0.0.1