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.
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.
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.
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"}
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.
{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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With