Requiring a module by asset ID and variable storage

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)

function module:GetParts()
    return PartsList

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("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.

Why didn’t you test it first? I doubt that it would get the same parts list, otherwise I think the module is cached in the server after requiring.

I’ll check later today.

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.

I think even if I spent the time to write the code and test this I still wouldn’t get a concrete understanding of the way things worked.

@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.