My survival game necessitates a lot of server checks for certain functions, and many of my scripts repeat the same code (if statements). I’d like feedback on a my method for successfully checking multiple if statements, as well as advice on how to avoid memory leaks by using cached variables.
-
What is the issue?
The issue is that I am hesitant to use cached variables, which I understand is a bad practice, but I am concerned that my cached variables at the top of the script will be used in functions/events below, resulting in untracked memory because the variable is always referenced and cannot be GC-ed.
--This is an example of what my script looklike:
-- bad example
-- function 1
if Values.Others.InGame.Value and not Values.Others.Dead.Value and Values.Controls.Camera.Value and ServerStorage.Values.Doors.LeftDoor.Value then
-- execute code
end
-- function 2
if Values.Others.InGame.Value and not Values.Controls.Camera.Value then
-- execute different event
end
You can see there is redundant code and repetition of “Values.Others.InGame.Value”
-
What solutions have you tried so far?
This is how I intend to store variables/tables to help with script speed optimisation/efficiency throughout
local Checklist = {workspace.Settings.Others.InGame,workspace.Settings.Controls.Camera, ServerStorage.Values.Doors.LeftDoor}
-- function 1
if Checklist[1].Value and Checklist[2].Value and Checklist[3].Value then
-- execute code
end
-- function 2
if Checklist[1].Value and not Checklist[2].Value then
-- execute different event
end
Is this a smart way to store the objects to avoid slow inefficient code, or is there a possible better solution that uses table.find() or something else?
Is there a way to avoid memory leaks with cached variables because they hold refernce to external varibles? That’s the main reason I’ve avoided them. However, I recently realised how useful cached variables (specifically object values) can be in improving script performance and speed.
Furthermore, if you suggest that I use the table *as shown above. Should I encapsulate this in its own scope and use do end
to allow the variable to be GC-ed? Please see the code below!
-- function 1
do
local Checklist = {workspace.Settings.Others.InGame,workspace.Settings.Controls.Camera, ServerStorage.Values.Doors.LeftDoor}
--set the checklist table reference in a seperate scope so it can be GC-ed???
if Checklist[1].Value and Checklist[2].Value and Checklist[3].Value then
-- execute code
end
-- function 2
if Checklist[1].Value and not Checklist[2].Value then
-- execute different event
end
end
-- hopefully the Checklist table reference can be GC-ed??
-- and do not have to worry about memory leakage???
-- other script stuff here!
Thank you very much for your time!