What is indexing?

I don’t understand what indexing means but I know how to use loops like for i,v in pairs and while true do loops.

3 Likes

Indexing is essentially accessing from something.

For instance say you have a dictionary with a string mapped to a number, and you want to get that number. So you index that table with the string, for the number.

local t = { apples = 5 }
print(t.apples) -- indexed table with apples, we can now get the value 5
4 Likes

So indexing means getting a value from a table?

For this roblox error: (attempt to index nil with character)
It is basically saying that it failed to get the character?

To elaborate further, let’s take a look at an example:

local myDictionary = {apples = 5}

Say we want to read how many apples there are.

print(myDictionary.oranges)

But wait, something is off here, isn’t it? There are no oranges in our dictionary, just apples. So if we ran this code, it would print nil, because oranges doesn’t exist as an index in our dictionary, just apples.

So the error you’re getting indicates you’re attempting to index something that doesn’t exist in the character model.

8 Likes

(attempt to index nil with character)

This actually means you’re trying to get nil.character. You are indexing object nil with key character.

Going off the above examples:

local appleColors = {red = 10, green = 3, orange = 2, blue = 0}
print(appleColors.orange) -- prints 2
print(orangeColors.orange) -- causes an error because there is no orangeColors

You most often end up indexing nil when you use :FindFirstChild or player.Character or the like, which can return or be nil (meaning whatever you were looking for doesn’t exist)
You may check whether you have nil and deal with it early:

local character = workspace.JayO_X -- will cause an error if "JayO_X" is not in Workspace, but is otherwise guaranteed to set character to something named JayO_X in Workspace
local player = game.Players:GetPlayerFromCharacter(character) -- can return nil or a Player, but does not error if no player associated with workspace.JayO_X exists
if player == nil then
	print("Doing nothing")
else
	-- player cannot be nil, therefore it must be a Player
	print("Doing something")
	player:Kick()
end

print(player.Name) -- causes an error (index nil with Name) if player does not exist (i.e. "Doing nothing" printed)
2 Likes