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

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

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!

1 comment

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.

1 answer

✓ Accepted answer

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.

2 comments

0

Ooooh!! I understand now! Thank you for answer!

0

Cool

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