Let’s suppose I want to access the local player through a local script. Instead of doing it instantly, I’d do:
local plrs = game:GetService("Players")
local plr = plrs.LocalPlayer
-- Instead of
local plr = game:GetService("Players").LocalPlayer
Is it plausible to store important things as variables instead of just ‘raw’ using it? I’ve seen way more than I can say people using services instead of storing them:
local tween1 = game:GetService("TweenService"):Create(...)
local tween2 = game:GetService("TweenService"):Create(...)
tween1:Play()
tween2:Play()
In my opinion, if you’re reusing the value more three times then you should probably store it as a variable (especially if it’s like an array, dictionary, or service of some sort)
It’s personal preference, but for organization, you should always initialize all services and modules as variables at the top of the script. If you’re too lazy to do it yourself, you can use SimpleComplete.
To put the actual memory use into perspective:
1 integer val is 32 bits/4 bytes (though this has a 64 bit option too) (as per Numbers)
1 number val (non integer/floating point) is 64 bits/8 bytes (Also as per Numbers)
1 CFrame = ~20 bytes.
Making a variable “local” can reduce the amount of memory it uses.
But all of this is negligible unless you’re making a really, really big game or loading a list or instance that has a LOT of data into memory, so the most accurate answer is it doesn’t really matter.
if game:service'Players'.LocalPlayer.Character == nil then
game:service'Players'.LocalPlayer.CharacterAdded:wait()
end
if game:service'Players'.LocalPlayer.Character:FindFirstChild'Humanoid' then
game:service'Players'.LocalPlayer.Character.Humanoid.Died:connect(function()
game:service'Players'.LocalPlayer:Kick("imagine dying")
end)
end
Because when you are setting up a variable to be locally implemented, you probably won’t need to use much of the memory to make it visible to the rest of the code? I don’t know
Yeah I imagine it’s something like that. There’s normally a big array storing global variables but local does something different. It gets rid of the variable from memory more often. I’m not sure how to explain it myself, so here.
Indeed, generally you would rarely use global variables for something. If we want to access a variable to the rest of the code, commonly we set it at the start of the script, so the scope is ‘global.’
EDIT: Then, we can simply update its value when needed:
local currentPart
for _, part in workspace:GetChildren() do
if part:IsA("BasePart") then
part.Touched:Connect(function()
currentPart = part.Name
end)
end
end
-- Instead of setting currentPart as a global variable inside the for loop.
what i meant is that if you are consistently using something, you should definitely use a variable. However, a variable takes up memory as it is being stored. So my point is to avoid using variables, but if you have something repetitive or accessing the same thing numerous times, you should use one.