Getting a part of a list or table in Lua
Asked Answered
G

3

18

I know it's very easy to do in Python: someList[1:2] But how do you this in Lua? That code gives me a syntax error.

Gallinule answered 5/3, 2013 at 13:10 Comment(0)
S
16

The unpack function built into Lua can do this job for you:

Returns the elements from the given table.

You can also use

x, y = someList[1], someList[2]

for the same results. But this method can not be applied to varying length of .

Usage

table.unpack (list [, i [, j]])

Returns the elements from the given table. This function is equivalent to

return list[i], list[i+1], ···, list[j]

By default, i is 1 and j is #list.

A codepad link to show the working of the same.

Sundry answered 5/3, 2013 at 14:3 Comment(1)
Notice that the square bracket in the usage part means the i & j are optional ! Take me a while to understand.Suhail
R
23
{unpack(someList, from_index, to_index)}

But table indexes will be started from 1, not from from_index

Remise answered 5/3, 2013 at 13:53 Comment(0)
S
16

The unpack function built into Lua can do this job for you:

Returns the elements from the given table.

You can also use

x, y = someList[1], someList[2]

for the same results. But this method can not be applied to varying length of .

Usage

table.unpack (list [, i [, j]])

Returns the elements from the given table. This function is equivalent to

return list[i], list[i+1], ···, list[j]

By default, i is 1 and j is #list.

A codepad link to show the working of the same.

Sundry answered 5/3, 2013 at 14:3 Comment(1)
Notice that the square bracket in the usage part means the i & j are optional ! Take me a while to understand.Suhail
A
9

The exact equivalent to the Python

someList = [ 'a', 'b', 'c', 'd' ]
subList = someList[1:2]
print( subList )    

in Lua is

someList = { 'a', 'b', 'c' , 'd' }
subList = { unpack( someList, 2, 2 ) }
print( unpack(subList) )

The key thing is that unpack returns "multiple results" which is not a table, so to get a list (aka table) in Lua you need to "tablify" the result with { and }.

However, you cannot print a table in Lua, but you can print multiple results so to get meaningful output, you need to unpack it again.

So unlike Python which mimics multiple returns using lists, Lua truly has them.


Nb in later versions of Lua unpack becomes table.unpack

Announcer answered 11/6, 2018 at 15:24 Comment(3)
printing the unpacked list did not work for me - it only printed the first element - but table.concat(subList, ", ")) is nice.Compensable
@Compensable which Lua version?Announcer
5.3.5 on windows. (Though it's well possible that I have made some mistake and that's why it did not work) Edit: Yeah if I use your example in a single file, that works. Just treat my comment as help for others who make mistakes they don't find :)Compensable

© 2022 - 2024 — McMap. All rights reserved.