Hi,
(Sorry for the basic question, but) how do I use optional parameters?
How do I handle them inside the called function?
Thanks,
Pedro
Hi,
(Sorry for the basic question, but) how do I use optional parameters?
How do I handle them inside the called function?
Thanks,
Pedro
read lua manual, that will help.
All parameters are optionnal in a function call. Example:
you have defined f(a,b,c)
.
then if you call f(3) -> a=3, b=nil, c=nil
and there is no error (if you manage the nil case in your code).
In your function you can write this to manage default values:
function f(a,b,c)
a = a or 0
b = b or 4
c = c of 25
....
@pvchagas Here’s another way to handle a different amount parameters.
function setup()
para("zxcvb","qwerty")
para("a","b","c")
para(5,4,3,2,1)
end
function para(...)
print("\
"..arg.n.." parameters")
for z=1,arg.n do
print(arg[z])
end
end
@dave1707: the implicit ‘arg’ is actually deprecated in Lua 5.1. The preferred method is the select
function (reference: http://www.lua.org/manual/5.1/manual.html#pdf-select )
function setup()
para("zxcvb","qwerty")
para("a","b","c")
para(5,4,3,2,1)
end
function para(...)
local nargs = select("#", ...)
print("\
"..nargs.." parameters")
for z=1, nargs do
local n = select(z, ...)
print(n)
end
end
This method is also less expensive, because it does not need to create a table containing the arguments under the hood just to use them (whereas when the implicit ‘arg’ table is used in a function, a new table must be instantiated for functions that uses it).
If you actually want to unpack your variable arguments into a table, you can do this:
function setup()
para("zxcvb","qwerty")
para("a","b","c")
para(5,4,3,2,1)
end
function para(...)
local args = {...}
print("\
"..#args.." parameters")
for z=1,#args do
print(args[z])
end
end