Creating global variables using ModuleScripts

Hey developers!

So I’m trying to create global variables without using _G. I heard that this would be done using a ModuleScript. Though, how would I create this? I did already brainstorm a bit myself:

--Script--
local gv = require(path)

gv.example.Color3 = Color3.fromRGB(0, 0, 0)

--ModuleScript--
local module = {}

module.example:Connect(function()
    return path
end)

return module

Is this the correct way? If not, what is? Any help would be highly appreciated.

Have a nice day!

The modules are to store whatever you want.
To determine something “global” it would be better to place a module called “Global”.
Personally, I would use it for functions like automatic welds and for information.

Module:

local Global = {
	Functions = {
    	Weld = function()	
		end
    },
    Information = {
	    Apple = 10
    },
    Colors = {
	    Red = Color3.fromRGB(255,0,0)
	}
}

return Global

Script:

Module = require() -- Module location
Module.Colors.Red
Module.Functions.Weld()
Module.Information.Apple

It is not necessary to create a function in the module to request a direct data from the table.

If you want to modify it, you must do it from the server if the module is for clients and server.
If it is only for the client, it will not be necessary for the server to modify it.

1 Like

Would I use it like this (for path variables and stuff)?

--Script--
local gvm = require(path)

gvm.example.CanCollide = false

--ModuleScript--
local module = {example = path}

return module

Yes it works, to avoid errors, example must be an object, it doesn’t matter if it has a defined parent.

1 Like

I think you mean path should be something like script.Parent? If so, yes I understand, this was just an example.

Edit reversed.

Here it must be an Instance.

{example = part}

I am confused because in both it says path xd

1 Like

I think you mean it should be:

--Script--
local gvm = require(game.ServerScriptService.GlobalVariables)

gvm.example.CanCollide = false

--ModuleScript--
local module = {example = game.Workspace.Part}

return module
1 Like

Yup ^ - ^

padding to write, blah xd

1 Like