OOP Formatting Help

I recently started to learn OOP from this tutorial All about Object Oriented Programming. But, I saw that their is a lot of different ways to format your code. The way I’m currently formatting everything looks like this.

local Test = {}

Test.__index = Test

function Test.new()
	local newtest = {}
	setmetatable(newtest, Test)

	newtest.number = 5
	newtest.text = "Test"
	
	return newtest
end

function Test:DoSomething()
	print("Test")
end

return Test

I was wondering if their is a better/cleaner way to implement this.

It looks good to me. The only thing that you might change is the code style. There is an article about it for Lua/Luau in Roblox (from roblox.github.io): ‘Roblox Lua Style guide’.

1 Like

Because Lua doesn’t have true OOP support there are different methods of doing it but this one works fine as is the most common method people use.

I would recommend when creating new Test objects, set the __index of that object to itself in case you were to add objects within objects.

I personally prefer doing it this way:

function Test.new()
        return setmetatable({
                  number = 5,
                  text = "Test"
         }, Test);
end