Does lua have a spread operator when you are passing a variable to a function?
For example, I have an array a
and I want to pass this to another function, say string.format
. If I just do string.format(a)
then I get
bad argument #1 to 'format' (string expected, got table)
I tried local f, e = pcall(string.format, t)
without any luck.
Kousha. I was tinkering about and stumbled upon a function you might interesting.
In version 5.1 of Lua, unpack
was available as a global function. In 5.2, they moved it to table.unpack
, which makes a lot more sense. You can call this function using something like the following. string.format
only takes in a single string unless you add more things in the format parameter.
-- Your comment to my question just made me realize you can totally do it with unpack.
t = {"One", "Two", "Three"};
string.format("%s %s %s", table.unpack(t)); -- One Two Three
-- With your implementation,
-- I believe you might need to increase the length of your args though.
local f = "Your table contains ";
for i = 1, #t do
f.." %s";
end
string.format(f, table.unpack(t));