Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How can a moduleScript get the script that required it?

So this is a generic question. So let's suppose we have an active moduleScript:

local module = {}
	function module.f()
		print("mekool")
	end
return module

and a Script requires it:

require(game.ServerScriptService.ModuleScript)

Is there a variable that represents the script that required the module, so we could make something like:

local module = {}
	local scriptthatrequiredthis = ?
	function module.f()
		print(scriptthatrequiredthis:GetFullName())
	end
return module

(Since of course the keyword script redirects to the module itself)

Anyways, thank you, your help is very appreciated!

1 answer

✓ Accepted answer

No, ModuleScripts have no in-built variables or information. This can be accomplished through two other ways.


Method 1: Parameters

You can call functions in ModuleScripts and give them parameters. From this, we can simply just use the parameter;

ModuleScript

local module = {}

function module.f(requirer)
	print(requirer:GetFullName())
end

return module

Requirer

local module = require(game.ServerScriptService.ModuleScript)
module.f(script)

Method 2: Setup

An alternate, and slightly more advanced method is to perform a setup of sorts, using a function in the ModuleScript. This method may cause errors, especially in terms of nil values, if the proper precautions are not performed.

ModuleScript

local module = {}
local requirer

function module.setup(scriptThatRequired)
	requirer = scriptThatRequired
end

-- Putting a repeat/while loop here would stop the code, including the script that required it, so therefore it would never get to the setup point

function module.f()
	if not requirer then -- If the script has not been setup when the function is called
		repeat wait() until requirer
	end
	print(requirer:GetFullName())
end

return module

Requirer

local module = require(game.ServerScriptService.ModuleScript)
module.setup(script)
module.f()

Hope I helped!

~TDP

2 comments

0

Thank you very much! Saving for reference.

0

No problem! This is probably one of my favorite questions I've answered, to be honest.

This discussion is preserved as it was. New answers, comments, and votes are closed.