Why should we bother even using metatables?
This really comes down to your preference; whether you prefer readability, maintainability, performance, etc. However, metatables can really help you do repetitive tasks along with a more syntatic sugar feel. (in my opinion)
Metatables can be substituted with regular functions, but with the downside of having to call it manually.
Metamethods can mimic the behavior of getters and setters (specifically the __index and __newindex metamethod)
â €This topic is still a work-in-progress.
There shall be more metamethod applications added in the future. If there’s any mistakes I made, please correct me as I am not an expert at this. I hope that this topic can help people understand the usage of metatables and its incredible versatility.
Pros and cons of using metatables
- Pros:
- Convenience
- Versatility
- Capabilities
- Cons:
- Memory & Performance overhead
- Complexity
- Maintenance
- Ambiguity
Useful metamethods applications
__index (getter)
The most frequent use for this is to set __index
to another table to be able to “combine” the two tables.
However, It also can be set to a function. In which the function will be fired whenever an Index is not found.
The code above is an example of using __index
to program a getter behavior. In which it doesn’t really exists, but when you index a non-existent key; It will run the function every single time
Which is a beneficial behavior to have! If you have a constantly changing reference value that you need to track off, you’d need to update the value to sync correctly with the reference value. But with __index
, you can just let it come to life!
Here is another example, with slightly more values.
The code above has an
Costs
table, programmed to have getters of G, H, and F. These values are frequently used in an A* algorithm, so it is good to have them easy to access.
In the __index metamethod, you can index another non-existent value, which will run another instance of the function. However, be careful using this, as you this can lead to a C-Stack overflow. To bypass the __index
metamethod, you can use rawget
.
__newindex (key-freezing)
The __newindex
is similar to __index
, but the only difference being __newindex
fires whenever a new key/index is added. You can use this to do stuff such as key freezing
The code above “freezes” the key “c”, making it immutable. It’s important to do rawset(t, k, v)
instead of t[k] = v
inside of the __newindex
metamethod. If we did t[k] = v
, that’ll cause another C-Stack overflow. So to bypass the __newindex
metamethod, we can use rawset