Joe Huang
Joe Huang

Reputation: 6560

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?

Upvotes: 9

Views: 7748

Answers (2)

J. Wesley
J. Wesley

Reputation: 11

You want to do this:

function print (...)
    for i=1, #arg do
        local v = arg[i]
        printResult = printResult .. tostring(v) .. "\t"
    end
    printResult = printResult .. "\n"
end

In Lua, pairs will ignore nil and ipairs will stop the for loop when it finds nil.

Upvotes: 0

Aadit M Shah
Aadit M Shah

Reputation: 74204

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.

Upvotes: 10

Related Questions