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.

- 78,589
- 36
- 144
- 183

- 636
- 1
- 4
- 13
3 Answers
{unpack(someList, from_index, to_index)}
But table indexes will be started from 1
, not from from_index

- 23,359
- 2
- 34
- 64
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 lua-table.
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.

- 78,589
- 36
- 144
- 183
-
Notice that the square bracket in the usage part means the i & j are optional ! Take me a while to understand. – Sisyphus Mar 21 '15 at 06:55
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

- 18,541
- 27
- 119
- 168
-
printing the unpacked list did not work for me - it only printed the first element - but [table.concat(subList, ", "))](https://stackoverflow.com/a/50111596/2550406) is nice. – lucidbrot Apr 13 '20 at 20:33
-
-
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 :) – lucidbrot Apr 13 '20 at 21:52