Hello, I don’t exactly have a issue with my code I just want to make sure I understand requiring modules correctly before going too deep into it. Say I had a module like this:
local PartsList = {}
local module = {}
function module:AddParts(newPart)
table.insert(PartsList, #PartsList + 1, newPart)
end
function module:GetParts()
return PartsList
end
return module
which I published as a model (ex: asset ID 123456)
then I had a script1 requiring the asset ID and calling the AddParts(Instance.new("Part")) function
then I had a script2 requiring the asset ID and calling the GetParts() function
Would I be able to obtain the same parts list as it’s populated from any script requiring the asset ID within the scope of the server? I have a feeling that there is always only one instance of a module, but it also seems like that might not be the case when requiring.
Script1 and Script2 would see the same parts list. When you require the module by asset ID, it behaves the same way as a ModuleScript in your game’s hierarchy. The only difference is where its being fetched from and what environment has access to it (only the server will).
Think of require being memoised; upon first require regardless of how, your module’s return is cached into a big array. Afterward, subsequent calls of require return that cached result in that array.
Your feeling that there’s always only a single instance of a module is correct. Require doesn’t suddenly return something new in any case - once a module’s been required, it’s loaded into the game. Other requires return the same thing, always.
@colbert2677 thanks for the response. Memoization for modules makes sense, I can imagine how caching modules can significantly speed things up and reduce memory.
So since the module has a scope of only the server it’s required on, I don’t have to worry about multiple servers accessing the same module contents?
Other servers will not receive the same copy of a module. Every instance of a place receives a fresh copy of the uploaded module, which consists of the stock code you supply.