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

help with indexing all values at once instead of progressively?

I want to index values all at once so I don't have to constantly add if statements like so:

while true do
	wait(1)
	--all values here--
	local part
	local light
part = script.Parent:FindFirstChild("Part2")
if part then
light = part:FindFirstChild("SurfaceLight")
end
--------------------------




--index values here--
if part and light then
	print("ran")
end
end
----------------------

when there a re a lot of children to index theres going to be a lot of if statements which is not desired as I want everything to be setup at once regardless of how many children there are.

something like this:

while true do
	wait(1)
	--all values here--
local part = script.Parent:FindFirstChild("Part2")
local light = part:FindFirstChild("SurfaceLight")
--------------------------




--index values here--
if part and light then
	print("ran")
end
end
----------------------

unfortunately if "part" becomes nil, an error comes up saying "attempting to index nil with findfirstchild"

is there a way around this to accomplish what I am trying to do?

2 answers

✓ Accepted answer

You can use what's called a shorthand if.

You use it by doing:

local x = a and b or c
  • where a would be a true/false/nil value (you can use this for parts to check if the part exists)
  • where b would be the value returned if a is true or exists
  • where c would be the value returned if a is false or nil (doesn't exist)

you can also omit c so that you have

local x = a and b

Back to your original question, you can utilize this to check if a parent exists. I.e:

local part = script.Parent:FindFirstChild("Part2")
local light = part and part:FindFirstChild("SurfaceLight")

-- then you just have to do one if statement for the last item:
if light then
	-- code
end

1 comment

1

that's awesome this is exactly what I was looking for.

You can store all respective children into an array via using the :GetChildren() method on the Instance you desire to gather all children from. Then use a pairs loop to iterate through each Instance and perform the given task on each Object.

for _,Light in pairs(script.Parent.Part2:GetChildren()) then
	if (Light:IsA("SurfaceLight")) then
		print("ran")
	end
end)

2 comments

0

but this would only be usable for getting the children from one place and its doing something straight away. it doesnt look to be storing any values.

0

Then please explain your desired goal better.

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