Getting a part of a list or table in Lua

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


{unpack(someList, from_index, to_index)}

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


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.

Tags:

Lua

Lua Table