简体   繁体   中英

Lua process vararg in function process only 1st parameter

I'm trying to get a bit tricky logging, but can't get why ... processing only 1st parameter in a function called

I have this function

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})

And how it's called

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

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

But getting back this result

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

The problem I can't get 2nd (and further) parameters from testf function and can't get why.

Thanks in advance!

Your code uses only first parameter

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

Also, you can use s = table.concat({...}) , but it will produce different results in cases where vararg contains nil values

You can't concatenate ... because it's not a value. Instead, Lua just takes the first value of the list.

If you want to concatenate more than one value, use table.concat first:

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

You could also do something like this instead if you're feeling particularly smart today:

local logger = function (...)
   print(string.format("[%s] log called with"..string.rep(" %s", select("#")), ...))
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM