Vital.sandbox
Table

table.move

Shared

Moves elements from one table to another


Syntax

local result = table.move(from, start_at, end_at, move_at, to = from)

Parameters

TypeNameDescription
tablefromTable to be copied from
intstart_atPosition where moving starts
intend_atPosition where moving ends
intmove_atPosition where its moving at
tabletoTable to move into

Returns

TypeNameDescription
tableresultAltered destination table

Examples

--Copy elements to another table
local src = {1, 2, 3, 4, 5}
local dest = {}
table.move(src, 1, 3, 1, dest)
engine.print(table.concat(dest, ", ")) --1, 2, 3
--Move elements within same table
local t = {10, 20, 30, 40, 50}
table.move(t, 1, 2, 4)
engine.print(table.concat(t, ", ")) --10, 20, 30, 10, 20
--Shift elements right
local t = {1, 2, 3, 4}
table.move(t, 1, 4, 2)
engine.print(table.concat(t, ", ")) --1, 1, 2, 3, 4
--Copy subset to new position
local t = {"a", "b", "c", "d", "e"}
table.move(t, 2, 4, 6)
engine.print(table.concat(t, ", ")) --a, b, c, d, e, b, c, d
--Clone entire table
local original = {1, 2, 3}
local clone = {}
table.move(original, 1, table.len(original), 1, clone)
engine.print(table.concat(clone, ", ")) --1, 2, 3
--Insert at beginning (shift right)
local t = {2, 3, 4}
table.move(t, 1, table.len(t), 2)
t[1] = 1
engine.print(table.concat(t, ", ")) --1, 2, 3, 4
--Append from another table
local t1 = {1, 2, 3}
local t2 = {4, 5, 6}
table.move(t2, 1, table.len(t2), table.len(t1) + 1, t1)
engine.print(table.concat(t1, ", ")) --1, 2, 3, 4, 5, 6
--Remove by shifting left
local t = {1, 2, 3, 4, 5}
table.move(t, 3, 5, 2)
table.remove(t)
table.remove(t)
engine.print(table.concat(t, ", ")) --1, 3, 4, 5
--Duplicate range
local t = {"x", "y", "z"}
table.move(t, 1, 3, 4)
engine.print(table.concat(t, ", ")) --x, y, z, x, y, z
--Copy partial range
local src = {10, 20, 30, 40, 50}
local dest = {0, 0, 0, 0, 0}
table.move(src, 2, 4, 1, dest)
engine.print(table.concat(dest, ", ")) --20, 30, 40, 0, 0
--Reverse copy
local src = {1, 2, 3, 4}
local dest = {}
for i = table.len(src), 1, -1 do
    table.move(src, i, i, table.len(src) - i + 1, dest)
end
engine.print(table.concat(dest, ", ")) --4, 3, 2, 1
--Efficient array extension
local base = {1, 2, 3}
local extension = {4, 5, 6, 7, 8}
table.move(extension, 1, table.len(extension), table.len(base) + 1, base)
engine.print(table.concat(base, ", ")) --1, 2, 3, 4, 5, 6, 7, 8

On this page