Assigning default values for boolean constructor parameters

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?

You can do this:

self.Var = (bool == nil) or bool

If bool is nil, self.Var will be set to true, otherwise, it will be set to the boolean value provided to bool.

1 Like

Ok, great, this is perfect for defaulting to true. What about defaulting to false?

In this case, you will have flip the or configuration to the front:

self.Var = bool or (bool == nil and false)

If bool is nil, it will evaluate this to nil or false, which will return false anyway

Alright, thank you so much for your help!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.