Help with your scripting

The .__index Metamethod

The .__index Metamethod

Postby Shando » 23 Mar 2015, 02:32

Hi all,

With the latest update came the ability to use the sky.include(filename) function :D

If you have taken a look at the "Base Classes" samples provided in the Asset Library, then you've probably seen this strange looking line of Lua:

Code: Select all
EntityBaseClass.__index = EntityBaseClass


and wondered what it means??

Basically, .__index is what Lua calls a "metamethod". Whenever you attempt to access an absent field in a Table, Lua doesn't just return a nil value, it actually looks for this metamethod first, and gets the result from it (if it exists).

The use of the __index metamethod for inheritance is so common that Lua provides a shortcut. Despite the name, the __index metamethod does not need to be a function: It can be a table, instead. When it is a function, Lua calls it with the table and the absent key as its arguments. When it is a table, Lua redoes the access in that table.

(from http://www.lua.org/pil/13.4.1.html)

This functionality allows the creation of a "prototype" Table that can be "inherited" by other Tables. This can lead to a long chain of Tables that "inherit" from the previous one in the chain (just be careful the chain doesn't get too long, as it can be slow).

An example of how to use this is on the lua-users wiki:

http://lua-users.org/wiki/InheritanceTutorial

Hope this helps

Shando
Ryzen 7 4800H 16GB GTX1650 Win 11 64
Love, Hope, Strength http://www.lovehopestrength.co.uk
User avatar
Shando
Skyline Moderator
Skyline Moderator
 
Posts: 560
Joined: 06 Mar 2013, 22:35
Location: Moffat Beach, Queensland
Skill: Programmer
Skill: Scripter
Skill: Level Designer

Re: The .__index Metamethod

Postby SolarPortal » 23 Mar 2015, 10:19

nice write up on that shando :)
Skyline Game Engine - Lead Dev.
Please provide as much info as possible when asking for help.


Specs: OS: Win 10 64bit, CPU: Intel i7 4770 3.4ghz x 4 core(8 threads), GPU: Nvidia GTX 1060 6GB, Ram: 16gig DDR3, Windows on 250gb Samsung Evo 860

Twitter: @SolarPortal
Instagram: @SolarPortal
User avatar
SolarPortal
Skyline Founder
Skyline Founder
 
Posts: 3631
Joined: 29 Jul 2012, 15:56
Location: UK
Skill: 3D Modeller
Skill: 2D Artist
Skill: Programmer
Skill: Level Designer


Return to Lua Scripting

Who is online

Users browsing this forum: Google [Bot] and 6 guests

cron