English What's __ and self.__index?

2 replies
Goto Page
To the start Previous 1 Next To the start
29.04.20 01:27:56 pm
Up
The Dark Shadow
User
Offline Off
Yo, as you can see the title explains what I'm asking for, What are they and why don't we use self.index instead? What's the magic with __? I always see them in objects.
29.04.20 01:45:22 pm
Up
Joghurt
User
Offline Off
here you can read something about oop in lua.
https://www.lua.org/pil/16.html
loading...
29.04.20 01:50:54 pm
Up
Masea
Super User
Offline Off
"__" actually means nothing at all, it is just there for developers to understand it is something there by default (a part of Lua itself), in case if you are going to use "index" as a key in your table. We generally put "_" (or more than just a single one) to the beginning of the variables, if we know they can conflict with something else later on.

"__index" key works just like any other key would work if you put it within a regular table, but it is a different scenario if you put it within a table that is going to be used as a metatable. There are metamethods for metatables just for the sake of dramatically changing their behaviours, and I stress the word dramatically there. "__index" is just one of those metamethods which is, if you ask me, best for inheritance and such. It is a plain function that is triggered when a key is checked in the table, of course, if that specific table has been set a metatable with this metamethod.

It is kinda tricky to explain it but pretty sure this would tell you something: https://www.lua.org/pil/13.4.1.html

Metatables and metamethods can be hard to learn at first, but once grasped, you are going to be questioning many possibilities with them.
Create your UI easy and fast: UI Framework | Go deeper into the darkness and test your bravery: file cs2d Outlast II Modification (28)
To the start Previous 1 Next To the start