Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

lua

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?

like image 260
Joe Huang Avatar asked Mar 02 '14 04:03

Joe Huang


People also ask

How do you find the variable number of arguments?

A variable-length argument is specified by three periods or dots(…). This syntax tells the compiler that fun( ) can be called with zero or more arguments.

How do you get args in Lua?

To pass arguments into Lua, the script name and arguments must be enclosed within double quotes. The arguments are stored within the arg variable in Lua, which is a table of strings.

How do you pass arbitrary number of arguments?

What are Arbitrary Arguments (*args)? If the number of arguments to be passed into the function is unknown, add a (*) before the argument name. Lets say you want to create a function that will sum up a list of numbers. The most intuitive way will be to create that list and pass it into a function, as shown below.


1 Answers

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.

like image 183
Aadit M Shah Avatar answered Nov 03 '22 01:11

Aadit M Shah