So I’m 100% new to metatables and for my new project, I think it would be beneficial to use metatables.
I’m trying to return a table of functions when you call on the table via :Function() and return the actual settings when you call on the table using [“Key”] or just indexing it using Module.Settings.
This is like my code.
local SETTINGS = {--[[Settings]]}
local RMG = {}
RMG.Settings = {}
local SETTINGS_FUNCS = {}
local SettingsMetatable = {
__index = function ()
return SETTINGS
end,
__call = function ()
return SETTINGS_FUNCS
end,
}
function SETTINGS_FUNCS:Function()
-- Code
end
Is this possible or should I just ditch that idea altogether and not use metatables?
OOP; Object Oriented Programming, is a very powerful tool. To do this in Lua I usually do the following:
local module = {}
module.__index = module
function module.new() -- Creates a new meta table
local self = {}
... -- Any misc code you need
setmetatable(self, module)
return self
end
function module:Function()
-- This passes in self, and this code will execute based on this object.
...
end
function module.OtherFunction()
-- This does not pass in self, and is used as a global function
...
end
return module
The __call metamethod is only invoked when you attempt to call a non-function value, the __call metamethod is looked for in the value’s metatable (if it has one set) and if defined the metamethod is ran, otherwise you’ll encounter an ‘attempt to call a table value’ error.
local t = setmetatable({}, {__call = function()
print("Hello world!")
end})
t() --Hello world!
local t = setmetatable({}, {__call = function(...) --The metamethod is passed the called value (table) and any values that were passed to it.
local a = {...}
print(table.unpack(a, 2))
end})
t("Hello", "world!") --Hello world!