--using a loop to iterate though your table for i=1, #colors do print(colors[i]) end
表操作
1 2 3 4 5
--insert local colors = { "red", "green", "blue" } table.insert(colors, "orange") local index = #colors --4 (this is the last index in the table) print(colors[index]) --orange
1 2 3 4 5 6 7
--insert at index local colors = { "red", "green", "blue" } table.insert(colors, 2, "pink") for i=1, #colors do print(colors[i]) end --red, pink, green, blue
1 2 3 4 5 6 7
--remove local colors = { "red", "green", "blue" } table.remove(colors, 1) for i=1, #colors do print(colors[i]) end -- "green", "blue"
2 尺寸表
1 2 3 4 5 6 7 8 9 10
--tables within tables local data = { { "billy", 12 }, { "john", 20 }, { "andy", 65 } }
for a=1, #data do print(data[a][1] .. " is " .. data[a][2] .. " years old") end
键表
二维表不适合不同类型的数据,而是使用表的键
1 2 3 4 5 6 7 8 9 10
local teams = { ["teamA"] = 12, ["teamB"] = 15 }
print(teams["teamA"]) -- 12
for key,value inpairs(teams) do print(key .. ":" .. value) end
1 2
--insert into key table teams["teamC"] = 1
1 2
--remove key from table teams["teamA"] = nil
从函数返回表
这可用于从函数返回多个值
1 2 3 4 5 6 7 8 9 10 11 12 13 14
functiongetTeamScores() local scores = { ["teamA"] = 12, ["teamB"] = 15 } return scores end
local scores = getTeamScores() local total = 0 for key, val inpairs(scores) do total += val end print("Total score of all teams:" .. total)