Requiring Module Multiple Times

Is it bad to require modules multiple times?

I know you can just save it as an upvalue, but just focus on the question please.

2 Likes

Modules are designed to be required multiple times. The code only runs once, so it’s a lot more convenient for something like that. That being said though, context is important - if it’s for a single script for example, it’s much better to store it in a local variable and reference it from there (so it doesn’t go through the process every time)

2 Likes

I have a framework system where I save the “object modules” (OOP) with only a reference to them, not requiring them.

All my modules in my game are connected via setmetatable.

Whenever i need a module i would do something like

--Infected Handler Service Module
require(self.SharedModules.Infected.Civilian).new()

dont know if it’s bad practice or now

Imo, it’d be better if you set them up as local variables at the top of your script. The way I like to do it is to define my services, game structure, constants, and follow all that up by the modules I need to use. It helps make the code more readable and if you decide to change the structure, you only have the one reference to it.

Also saves on all the extra require() calls you’d be making which are unnecessary which’ll at least give you a marginal boost to how fast it runs.

I think i can’t use “self” unless i call a method under the object, so how am i suppose to save it as an upvalue?

Oh, I missed that. In that case I’d store it under the object when you do your constructor - just set it as one of your properties, then access it from there

That’s currently what I’m doing, if I’m understanding what you’re saying

you mean

local  MODULE

function Object.new()
MODULE = require(self.Modules.SomeModule) 
end

or

function Object.new()
local MODULE = require(self.Modules.SomeModule) 
end

Oh you mean liek this

function Object.new()
local self = {}
setmetatable(self, Object)
self.MODULE = require(self.Modules.SomeModule) 
return self
end

so the object’s other methods can use it

It’d depend on context.

If self.Modules.SomeModule would change based on which object you’re inside of (as in, one Object.new() would vary from another), then I’d put it on the object itself like you’re doing in that second one.

Otherwise, if the Object instance isn’t going to affect it, then I’d put it up at the top like your first one. It makes more of a point of saying that it should be the same across every instance.

But yeah, either way would be fine and that’s usually the way I go about doing it myself.

this is using “require” everytime the object is instantiated. I’m guessing that’s okay?

require caches its result the first time you call it.

-- ModuleScript
print("hello")
return true
require(script.ModuleScript)
-- prints hello
require(script.ModuleScript)
-- no print

So it’s perfectly fine to require a module multiple times.

9 Likes