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 .
There exists one more strict method if you want to be able pass nil
as argument(eg you want distinguish foo(1,2,nil)
and foo(1,2)
)
function foo(...)
local n,x,y,z = select('#', ...), ...
if n < 3 then z = default end
if n < 2 then y = default end
if n < 1 then x = default end
-- here x,y or z can be nil
...
end
But you have to be shure you know what you doing because it may be not expected behavior for users of your function.
This should work as expected:
function foo(x, y, z)
x = (x == nil) or x
y = (y == nil and 1234) or y
z = (z == nil and "default") or z
print(x, y, z)
end
> foo()
true 1234 default
> foo(false, false, "me")
false false me
> foo(nil, 50, "me")
true 50 me
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.