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).