From f3f8862402ed76b44e327fa81300b9e65541aebd Mon Sep 17 00:00:00 2001 From: Ibrahim Abdulhameed Date: Mon, 1 Sep 2025 13:09:11 +0100 Subject: [PATCH] feat: add Misc & metatables --- source/_posts/lua.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/source/_posts/lua.md b/source/_posts/lua.md index 1c785cd..779c3f0 100644 --- a/source/_posts/lua.md +++ b/source/_posts/lua.md @@ -363,3 +363,29 @@ s:byte() s:format() ``` + +## Misc + +### Meta-tables + +A metatable is simply a table with functions in it. + +```lua +mt = {} + +mt.__tostring = function() return "lol" end +mt.__add = function(b) ... end -- a + b +mt.__mul = function(b) ... end -- a * b +mt.__index = function(k) ... end -- Lookups (a[k] or a.k) +mt.__newindex = function(k, v) ... end -- Setters (a[k] = v) +``` + +Metatables allow you to override behavior of another table. + +```lua + +mytable = {} +setmetatable(mytable, mt) + +print(myobject) +```