What is the best way to define object variables?

I’ve been reading some open source projects lately, and have noticed two different ways to define object variables(not sure if this is what they’re called) in their constructor function(usually object.new) when using OOP.

First method(most common)

function Object.new(arguments)
    self = setmetatable({}, Object)
    self.someVariable = true
    self.someOtherVariable = 50
    return self

Second method(???)

function Object.new(arguments)
    return setmetatable({
        someVariable = false
        someOtherVariable = 20
    }, Object)

I’m honestly wondering, is there a benefit to using one or the other? Or is it just a purely preference thing?

Both are good, but if the methods of the metatable have __newindex, option 2 is better so that it is not activated.

Personally I think it is better not to use metatable if it is not necessary, so you can use it later

local Methods = {}
function Methods:hey()
	print("Hi:", self.You)

local Constructor = {}
function Constructor.new(You: Player)
	local self = table.clone(Methods)
	self.You = You
	return self
return Constructor

After creating it, you can add or remove the metatable without problems. Also, the type will look cleaner, since only the assigned ones will appear


The first method is typically used because it is easier to read, since the other methods follow the same structure (usually).