Lua 函数处理中的可变参数仅处理第一个参数
Lua process vararg in function process only 1st parameter
我正在尝试进行一些棘手的日志记录,但不明白为什么 ...
只处理名为
的函数中的第一个参数
我有这个功能
local logger = function (name, ...)
-- Expected table processing here, but no.
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
函数中获取第二个(以及更多)参数,也不知道为什么。
提前致谢!
您的代码仅使用第一个参数
local s = ''
for i=1,select('#',...) do s = s .. select(i, ...) end
print("[" .. name .. "] log called with " .. s)
此外,您可以使用 s = table.concat({...})
,但在 vararg 包含 nil 值的情况下会产生不同的结果
您不能连接 ...
,因为它不是一个值。相反,Lua 只取列表的第一个值。
如果要连接多个值,请先使用 table.concat
:
local concatenated = table.concat({...})
如果你今天感觉特别聪明,你也可以这样做:
local logger = function (...)
print(string.format("[%s] log called with"..string.rep(" %s", select("#")), ...))
end
我正在尝试进行一些棘手的日志记录,但不明白为什么 ...
只处理名为
我有这个功能
local logger = function (name, ...)
-- Expected table processing here, but no.
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
函数中获取第二个(以及更多)参数,也不知道为什么。
提前致谢!
您的代码仅使用第一个参数
local s = ''
for i=1,select('#',...) do s = s .. select(i, ...) end
print("[" .. name .. "] log called with " .. s)
此外,您可以使用 s = table.concat({...})
,但在 vararg 包含 nil 值的情况下会产生不同的结果
您不能连接 ...
,因为它不是一个值。相反,Lua 只取列表的第一个值。
如果要连接多个值,请先使用 table.concat
:
local concatenated = table.concat({...})
如果你今天感觉特别聪明,你也可以这样做:
local logger = function (...)
print(string.format("[%s] log called with"..string.rep(" %s", select("#")), ...))
end