Search code examples
lua

In Lua, how to get all arguments including nil for variable number of arguments?


For variable number of arguments, here is an example from lua.org:

function print (...)
    for i,v in ipairs(arg) do
        printResult = printResult .. tostring(v) .. "\t"
    end
    printResult = printResult .. "\n"
end

From the sample code above, if I call

print("A", "B", nil, nil, "D")

only "A" & "B" are passed in, all arguments since the first nil are ignored. So the printing is result is "AB" in this example.

Is it possible to get all the arguments including nils? For example, I can check if an argument is nil, and if it is, I can print "nil" as a string instead. So in this example, I actually want to print

AB nil nil D

after some modification of the code, of course. But my question is... above all, how to get all the arguments even if some of them are nils?


Solution

  • Have you tried:

    function table.pack(...)
        return { n = select("#", ...); ... }
    end
    
    function show(...)
        local string = ""
    
        local args = table.pack(...)
    
        for i = 1, args.n do
            string = string .. tostring(args[i]) .. "\t"
        end
    
        return string .. "\n"
    end
    

    Now you could use it as follows:

    print(show("A", "B", nil, nil, "D"))
    

    Hope that helps.