Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How much better is it to switch over to a Module Script for reused variables?

So I was looking for ways to make my game more efficient, and I decided to mess around with ModuleScripts. Currently, my game has around 100 attacks. At the top of each attack script, there is a block of code such as this:

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Debris = game:GetService("Debris")
local ModifyStages = ReplicatedStorage.ModifyStages
local Attacks = ReplicatedStorage.Attacks

local BodyPosition = Instance.new("BodyPosition")
BodyPosition.MaxForce = Vector3.new(math.huge, math.huge, math.huge)

This carries true for almost all of the ~100 attacks in my game. If I put all of these variables into a ModuleScript instead, and have it set up like so:

--Module Script:
ReplicatedStorage = game:GetService("ReplicatedStorage")
Debris = game:GetService("Debris")
ModifyStages = ReplicatedStorage.ModifyStages
Attacks = ReplicatedStorage.Attacks

BodyPosition = Instance.new("BodyPosition")
BodyPosition.MaxForce = Vector3.new(math.huge, math.huge, math.huge)

return function() 
	local ModuleEnvironment = getfenv(1) -- Module Script Variable Environment
	local CallingEnvironment = getfenv(2) -- Calling Script Variable Environment
	for Variable, Value in pairs(ModuleEnvironment) do
		if Variable ~= "script" then -- Don't overwrite "script" variable
			CallingEnvironment[Variable] = Value -- Send variable to Calling Environment
		end
	end
end
--Attack Script:
require(script.Parent)()

Would this make my game any more efficient?

1 answer

✓ Accepted answer

I believe this would work just fine, but any increase in efficiency will be unnoticeable, since in both cases the code only runs once.

I personally don't think that this would be a good idea as it increases your code's complexity for little (if any) gain. The only real gain is that it decreases boilerplate code.

Really, you really shouldn't be concerned much about performance unless it is a big issue.

This discussion is preserved as it was. New answers, comments, and votes are closed.