arrays - 数组上的 Lua 展开运算符

标签 arrays lua spread

当你将变量传递给函数时,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/

相关文章:

r - tidyr - 展开多列

c++ - 调整大小时数组 "breaks"

javascript - 从 json 数组获取值

Lua:如何在所有表上创建自定义方法

sorting - Lua 按属性排序表

python-3.x - 在 Pandas 中旋转时遇到麻烦(在R中传播)

python - 与 Numpy 不同,Pandas 似乎不喜欢内存步幅

c - 需要验证以创建连续数组

lua - 在另一个协程中运行 Tarantool Lua 函数

jquery - CSS3 - 仅使用 jquery 缩放框阴影