Is there a method for getting the first N elements of a table? And more generally, give me the first N elements starting from position P.
Or do I have to write a function and use pairs
to do so?
As mentioned in the comments tables don't have an order by default. It's just a bunch of key value pairs. So your request only makes sense for sequences. Here's some detail and an example for each suggested solution.
local myTable = {"a", "b", "c", "d", "e", "f", "g", "h"}
local p = 3
local n = 4
Option 1: https://www.lua.org/manual/5.3/manual.html#pdf-table.unpack
table.unpack(list [, i [, j]])
Returns the elements from the given list. This function is equivalent to
return list[i], list[i+1], ···, list[j]
By default,
i
is1
andj
is#list
.
print(table.unpack(myTable, p, p+n-1))
c d e f
Option 2: https://www.lua.org/manual/5.3/manual.html#pdf-table.move
table.move (a1, f, e, t [,a2])
Moves elements from table
a1
to tablea2
, performing the equivalent to the following multiple assignment:a2[t],··· = a1[f],···,a1[e]
. The default fora2
isa1
. The destination range can overlap with the source range. The number of elements to be moved must fit in a Lua integer.Returns the destination table
a2
.
local slice = table.move(myTable, p, p+n-1, 1, {})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With