viviah
viviah

Reputation: 1

How do I avoid creating a nil reference in Lua when I remove an item from a table?

I am new to Lua, and I'm trying to create a video game using LOVE2D in which the player decorates pizzas moving on a conveyer belt. Once the player successfully builds a pizza, they receive a new order and automatically begin working on the next pizza.

The issue I'm having is with keeping track of the pizza objects the player interacts with. I've created a table to hold the pizzas, where the item at the first index is the current pizza--the one the player can add toppings to. To save memory, I thought of removing the pizza at the first index (table.remove(pizzas, 1)) once it leaves the screen. However, this results in the error 'attempt to index a nil value', which I'm guessing is because I have multiple references to the item at the first index (e.g. to keep track of position, pizzas[1].x, or to keep track of cheese, I have pizzas[1].cheeseCount). How do I avoid this? Thanks so much!

Upvotes: 0

Views: 317

Answers (1)

Piglet
Piglet

Reputation: 28994

https://www.lua.org/manual/5.3/manual.html#pdf-table.remove

table.remove (list [, pos])

Removes from list the element at position pos, returning the value of the removed element. When pos is an integer between 1 and #list, it shifts down the elements list[pos+1], list[pos+2], ···, list[#list] and erases element list[#list]; The index pos can also be 0 when #list is 0, or #list + 1; in those cases, the function erases the element list[pos].

The default value for pos is #list, so that a call table.remove(l) removes the last element of list l.

So your problem is most likely not that you index the first (removed) pizza, but that you index a pizza that has been shifted down and hence does no longer exist at its original index.

local pizzas = {"A", "B", "C"}
table.remove(pizzas, 1)

now your table looks like that: {"B", "C"}

and pizzas[3] would be nil.

Upvotes: 2

Related Questions