Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua get first N elements of a table

Tags:

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?

like image 941
Kousha Avatar asked Jul 24 '19 19:07

Kousha


1 Answers

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 is 1 and j 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 table a2, performing the equivalent to the following multiple assignment: a2[t],··· = a1[f],···,a1[e]. The default for a2 is a1. 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, {})
like image 180
Piglet Avatar answered Sep 20 '22 11:09

Piglet