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

Any way to compact this code?

I have a piece of code that modifies certain property from a lot of different variables linked to instances, but typing each variable + property is a PITA. Any way to compact it? I can't figure out if it's possible to just use a single variable to change them all.

Thanks!

local s = script.Parent
local A1, A2, A3, A4 = s.A1, s.A2, s.A3, s.A4
local backpack = game.Players.LocalPlayer.data.backpack   -- backpack is a StringValue

if backpack then
	if backpack.Value == "None" then
		A1.Visible, A2.Visible, A3.Visible, A4.Visible,
		A1.Active, A2.Active, A3.Active, A4.Active = 
		false, false, false, false, false, false, false, false
	end
end

-- Is there a way to compact A1 through A4 Visible and Active properties' code? Can I only type false one time instead of 8 times?

1 answer

✓ Accepted answer

Yes.

Usually, when you have variables that you are naming A1, A2, etc, it's a sign that you should be using a list:

local As = {s.A1, s.A2, s.A3, s.A4}
-- They are now As[1], As[2], As[3], and As[4]
-- which is more easily programmatically accessible because `1` is a value
-- instead of a part of the name.

You then write a loop that goes over them all:

for _, A in pairs(As) do
	A.Visible = false
end

If you frequently are setting the visible property of these, I would suggest making a function:

function show(visible)
	for _, A in pairs(As) do
		A.Visible = visible
	end
end

show(true) -- all visible
show(false) -- all invisible

If you have a lot of things in s that you want, it might be a good idea to use :GetChildren() instead.

If you moved the script out of there, then it's likely that all of the children would be the things you want. Otherwise, you would need to filter them somehow (e.g., they are all Frames, perhaps?):

local As = s:GetChildren()
for _, A in pairs(As) do
	if A:IsA("Frame") then
		A.Visible = false
	end
end

2 comments

0

Can a array be called a list?

0

Thank you!

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