table.move()
The table.move()
function moves a specified range of elements from one table to another, allowing you to reposition elements within the same table or transfer them to a different table.
Syntax
table.move(source, sourcePos, targetPos, targetEnd, target)
Parameters
- Name
source
- Type
- table
- Description
The table from which elements will be moved.
- Name
sourcePos
- Type
- number
- Description
The starting position in the source table from which to move elements.
- Name
targetPos
- Type
- number
- Description
The position in the target table where the elements will be moved to.
- Name
targetEnd
- Type
- number
- Description
The ending position in the source table. This indicates how many elements to move.
- Name
target
- Type
- table|nil
- Description
Optional. The target table to which elements will be moved. If omitted, the source table will be used.
Return
The function returns the target table containing the moved elements.
Description
The table.move()
function is useful for rearranging elements within a table or transferring elements to a different table. It allows for specified ranges and can be used to efficiently manipulate tables.
Examples
Moving elements within the same table
local numbers = {1, 2, 3, 4, 5}
table.move(numbers, 2, 4, 1, numbers) -- Moves elements from index 2 to 4 to the start
print(table.concat(numbers, ", "))
-- Output: 2, 3, 4, 1, 5
Moving elements to a different table
local source = {1, 2, 3, 4, 5}
local target = {}
table.move(source, 2, 4, 1, target) -- Moves elements from index 2 to 4 of source to target
print(table.concat(target, ", "))
-- Output: 2, 3, 4
Overlapping move within the same table
local letters = {"A", "B", "C", "D", "E"}
table.move(letters, 2, 4, 3, letters) -- Moves B, C, D to positions 3, 4, 5
print(table.concat(letters, ", "))
-- Output: A, B, B, C, D
See also
table.insert()
: Inserts a value into a table at a specified position.table.remove()
: Removes a value from a table at a specified position.