#Quick questions about metables
1 messages · Page 1 of 1 (latest)
would like an explanation on this as well, don't mind this message
Only if its nil :) but yes it works everytime you index it
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)
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
In the code? there is no need for it. I just added the function straight into the dict instead of into a table, then making an index nil reference said table
-- 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())
ExampleString
ExampleString2
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)