I'm trying to figure out the equivalent of:
foo = [] foo << "bar" foo << "baz"
I don't want to have to come up with an incrementing index. Is there an easy way to do this?
The table.insert function inserts an element in a given position of an array, moving up other elements to open space. Moreover, insert increments the size of the array (using setn ). For instance, if a is the array {10, 20, 30} , after the call table.insert(a, 1, 15) a will be {15, 10, 20, 30} .
unpack() function in Lua programming. When we want to return multiple values from a table, we make use of the table. unpack() function. It takes a list and returns multiple values.
A table is a Lua data type that can store multiple values including numbers, booleans, strings, functions, and more. Tables are constructed with curly braces ( {} ) as shown here: Code Sample Expected Output Expand.
Moreover, Lua does not even offer pointers to other objects, such as tables or functions. So, we cannot refer to Lua objects through pointers. Instead, when we need such pointers, we create a reference and store it in C.
You are looking for the insert
function, found in the table
section of the main library.
foo = {} table.insert(foo, "bar") table.insert(foo, "baz")
foo = {} foo[#foo+1]="bar" foo[#foo+1]="baz"
This works because the #
operator computes the length of the list. The empty list has length 0, etc.
If you're using Lua 5.3+, then you can do almost exactly what you wanted:
foo = {} setmetatable(foo, { __shl = function (t,v) t[#t+1]=v end }) _= foo << "bar" _= foo << "baz"
Expressions are not statements in Lua and they need to be used somehow.
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