Personally, I donāt like your solution. Adding tables just makes your code more complicated (although in some ways it can feel organised). But it is also acting like a disorganized dump for variables.
I prefer to organise things using do
blocks. If I have a single function that uses lots of variables, instead of adding them to the global scope I just stick everything in a do block, and magically it becomes organised in the human brain.
If I have issues with having too many variables, my solution usually works like this:
local GlobalVariable1
local Something do
local RelevantVariable1
local RelevantVariable2
Something = function()
print(RelevantVariable1, RelevantVariable2)
end
end
Something()
Let me break it down for you. GlobalVariable1
is a variable that gets used by multiple parts of the script. Think of a service you would use in lots of different situations (e.g. ReplicatedStorage).
local Something do
is great. It allows you to define Something
in the global scope so it can be used by other parts of the script, and the do
allows you to define variables and do other things within a scope related only to the Something
variable (that is, if you are staying organised). It also lets you name a do
block, which is great because
do
LotsOfStuffHere
end
is real ugly and uninformative in my opinion.
Inside the Something
block two variables are defined. Since they are local
, they canāt be used outside of the do block, which is great for variables that will only get used by the Something function.
As you now know, the Something
variable is actually a function, and this is where the organisation shines. You can split up your code (and therefore your variables) into their own relevant, self-contained places. It can make your code easier to understand and work with.
Hereās an example of this in the context of changing a gameās scene (ignore the validity of the shorthand stuff):
local ChangeLighting do
local Lighting = game:GetService("Lighting")
local ColorCorrection = Instance.new("ColorCorrection", Lighting)
ChangeLighting = function(NewLighting) end
end
local InsertMap do
local MapFolder = workspace.Map
local CurrentMap = MapFolder.Lobby
InsertMap = function(NewMap) end
end
local ChangeScene = function(NewLighting, NewMap)
ChangeLighting(NewLighting)
InsertMap(NewMap)
end
I only consider the solution of using a ModuleScript for variables useful when you have actual code you need to share ā as duplicate code is no good. I have modules in my game for retrieving items for ReplicatedStorage, enabling/disabling certain types of input, calculating stats, etc.
But, itās often better when scripting to know what a variable is at a glance (instead of having to navigate to another script) and you donāt want to get into dependency hell or anything like that ā so I donāt really have any variables in a module.
Either way, itās ultimately up to you. You want to find an environment you can work the best in (with the least amount of work on your end possible, too).