Lua 数组上的展开运算符

Lua 在你将变量传递给函数时,是否有展开运算符?

例如,我有一个数组 a,我想将其传递给其他函数,比如 string.format。如果我只是简单地执行 string.format(a),那么我得到

bad argument #1 to 'format' (string expected, got table)

我尝试过 local f, e = pcall(string.format, t),但没有什么运气。

点赞
用户9622872
用户9622872

Kousha。我在摆弄时偶然发现了你可能会感兴趣的一个函数。

在Lua5.1中,unpack作为一个全局函数是可用的。在5.2中,他们将其移动到table.unpack,这更有意义。您可以使用以下类似的代码调用此函数。string.format只接受一个字符串,_除非您在格式参数中添加更多内容_。

--你对我的问题的评论让我意识到你完全可以用unpack做到这一点。
t = {"One", "Two", "Three"};
string.format("%s %s %s", table.unpack(t)); -- One Two Three

- 使用您的实现,
- 我认为您可能需要增加args的长度。
local f = "Your table contains ";
for i = 1, #t do
    f.." %s";
end
string.format(f, table.unpack(t));
2018-05-23 01:17:06