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 Something do
Something = function()
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
is real ugly and uninformative in my opinion.
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
local InsertMap do
local MapFolder = workspace.Map
local CurrentMap = MapFolder.Lobby
InsertMap = function(NewMap) end
local ChangeScene = function(NewLighting, NewMap)
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).