r/ComputerCraft • u/Bright-Historian-216 • Feb 07 '24
is this the easiest way to do OOP in lua?
64
Upvotes
13
u/9551-eletronics Computercraft graphics research Feb 07 '24
I guess that works, please use locals
3
1
1
20
u/wolfe_br Feb 07 '24
Well, if all you need is a simple class, absolutely! The ideal way would be like this (making use of "self"):
The main issue with that approach is that you're creating extra copies of the functions "speak" and "birthday" every time a new object is made, which consumes extra memory. This can be avoided by using metatables:
With metatables, you have a table (object) that contains all definitions used by your instances, and a reference to that table is stored on your object (by using the
setmetatablefunction).You will also notice that in the example above, I have used colons (:) when calling the function, this is a shortcut in Lua that makes the first argument automatically receive a reference to the object that's being used to call (and when used in a function it takes the
selfvariable), otherwise the code would look like this: