Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Lua, how to set a nil parameter to some default value correctly?

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?

like image 796
Joe Huang Avatar asked Mar 22 '15 00:03

Joe Huang


1 Answers

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.

like image 199
hjpotter92 Avatar answered Sep 28 '22 06:09

hjpotter92