Lua - Slicing Arrays
In Lua, we do not have direct support for slicing array. But using table.unpack() method, we can achieve the same using following syntax:
Syntax
slicedArray = {table.unpack(array, startIndex, endIndex)}
Where
array− source array.
startIndex− index of array from where slicing is to be done.
endIndex− index of array where slicing ends.
Example - Slicing array of characters
Create a new source file named main.lua and paste the following code to slice an array.
main.lua
-- source array
array = {"a", "b", "c", "d", "e", "f"}
-- unpack the array with start/end indexes
slicedArray = {table.unpack(array, 2, 4)}
-- iterate the sliced array and print the values
for key, value in pairs(slicedArray) do
print(key, value)
end
Output
1 b 2 c 3 d
Example - Slicing array of numbers
Update the source file named main.lua and paste the following code to slice an array.
main.lua
-- source array
array = {1, 2, 3, 4, 5, 6}
-- unpack the array with start/end indexes
slicedArray = {table.unpack(array, 2, 4)}
-- iterate the sliced array and print the values
for key, value in pairs(slicedArray) do
print(key, value)
end
Output
1 2 2 3 3 4
Example - Slicing array Using custom method
We can create a custom method, to get a sliced array.
Update the source file named main.lua and paste the following code to slice an array.
main.lua
-- custom function to get sliced array
function slice(array, first, last, step)
local slicedArray = {}
-- iterate the loop from first to loop
-- fill the sliced array
for i = first or 1, last or #array, step or 1 do
slicedArray[#slicedArray+1] = array[i]
end
-- return the array
return slicedArray
end
-- source array
sourceArray = {1, 2, 3, 4, 5, 6}
-- get sliced array
targetArray = slice(sourceArray, 2, 4)
-- iterate the sliced array and print values
for key, value in pairs(targetArray) do
print(key, value)
end
Output
1 2 2 3 3 4
Advertisements