Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua insert multiple variables into a table

My question is how (or if) you can insert two values into a 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 that points into a table,

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

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

like image 880
reklrekl Avatar asked May 20 '26 20:05

reklrekl


1 Answers

The select function operates on the vararg ...

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

This will ignore nils in .... myTable is assumed to be a sequence (no nils between non-nil values; {1, nil, 3} would not be a sequence) for this to insert the values in the correct order.

E.g.,

> myTable = {'a','b'}
> b('c','d')
> for i = 1, #myTable do print(myTable[i]) end
a
b
c
d
> 
like image 95
Doug Currie Avatar answered May 25 '26 12:05

Doug Currie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!