Some questions about OOP

Hello, I’ve been trying to learn about metatables and OOP but I cant wrap my head around these:

Why do people set the __index metamethod to the table it was called in?

Something like

Inventory = {}
Inventory.__index = Inventory

Are __index’s parameters like this: (Table it was called from, value it tried to index)?

How do you use functions with : and self when you create a class?

If you specify a __newindex metamethtod, does that mean you have to specifically code what it has to do or does Lua still take care of automatically indexing the new value like a normal table?

What are some good use cases for OOP? I’m trying really hard to understand this, but then again I don’t know when I would use it

Fun question: Is there any way to add your own custom highlighted keywords, like game and workspace? I feel like this would be really useful when you’re making your own classes.

Yeah, it’s just the table that was indexxed and what it was indexxed with.

__index can be a function or a table. If it’s a table, it’ll grab from the __index table if it can’t find anything in the main table. People use Inventory.__index = Inventory when their Inventory class has all the class functions they want specific instances of that class to inherit. Doing something like setmetatable(class, Inventory) would then allow class to inherit those functions.

__newindex is just a fallback for when there’s no value already at that position. For example, if you do local x = {1, 2, 3}, set a __newindex metamethod, and then do something like x[1] = 2, the function won’t be called. If you tried x[6] = 3 in that situation, it’d set the value of x[6] to whatever __newindex(table, index, value) returns. You can use rawset and rawget to bypass __newindex and __index, respectively.

It’s just a specific way people like to organize their code. There’s no specific situations you have to use it in, it’s just one way that some people like to organize their code using. Plenty of games are perfectly fine without using any OOP at all (aside from the built-in Roblox classes, of course).

Nope. The syntax highlighter isn’t customizable at all.


Since a lot of these questions were about metamethods rather than OOP, I’d also recommend checking out the wiki article on those if you haven’t already:

5 Likes

Great explanations, I’ll look at the article later.
What about my question on functions and self though?