通过给出一个key来获得对应的value。并且,table的key可以是除nil以外的任意类型
local tab = {}tab.a = 1tab["hello"] = "world"tab["f"] = function()print("c is function")endfor k, v in pairs(tab) doprint(string.format("key=%s,value=%s", tostring(k), tostring(v)))end
concat
concat是concatenate(连锁, 连接)的缩写. table.concat()函数列出参数中指定table的数组部分从start位置到end位置的所有元素, 元素间以指定的分隔符(sep)隔开。
fruits ={"banana","apple","origin"}print(table.concat(fruits))print(table.concat(fruits,","))
输出结果
bananaappleoriginbanana,apple,origin
制定索引连接table
fruits ={"banana","apple","origin"}print(table.concat(fruits,",",2,3))
输出结果
apple,origin
insert
插入数据
fruits ={"banana","apple","origin"}table.insert(fruits,"mango")print(table.concat(fruits,","))
打印结果
banana,apple,origin,mango
在索引2 插入数据
fruits ={"banana","apple","origin"}table.insert(fruits,2,"mango")print(table.concat(fruits,","))
输出结果
banana,mango,apple,origin
remove
fruits ={"banana","apple","origin"}table.remove(fruits)print(table.concat(fruits,","))
输出结果
banana,apple
遍历
ipairs
myTable ={1,a=2,"hello",b="world"}for k,v in ipairs(myTable)doprint(k,v)end
输出结果
1 12 hello
pairs
myTable ={1,a=2,"hello",b="world"}for k,v in pairs(myTable)doprint(k,v)end
输出结果
1 12 helloa 2b world
数组形式还可以用和c语言类似的方式
letters = { "a", "b", "c" }for k = 1, #letters doprint(k, letters[k])end
