Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a part of a list or table in Lua

Tags:

lua

lua-table

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.

like image 938
sdamashek Avatar asked Mar 05 '13 13:03

sdamashek


People also ask

How do I index a table in Lua?

For Lua, that means "index the table io using the string "read" as the key". When a program has no references to a table left, Lua memory management will eventually delete the table and reuse its memory. Notice the last line: Like global variables, table fields evaluate to nil if they are not initialized.

How do I get the key of a value in Lua?

To access the value associated with the key in a table you can use the table[key] syntax: > t = {} > t["foo"] = 123 -- assign the value 123 to the key "foo" in the table > t[3] = "bar" -- assign the value "bar" to the key 3 in the table > = t["foo"] 123 > = t[3] bar.

What is unpack Lua?

In Lua, if you want to call a variable function f with variable arguments in an array a , you simply write f(unpack(a)) The call to unpack returns all values in a , which become the arguments to f . For instance, if we execute f = string.find a = {"hello", "ll"}

How do I remove an item from an array in Lua?

If you want to delete items from an array (a table with numeric indices), use ArrayRemove() . By the way, the tests above were all executed using Lua 5.3. 4 , since that's the standard runtime most people use.


2 Answers

{unpack(someList, from_index, to_index)}

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

like image 106
Egor Skriptunoff Avatar answered Oct 26 '22 18:10

Egor Skriptunoff


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.

like image 38
hjpotter92 Avatar answered Oct 26 '22 17:10

hjpotter92