Lua inserts several variables into a table

My question is how (or if) you can insert two values ​​into the lua table.

I got a function that returns (a variable number of values)

function a(x, y) return x, y end 

and another function that inserts this into the table,

 function b(x, y) table.insert(myTable, x, y) end 

So, how can I do that I can call function b with a variable number of arguments and insert them all into my table?

+1
source share
2 answers

If the last parameter for your function ... (called the vararg function), the Lua interpreter puts any additional arguments in ... You can convert it to a table using {...} and copy the keys / values ​​to your global table called myTable . Here is what your function looks like:

 function b(...) for k, v in pairs({...}) do myTable[k] = v end end b(1, 2) -- {[1] = 1, [2] = 2} is added to myTable 

You must customize the function depending on whether you want to replace, merge, or add items to myTable .

+1
source

The select function works on vararg ...

 function b(...) for i = 1, select('#',...) do myTable[#myTable+1] = select(i,...) end end 

eg.

 > myTable = {'a','b'} > b('c','d') > for i = 1, #myTable do print(myTable[i]) end a b c d > 
+1
source

All Articles