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

How do I use my table outside of my loop?

I asked this question before, but I don't think I explained it properly.

Anyways in the for loop I'm attempting to find all children in workspace called "StartAndEnd" and place their child called EndPoint in the table.

When I try to get a random value from this table I recieve the error:

Workspace.StartAndEnd.NPC.Pathfinding:18: attempt to index local 'TrueEnd' (a nil value)

Is this because I cant get the values from the table outside the for loop?

OwnEnd = script.Parent.Parent

EndPoints = {}

for i, Ends in pairs (workspace:GetChildren()) do
	if Ends ~= OwnEnd and Ends.Name == "StartAndEnd" then 

		EndPoints[i] = Ends.EndPoint	
	end
end

wait(5)

local TrueEnd = EndPoints[math.random(1, 3)]

local Path = game:GetService("PathfindingService"):ComputeRawPathAsync(OwnEnd.StartPoint.Position, TrueEnd.Position, 500)

1 comment

0

My guess is that EndPoints[1], EndPoints[2] or EndPoints[3] is nil

1 answer

i is the current index of the table GetChildren returns. It will start at 1 and end at the number of children in workspace. You then take the same number and make that index of EndPoints equal to the EndPoint.

On line 14, you choose a random value in EndPoints at index 1, index 2, or index 3. But how do you know 1, 2, and 3 are the indexes you assigned values to? You previously set it to be at i, but i could be 23 for all you know.

There's different ways you could go about fixing this problem, but I'll just use table.insert. It always puts the value at #table + 1 unless you specify otherwise.

table.insert(EndPoints, Ends.EndPoint)

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