Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How can a moduleScript get the script that required it?

Asked by
davness 376 Moderation Voter
8 years ago

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

Log in to vote
5
Answered by 8 years ago

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

0
Thank you very much! Saving for reference. davness 376 — 8y
0
No problem! This is probably one of my favorite questions I've answered, to be honest. TheDeadlyPanther 2460 — 8y
Ad

Answer this question