#Quick questions about metables

1 messages · Page 1 of 1 (latest)

strong orbit
#

Hey i was just wondering can someone explain to me howw the __index function in metables truly works ? Does it just fires EVERYTIME i index something in my table or only when i index something to initialize a variable ?

#

myvariable = table[index] works ?

#

table[index] +=5 works ?

knotty void
#

would like an explanation on this as well, don't mind this message

exotic valley
#

Only if its nil :) but yes it works everytime you index it

rocky halo
#

Basically you know when you do something like humanoid:TakeDamage

#

If you have a table and uou create a function

#

You can assign that to the table

#

For example if the table = player = {health = 100}

#

And hsve this function

#

Local function toonehp(amount)

#

Then you can do metatable(player,__index = tooonehp)

#

And you can fire this:

#

Player:toonehp(99)

#

Keep in mind that when using : the self is already a variable and is set as the table (in this case the player)

rotund herald
# rocky halo Player:toonehp(99)

close but no cigar. This is not quite what the metamethod does. This can also be achieved by just adding functions to dicts:

local ExampleDict = {};

ExampleDict["ExampleMethod"] = function() return "ExampleString" end

print(ExampleDict:ExampleMethod())

anyways, @strong orbit @knotty void metatables are just a way to connect metamethods to a table.
Metamethods are internal events that listen for certain actions to work. E.g. __index fires when you index a table key that does not exist in said table (which is what roamer used to then connect that to another table), but there are many other metamethods, which you can read about here https://create.roblox.com/docs/luau/metatables#metamethods

There are also some optimization techniques that use metatables, to simply attach references to different tables to a table, instead of copying the entire table for every table that has to keep those references

Metatables attach powerful metamethods to tables, allowing for manipulation like indexing, addition, and concatenation.

rocky halo
#

Wth

#

Wheres the metatable function

rotund herald
rocky halo
#

No way

#

Thats cool

rotund herald
#
-- alternative (and more common) way of adding functions to dicts
function ExampleDict.ExampleMethod2()
    return "ExampleString2"
end
#

Both work fully without metamethods

#

;compile

local ExampleDict = {};

ExampleDict["ExampleMethod"] = function() return "ExampleString" end
function ExampleDict.ExampleMethod2()
    return "ExampleString2"
end

print(ExampleDict:ExampleMethod())
print(ExampleDict:ExampleMethod2())
grizzled rampartBOT
#
Program Output
ExampleString
ExampleString2

rotund herald
#

The reason why folks use index for this effect is to save on ram. As then you can just save a singlular reference to the functions instead of having to create new functions for every table (purely in memory, not in the script itself of course)