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

attempt to index field '?' (a nil value) Question:

Asked by 6 years ago
Edited 6 years ago

I got a question. When i start my script. This code always wrong by attempt to index field '?' (a nil value)! i'm wanna to know why? Codes(The wrong place):

function findClosestComputer(Character)
    for i = 1,#AllComputers do
        local Computer
        local Distance = Player:DistanceFromCharacter(AllComputers[i].PrimaryPart.Position)
        local NextDistance = Player:DistanceFromCharacter(AllComputers[i+1].PrimaryPart.Position)
--He said Here! attempt to index field '?' (a nil value)
        if Distance < NextDistance then
            Computer = AllComputers[i] 
            print("1")
        else
            Computer = AllComputers[i+1]
            print("2")
        end
    end
end

Thank you!

0
You're trying to index the PrimaryPart of a nil value of the table. It's happening because of the [i+1] part. Make sure you're not trying to index more than the contents of the table. PlantChampion 136 — 6y

1 answer

Log in to vote
0
Answered by
PlaasBoer 275 Moderation Voter
6 years ago
Edited 6 years ago

I also did it like that before but what happens is lets say you have 10 computers so the table is 10 index if the index comes to 10 like i = 10 then what is i after AllComputers[i+1] it is 11 so AllComputers[i+1] it is trying to index a nil value because the table is only size 10.

What I was thinking is make the index start at the one before the last so if the size 10 the loop will end at 9.

function findClosestComputer(Character)
    for i = 1,#AllComputers - 1 do --Here I added that
        local Computer
        local Distance = Player:DistanceFromCharacter(AllComputers[i].PrimaryPart.Position)
        local NextDistance = Player:DistanceFromCharacter(AllComputers[i+1].PrimaryPart.Position)
--He said Here! attempt to index field '?' (a nil value)
        if Distance < NextDistance then
            Computer = AllComputers[i] 
            print("1")
        else
            Computer = AllComputers[i+1]
            print("2")
        end
    end
end

Note! That won't get the closest one since i changes. Read that code I gave earlyer then you can still change the names to your likingand so you get the latest closest distance.

0
Ooooh!! I understand now! Thank you for answer! MEndermanM 73 — 6y
0
Cool PlaasBoer 275 — 6y
Ad

Answer this question