Easiest way to do OOP (Object Oriented Programming)

This isn’t the case, Luau has introduced an optimization on which it ‘caches’ functions if they are the same, a function can look the same and not be the same, so it’s important to understand how that works.

If you take his implementation and get two objects and compare their functions together, it will, infact, return true.

Your ‘test code’ somewhat breaks this optimization, my guess is that it’s because the functions are declared inside a table construct, and not after a table is created.

For example, in this case, it does return true.

local function Class()
	local self = {
		_number = 0
	}
	
	function self:Add(num)
		self._number += num
	end
	
	return self
end

print(
	Class().Add == Class().Add
)

Something to note is that using this method does make the creating of the object a lot slower, and it does use some more memory, which is the memory needed to be allocated for the extra entries for these functions in the table, however, there are some benefits, and one of those is type satefy. It just works better with types, metatable OOP breaks with metatables from what I’ve experienced, and this method did not.

The tutorial isn’t that great, like, the example is ehh, using table.index = function() is really ugly. Also, they could’ve declared the properties (not the methods) on the table construct it self, etc, but this method in its principle is fine. AFAIK, there’s not really big performance advantages to metatable OOP, at least since well, 2021. (I have not been active basically since then) Most optimizations have to do with indexing, and I believe it’s actually faster for Luau to find the function index this way, not sure.

I actually have a community tutorial on this exact method and I’ll be tagging it here, just need to find it.

1 Like

Is there another way to create a function instead of doing table.index = function() as you mentioned on your last paragraph? Thanks!

I’m aware, I just didn’t go into that because that wasn’t the point of the post. Functionally, that’s what the __index metamethod does, and that’s how oop works.

It was test code to show how it worked, it wasn’t meant to be used at all. Just to show how it worked.

Yeah! That would be:

function table.index(...)
    return ...
end

It definitely didn’t sound like it, the entire post was directed at the fact those functions would be separate instances which isn’t the case;

I’m aware and it didn’t work as test code, it didn’t demonstrate how that would actually behave when someone were to use this method properly.

2 Likes

Oh yeah and another thing, the code shown by the OP actually does not work with function caching because the reference to self is the one created by the function so when the function is created, it’s actually different each time because it references a variable that only exists in the context of the object function being created.


4 Likes