Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I append to a table in Lua

Tags:

lua

lua-table

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?

like image 642
drewish Avatar asked Dec 11 '14 23:12

drewish


People also ask

What is table insert in Lua?

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} .

How do I unpack a table in Lua?

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.

What is a table value in Lua?

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.

Are there pointers in Lua?

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.


2 Answers

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") 
like image 147
rsethc Avatar answered Sep 28 '22 21:09

rsethc


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.

like image 30
lhf Avatar answered Sep 28 '22 20:09

lhf