From my understanding, one can use the or
operator to assign something to another value if the first value is nil
. This allows us to create optional parameters for classes.
local x = nil or 5
print(x) -- 5
But if I’m making a class where one of its constructor parameters is a boolean and pass it in as false
, the class attribute would default to the second possible value instead of staying as false
.
local class = {}
class.__index = class
function class.new(bool)
local self = {}
self.Var = bool or true
return setmetatable(self, class)
end
In the above case, if bool
were false
, self.Var
would be set to true
even though it shouldn’t. To bypass this, I had to do something like this instead:
self.Var = bool
if self.Var == nil then
self.Var = true
end
This can get pretty messy fast for me because the classes I’m creating can have a lot of boolean constructor parameters, so is there better way of solving this problem?