动态数组

数组和集合 / 数组

-- 无需声明大小:
-- 向末尾添加元素时数组自动增长
local squares = {}
local n = 1
while n * n < 50 do
  squares[#squares + 1] = n * n
  n = n + 1
end
-- squares = 1, 4, 9, 16, 25, 36, 49
print("squares = " .. table.concat(squares, ", "))

-- 已有的索引会被替换
squares[1] = 100
-- squares = 100, 4, 9, 16, 25, 36, 49
print("squares = " .. table.concat(squares, ", "))

-- 读取超出末尾的位置不是错误
local past_end = squares[10]
-- past_end = nil
print("past_end = " .. tostring(past_end))