Attempt to iterate over nil value

I keep getting “attempt to iterate over a nil value”

for index, i in print(handSealsUsed) do
	if handSealsUsed[i] then
		handSealsUsed[i] = nil
	else
		break
	end
end
1 Like

The first lina

for index, i in print(handSealsUsed) do

has the function call print(handSealsUsed).

The print() function outputs a string to the console and then returns nil.

The expansion of what you’re writing looks like:

for index, i in print(handSealsUsed) do

becomes

for index, i in nil do

Which is your problem. Try instead:

for index, i in handSealsUsed do

I forgot that i have an array inside a print

So you mean keywords like these cannot be used as functions?

The reason this can’t be used is because of what the function print() actually returns.

You can think of functions as a sort of magical box. In the case of the function print(), we’re putting a string inside of the magical box. Print(“hello”) means we’re giving our box the string “hello” as its input.

This magical box does something with the input. In the case of our print function, our magical box displays the input in the console. From writing print(“hello”), we expect “hello” to appear in the output / developer console.

However, some functions also return something. The thing they return is called the output. If a function returns nothing, we say the output is nil. The function print() returns nothing - i.e. it returns nil.

Keywords like “print” are functions - what’s important is that the function “print” returns nil. After all, what would print() return? The job of print() is to make your developer console say something.

The reason this particular problem occurred is because the original poster was trying to iterate over what print(variable) returns. You can’t iterate over something that doesn’t exist (remember, print returns nil).

1 Like