user1597438
user1597438

Reputation: 2221

Removing items inside an array using for loop in lua

I'm trying to use a for loop to destroy objects inside my array like so:

for item in self.objects do
    item:removeSelf()
end

The self.objects is my array and it contains images I use for animation. If I touch one of these animated objects, it should be destroyed (disappear). My problem is, I'm getting this error message:

Attempt to call a table value

I'm not sure why I'm getting this error and how to fix it so can somebody please explain how I can remove objects from my array during touch event and why I'm getting this message? Thanks in advance. :D

Upvotes: 1

Views: 2136

Answers (1)

furq
furq

Reputation: 5788

A generic for loop of the form for x in y do... expects y to be an iterator function. You're passing it a table, hence the error message.

If you just want to iterate over each entry in the table, use pairs:

for key, item in pairs(self.objects) do
  item:removeSelf()
end

See PiL 4.3.5 and all of Chapter 7 for more info on generic for and iterators.

Upvotes: 5

Related Questions