Forum

> > CS2D > Scripts > What's __ and self.__index?
Forums overviewCS2D overview Scripts overviewLog in to reply

English What's __ and self.__index?

2 replies
To the start Previous 1 Next To the start

old What's __ and self.__index?

The Dark Shadow
User Off Offline

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

old Re: What's __ and self.__index?

Masea
Super User Off Offline

Quote
"__" 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.
To the start Previous 1 Next To the start
Log in to reply Scripts overviewCS2D overviewForums overview