I am trying to set default value of parametr in function. How to do it?
The only way to do this in lua is to assign a value inside of the function if the parameter is nil.
function a(par)
if par == nil then
par = defaultValue;
end
end
The simplest way of doing this is by using the or operator. Here’s an example:
local num = 0
local function increment(inc)
local inc = inc or 1
num = num + inc
end
inc() -- 1
inc(3) -- 4
inc() -- 5
Basically what above explained, this does it similarly but in a more readable fashion. It picks the non-nil operand (items before and after the or) to use here.
Careful there; this might not give intended results if the passed parameter is false
in a function that takes a bool or such.
Also, you don’t need the local
keyword again, since parameter names count as locals.
That won’t be a problem when Typed Lua comes out. That is unless you’re referring to the or
trick, which would be understandable because the false value would fall through.
In this specific example, I’m not type checking the parameter so it would fail if an invalid type were passed. In the case of a boolean expression, what I normally do is hold the flag in the function itself and change it based on the passed value if one is passed.
local function bool(boolean)
local var = false
if type(boolean) == "boolean" then
var = boolean
end
end
It’s probably unnecessary overhead since it’s creating a second variable and throwing away what’s passed in the function if any is.
Is this because of the way arguments are treated or because the function itself is prefixed with local? If the variables are already treated as local, am I just variable shadowing with a new one?
Yes. It has nothing to do with the function name or declaration; parameters are always treated as local names in the function scope.