How would you use module scripts like global variables?

I recently made a topic about it if _g is better than module scripts, and a lot of people said module scripts were better. However, while they explained why, I couldn’t understand how to use it in a way that would work like _g

1 Like

ohhh i tried that it didnt go out as good i suggest not doing this using module scripts as a variable storage is a bit inadequate

I have done some researching on google and have found that ModuleScripts are better because _G although it can be used on server and client, any variables from _G that’s in a server script can’t be passed to the client. ModuleScripts are faster than _G and isn’t recommended by Roblox. Overusing _G causes lag overall ModuleScripts are just better.

all though even if you were able to user module script as a variable storage you would still need to return something liek
Var
then in scripts you would have to do
Var.Frame

Thanks! But this still doesn’t really tell me how to use it like a global variable.

why use it as a global variable are you trying to use something that might get deprecated in the future

If I understand you correctly, If you want to create a global variable for a ModuleScript you would do something like:

local module = {} 

module.VariableName = 1 -- Variable stored inside of module table inside of ModuleScript

return module

Well what I mean is like

If I set a variable in one place to false, how would I know in another script that it has been set to false (with module scripts)

are you trying to use that? serverscript to serverscript or like localscript then serverscript

ModuleScript:

local module = {}

module.VariableName = false -- Variable stored inside of module table inside of ModuleScript

return module

Script:

local module = require() -- Location to ModuleScript

if module.VariableName == false then
     -- Code here
end

You shouldn’t compare ModuleScripts with the _G table.

Whilst there are similarities, ModuleScripts are a lot more flexible and organized.
I recommend reading the article on ModuleScripts: ModuleScript

Neither ModuleScripts nor _G are “shared” between the client and server because they run separate Luau instances with various permissions; however you can run both server and client code on ModuleScripts and once they’re require(moduleScript)'d, the code only runs once and whatever was returned can be changed.

If I were to have a DaytimeCycle ModuleScript that held information about how long days should last like this:

return {
    DayLength = 10,
    EasingStyle = Enum.EasingStyle.Quad,
    EasingDirection = Enum.EasingDirection.Out,
}

If I were to require(DaytimeCycle) then change the DayLength to 20 in one LocalScript, another LocalScript that has required DaytimeCycle would see that change.

ModuleScripts also bring the advantage of organization, so you can separate each class and container into it’s own ModuleScript.

3 Likes