Requiring Module More Than Once


#1

Is it “bad” to require a module more than once?

I have a reference to module scripts in my framework but every time I need it I would require it.

for example.

local specModule = require(clientFrameWork.Modules[moduleName])
local newObj = specModule.new()

I would do this multiple times.


#2

If anything, the point of ModuleScripts is to use them more than once.


#3

Should I save a reference to the framework table already required?

So I can do this:

local newObj = clientFrameWork.Modules[moduleName].new()

instead?


#4

There’s no point–Roblox caches module results for you.


#5

I feel like requiring a module more than once is redundant, bc the code written directly in the module script only runs when you require it once.

I mean, I can use the functions repeatedly, but the code that’s not part of the module scripts’ table only run once. I feel weird about this.


#6

What’s to feel weird about? The point of require is to get the return value of a module. If it reran its entire code every time, it would be slower, more memory inefficient, and less useful to developers.


#8

I do this in Studio a fair bit! When I’m testing modules from the command line, I often use my own ‘unique require’ function to make sure Studio doesn’t cache the return value and runs the most up to date version of the code.

Here’s the implementation:

local function urequire(module)
    assert(typeof(module) == "Instance" and module:IsA "ModuleScript", "urequire only works with module script instances")
    -- create copy of module
    local newModule = module:Clone()
    -- swap module with cloned version
    newModule.Parent = module.Parent
    module.Parent = nil
    -- run module
    local value = require(newModule)
    -- put old module back and destroy cloned module
    module.Parent = newModule.Parent
    newModule:Destroy()
    -- done
    return value
end

This code will replace the module script with a cloned version, require the newly cloned version, then put the old module back, and return the values from require().


#9

That seems extraneous, I’ve always just done require(module:Clone())?


#10

That works for most cases, but my method ensures that script.Parent works as expected, including references back to the instance from ancestors.


#11

whats wrong with my way


#12

Nothing’s wrong with your method :slight_smile: