Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I use my table outside of my loop?

Asked by 7 years ago
Edited 7 years ago

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)
0
My guess is that EndPoints[1], EndPoints[2] or EndPoints[3] is nil User#6546 35 — 7y

1 answer

Log in to vote
1
Answered by
Perci1 4988 Trusted Moderation Voter Community Moderator
7 years ago
Edited 7 years ago

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)
Ad

Answer this question