3

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?

1
  • 1
    As currently written, function b inserts the value y at position x. Is that your intent? If you want to insert multiple values into a table, you have to call table.insert multiple times. This page describes how to handle a variable number of arguments to a function; does that help? Commented Nov 4, 2012 at 0:47

3 Answers 3

2

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
> 
Sign up to request clarification or add additional context in comments.

2 Comments

As a slightly remark, calling b(1,2,nil,4) produces the table {[1] = 1, [2] = 2, [3] = 4}. It can be good, or bad, depending on the requirements.
A funny theoretical edge case: If myTable has holes (is not a proper sequence), b may fill them in any order ;)
1

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.

Comments

1
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

2 Comments

Downvoted. Overriding table.insert like this will massively break existing code that uses the index parameter. Small side note: This doesn't deal with nils in ... properly; it will stop at the first nil (it should ideally either ignore nils, or throw an error).
Thanks, you are right! Fixed the code as new function instead of table.insert.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.