The question
I need to use two module scripts that has a third as its parent, For efficiency I would like to just have to require the top level module script instead of having to individually add each module script into a separate variable.
So is it possible to merge the two child module scripts in the parent? For efficiency I do not want to make another copy.
Example only (not tested)
module script A:-
local f = {} function f.a() print('a1') end function f.b() print('a2') end return f
module script b:-
local f = {} function f.c() print('b1') end function f.d() print('b2') end return f
Parent module script:-
local mod1 = require(script.a) local mod2 = require(script.b) -- I am not looking to create another variable e.g. local tmp = {} for I, v in pairs(mod1) do --add to tmp end for I, v in pairs(mod2) do --add to tmp end return tmp --- I do not want to make a copy as this is inefficient -- now how do I return both module script as one variable return mod1+mod2 -- example
I hope that I have managed to explain this well, pls comment if you need any more info.
Short answer: No, there is no other way.
Long answer:
If you're doing this so it looks better to other users or something and just don't want to iterate through the tables on the parent module, you can easily use the __add
metamethod on one (or both, but I recommend only Module Script A for efficiency) the tables returned by the modules.
An example is below:
Module Script A
local f = {} function f.a() print('a1') end function f.b() print('a2') end return setmetatable(f,{ -- setmetatable returns the given table __add = function(self, otherTable) local tmp = {} for i,v in pairs(self) do rawset(tmp, i, v) -- if you use i (either on table.insert or rawset), it'll be overwritten if the same key is used on another module end for i,v in pairs(otherTable) do rawset(tmp, i, v) end end })
Module Script B
local f = {} function f.c() print('b1') end function f.d() print('b2') end return f
Parent Module
local mod1 = require(script.a) local mod2 = require(script.b) return mod1+mod2 -- OR, if you want to make it shorter: return require(script.a) + require(script.b)
Hope it helps. Comment if you have any question.