I’ve never used Metatables before, but I believe I should’ve learned them previously so, is what I’m doing here not the worst way you can do it? Is there anything to improve on, as the way I went about this was from methods presented years ago, so I was interested if it was any outdated.
This is a simple Module return, and print values that utilize a Metatable, or something.
local Globals = {}
Globals.TestGlobal = {}
return Globals
Test_Module
local TestModule = {}
function TestModule:PrintSomething()
print("Something")
end
function TestModule.Init()
local Metatable = {}
setmetatable(Metatable, TestModule)
Metatable.TestValue = "Test_1"
Metatable.TestValue2 = "Test_2"
Metatable.ModuleFunctions = TestModule
return Metatable
end
return TestModule
Startup_Script
local Globals = require(script.Parent.Globals)
local Test = Globals.TestGlobal
local TestModule = require(script.Parent.TestModule)
-------//
Test["NewThing"] = TestModule.Init()
-------\\ Can Call Across Multiple Scripts
print(Test["NewThing"].TestValue)
Test["NewThing"].ModuleFunctions:PrintSomething()
It’s a simple test that allows certain data to circulate through scripts using the module, it was question if the method of doing so was not outdated and wouldn’t be un-optimized or a “bad way of doing it”.
--Test module script
local TestModule = {}
TestModule.__index = TestModule --When we create a new 'object' we need to say which table it should create.
function TestModule:PrintSomething()
print("Something")
--you could add this line
print(self.TestValue)
end
function TestModule.Init()
local Metatable = {}
setmetatable(Metatable, TestModule)
Metatable.TestValue = "Test_1"
Metatable.TestValue2 = "Test_2"
Metatable.ModuleFunctions = TestModule --This is not necessary, you can use 'Metatable:Print something()', the methods defined in TestModule are available to the newly created Metatable object.
return Metatable
end
return TestModule
I use the same method of accessing metatable objects from different scripts, and I can’t think of another way which is simpler!
(Edit : to clarify language)
I forgot index, was meant to be there just thought I was wrong and made a workaround for function calling since I didn’t notice I didn’t add it. Was also looking to advance to self but I didn’t try to do it yet.