Копирование массива

Массивы и коллекции / Массивы

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

-- Присваивание ничего не копирует: второе имя
local alias = numbers1

-- Копия циклом
local numbers2 = {}
for index, number in ipairs(numbers1) do
  numbers2[index] = number
end

-- table.move(source, from, to, at, target) копирует элементы в целевую таблицу
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

-- Вложенные таблицы: у копии внутренние общие
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])