Hey all. I am setting up an actor in my game engine with a table of options but something is not quite working when I go to set a default property if the option is missing from the table....
local function addActor1(options)
local actor = {}
actor.shrinks = options.shrinks or false
print(actor.shrinks)
end
local function addActor2(options)
local actor = {}
actor.shrinks = options.shrinks or true
print(actor.shrinks)
end |
Calling either function with a blank table for options works fine. If I call addActor1({shrinks = true}), then actor.shrinks is TRUE as I would expect. If I call the addActor2({shrinks = false}) however, actor.shrinks is still TRUE! Why is it not false?
I thought if shrink has been specified then that value would be used, and if shrink was not specified then the default TRUE would be used.
Am I missing something simple here (as per usual)??
Comments
and what you are doing is evaluating
false or true, which will always be true.
You can do such default value assignment but, not with booleans (or probably even not numbers)
you would need to explicitly check if it is nil
Oh, you also can use that
@Fyfff awesome, I'll use that since it's less code
Btw, this code will return "nil" if you don't set the "shrinks" field explicitly. If you want to have "true" when "shrinks" doesn't set you need smth like this: