I understand how metatables and metamethods work, but whenever I am creating stuff I never see any practical uses for them or how I could put it into my game.
Could someone give me an example of a block of code that shows good application of a metamethod?
Thanks 
1 Like
Metatables alter the behavior of how tables should act in Lua.
For instance, we can lock a table to be read-only with by changing the behavior of __newindex
for when we want to index anything new to the table, it will just throw an error instead, while indexing preset values will still work.
Immutable module:
local Immutable = {}
Immutable["Bob"] = "Hi"
local Metatable = {
__newindex = function()
error("This table is immutable. It is set to be read-only.")
end
}
return setmetatable(Immutable, Metatable)
Some script using Immutable:
local Immutable = require(PathToImmutable)
print(Immutable["Bob"]) --> Hi
Immutable["Rory"] = "Hello" --> Error: This table is immutable. It is set to be read-only.
Immutable would block mutations from occurring in the table, in this case any new index from the __newindex
metamethod would just throw an error.
Several use cases:
-Using programming paradigms to change the overall workflow. Such as MVC, OOP, ECS, etc…
-Custom class constructors, such as your own Vector class for handling complex objects.
-Performing arithmetic on tables
There are so many other cases and tutorials on using Metatables around and about in the Devforum already.
4 Likes