I trying to learn how to do OOP in Lua and while I did find working solutions, I don't actually understand how it works. So I am trying to better understand why and how things works in Lua. But I have a hard time with it.
Could someone please help me explaining the relationship between the .__index meta method and the setmetatable() method?
I did read documents and watched tutorial videos including the one from Jeeper but I just don’t understand it.
This is what I am trying to do to help me understand:
I have 2 tables
Code: Select all
human = {age = 12}
student = {grade = 5}
student.__index = student
setmetatable(student,human)
function love.draw()
love.graphics.print(""..student.age)
end
I understand I set human as the parent table of student and so student can access the age property of human.
What I don’t understand however is that I need to set the .__index of student to point to it self in order for this to work. I simply can not figure out why do I have to do this.
Some tutorials saying if I would do
student.__index = human
On it’s own it would point to the table human and I could call student.age but it is not true. For this to work I need to setmetatable(student,student) and then I can call student.age which is just even more confusing.
Could anyone please explain it in layman's terms what is happening here, what is the connection between .__index and setmetatable()?
Thank you in advance.