Lua 函数处理 vararg 参数时只处理了第一个参数

我试图进行一些棘手的记录,但不明白为什么 ... 只处理调用函数中的第一个参数

我有这个函数

local logger = function (name, ...)
    -- 期望在这里处理表,但实际上没有处理。
    print("[" .. name .. "] log called with " .. ...)
end

return setmetatable({}, {__index = function(self, name)
    local log = function(...)
        return logger(name, ...)
    end
    self[name] = log
    return log
end})

它是这样调用的

local testf = require "test_log"["TestA"]

testf("TestB", "TestC")
testf("TestC", "TestB")

但是却得到了这样的结果

[TestA] log called with TestB
[TestA] log called with TestC

我的问题是我不能从 testf 函数得到第二个(和后续的)参数,也不知道为什么。

提前感谢!

点赞
用户2328287
用户2328287

你的代码仅使用第一个参数

local s = ''
for i=1,select('#',...) do s = s .. select(i, ...) end
print("[" .. name .. "] log called with " .. s)

另外,你可以使用s = table.concat({...}),但如果可变参数包含了nil值,它会产生不同的结果。

2020-03-20 08:49:20
用户4984564
用户4984564

错误信息:

你不能连接 ... 因为它并不是一个值。相反,Lua只取列表中的第一个值。

如果你想连接多个值,首先使用 table.concat

local concatenated = table.concat({...})

如果你今天感觉特别聪明,也可以像这样做:

local logger = function (...)
   print(string.format("[%s] log called with"..string.rep(" %s", select("#", ...)), ...))
end
2020-03-20 09:43:54