1

In lua I'm using someone elses function that takes variable number of arguments. What I would like to be able to do is build the argument list via loop. Is this possible?

Example function:

printResult = ""

function print (...)
  for i,v in ipairs(arg) do
    printResult = printResult .. tostring(v) .. "\t"
  end
  printResult = printResult .. "\n"
end

I tried

print({"test","test2"})

But that just passes one argument (the table) to the function

2
  • Use {...} instead of arg. Commented Oct 5, 2019 at 14:06
  • Like I said it's not my function. But I tried what you suggested in test function but the result was the same Commented Oct 5, 2019 at 15:21

1 Answer 1

1

You are looking for the table.unpack function. You can build the arguments to the vararg function you want to call in a table. Calling table.unpack on the table will expand the table into an argument list. Like so,

args = {}
for i = 1, 4 do
    args[#args+1] = i * i * math.pi
end

print(table.unpack(args))

Also, you will need in the print function you posted to gather all those arguments into the arg list that you are using...

function print (...)
  printResult = ""
  arg = {...}
  for i,v in ipairs(arg) do
    printResult = printResult .. tostring(v) .. "\t"
  end
  printResult = printResult .. "\n"
  return printResult
end

Finally, there is already a way to accomplish what you are trying to do using table.concat.

function print(...)
    return table.concat({...}, "\t").."\n"
end
Sign up to request clarification or add additional context in comments.

Comments

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.