Understanding OOP in Lua

I do most of my Python programming, and I use OOP methods for most of my projects. Recently, I began to study the library of games and the Love2D engine. I managed to tweak some settings, and then thought about creating a GameObject class. But what is it? Lua has no classes! It has tables, meta tags, and other similar things. I'm having problems with heads or tails, even after reading the documentation several times.

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 result of this is as follows:

Cat
Dog
Cat
Cat

I don’t understand why changing cat1.type in "Dog" does not cause the same changes in cat2 and catClass. Does metadata create a copy of the table? Google did not provide useful results (very few good Lua explanations).

+4
2

, , Lua , . , __index .

cat1, catClass. , type, , cat1 type , , , .

type cat1 Dog, cat1, . , cat1 type, Dog, Cat.

http://www.lua.org/, Lua, Lua.

+6

. setmetatable. - , .

create ( {}), . , , "" 1.

, : cat1 ( mt catClass), cat2 ( mt catClass) catClass. cat1, , .


1 . Lua Metatables Tutorial; __index, metatable, JavaScript [prototype].

, , , . Lua __index , . __index , Lua , , __index.

__index - . ( __newindex, .)

+4

Source: https://habr.com/ru/post/1523757/


All Articles