当你将变量传递给函数时,lua 是否有扩展运算符?
例如,我有一个数组a
我想把它传递给另一个函数,比如说 string.format
.如果我只是做 string.format(a)
然后我得到
bad argument #1 to 'format' (string expected, got table)
我试过了 local f, e = pcall(string.format, t)
没有任何运气。
最佳答案
酷莎。我正在修补并偶然发现了一个您可能感兴趣的函数。
在 Lua 5.1 版本中,unpack
作为全局函数可用。在 5.2 中,他们将其移至 table.unpack
,这更有意义。您可以使用类似下面的内容调用此函数。 string.format
只接受一个字符串除非您在格式参数中添加更多内容。
-- 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));
关于arrays - 数组上的 Lua 展开运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50478236/