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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With