数组复制

数组和集合 / 数组

local numbers1 = {1, 2, 3, 4, 5}

-- Assignment copies nothing: a second name
local alias = numbers1

-- A copy by a loop
local numbers2 = {}
for index, number in ipairs(numbers1) do
  numbers2[index] = number
end

-- table.move(source, from, to, at, target)
-- copies the items into the target table
local numbers3 =
  table.move(numbers1, 1, #numbers1, 1, {})

numbers1[1] = 10
-- numbers1 = 10, 2, 3, 4, 5
-- alias = 10, 2, 3, 4, 5
-- numbers2 = 1, 2, 3, 4, 5
-- numbers3 = 1, 2, 3, 4, 5

-- Nested tables: a copy shares the inner ones
local matrix1 = {{1, 2}, {3, 4}}
local shallow =
  table.move(matrix1, 1, #matrix1, 1, {})
matrix1[1][1] = 100
-- shallow[1][1] = 100

print("numbers1 = "
      .. table.concat(numbers1, ", "))
print("alias = " .. table.concat(alias, ", "))
print("numbers2 = "
      .. table.concat(numbers2, ", "))
print("numbers3 = "
      .. table.concat(numbers3, ", "))
print("shallow[1][1] = " .. shallow[1][1])