For Lua code below:
local function foo(x, y, z)
local x = x or true
local y = y or 1234
z = z or "default"
end
I always thought the meaning of these three lines inside the function is:
If x/y/z is nil, x/y/z is set to true/1234/"default". Otherwise, it remains whatever it is. Therefore, I have such a line in many places to set a parameter to some default value in case it might be passed into a function as nil.
However, it seems not totally correct in my experiments. I am not sure where I learnt this Lua coding concept. How to do it correctly?
The method will work as long as your boolean(?) variable x
was not initialised as false
. If you only want to use defaults against nil
values, the a or b
method is correct.
If your variable can be false
, you'd have to use a strict if-then block:
if x == nil then x = true end
You can see a few more methods/examples about ternary operators on lua wiki.
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