reklrekl
reklrekl

Reputation: 33

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?

Upvotes: 3

Views: 15854

Answers (3)

darkfrei
darkfrei

Reputation: 521

function tableMultiInsert (list, ...)
  for i, v in ipairs({...}) do
    list[#list+1] = v
  end
end

local list = {}
tableMultiInsert (list, 'a', 'b')
print (table.concat (list, ',')) -- a, b
tableMultiInsert (list, 'c', 'd')
print (table.concat (list, ',')) -- a,b,c,d

Upvotes: 1

Doug Currie
Doug Currie

Reputation: 41170

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
> 

Upvotes: 2

Ryan
Ryan

Reputation: 2404

If the last parameter for your function is ... (called a vararg function), the Lua interpreter will place any extra arguments into .... You can convert it to a table using {...} and copy the keys/values into your global table named myTable. Here's what your function would look 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 should tweak the function depending on whether you want to replace, merge or append elements into myTable.

Upvotes: 1

Related Questions