Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making sense of OOP in Lua

Tags:

oop

lua

I do most of my programming in Python, and I use OOP practices for most of my projects. I recently started taking a look at the Love2D game library and engine. I managed to get some things configured, and then thought about making a GameObject class. But, what's this? Lua doesn't have classes! It has tables, and metatables, and other such things. I'm having a lot of trouble making heads or tails of this even after reading the documentation several times over.

Consider the following example:

catClass = {}
catClass.__index = catClass
catClass.type = "Cat"

function catClass.create(name)
    local obj = setmetatable({}, catClass)
    obj.name = name
    return obj
end

cat1 = catClass.create("Fluffy")
print(cat1.type)

cat2 = catClass.create("Meowth")

cat1.type = "Dog"

print(cat1.type)
print(cat2.type)
print(catClass.type)

The output of this is as follows:

Cat
Dog
Cat
Cat

What I do not understand is why changing cat1.type to "Dog" does not cause identical changes in cat2 and catClass. Does setting a metatable create a copy of the table? Google did not provide useful results (there are very few good Lua explanations).

like image 443
user3076291 Avatar asked Dec 26 '22 14:12

user3076291


1 Answers

When you index a table and a key does not exist then Lua will look to see if a metatable exists for the table. If one does then it will use the __index key of that metamethod to re-index your key.

When you created cat1 it inherited the catClass metatable. Then when you indexed type it will see that cat1 does not have a table entry called type and thus looks to the metatable to find it.

Then you set type on cat1 to Dog, which only sets the table key of cat1 itself, not the metatable. That is why when you index cat1 again for type you get Dog and not Cat.

If you go to http://www.lua.org/ there is documentation and some older copies of the Programming in Lua, written by the authors of Lua itself.

like image 191
Paige DePol Avatar answered Jan 17 '23 14:01

Paige DePol