I’m attempting to use Lua’s closures in the following bit of code:
[lua]
for k,v in pairs(tiles) do
for key, value in pairs(v) do
position.xPos = value[1]
position.yPos = value[2]
if self.inventoryData[itemId].Type == “Seed” then
item = SeedClass.new(itemData, self._game, position) –
self.items[item.id] = item
TaskManager:addTask({id=item.id, desc="Plant “…item.name, duration=15000, repeated=false,
callback = function()
print(”* x: “…item.mainImage.x) --always referring to last item created in the for loop
print(”* Y: "…item.mainImage.y) --always referring to last item created in the for loop
return item:action({x=item.mainImage.x, y=item.mainImage.y}) --always referring to last item created in the for loop
end})
end
end
end
[/lua]
Many thanks…
The idea being that a task is added to create the object, once the task’s duration has passed the object is displayed on screen in the item:action() call via a call to the task.callback() method.
Although this code works fine it comes across a problem when I’m trying to spawn multiple objects; the callback function only refers to the last item created up above - so the call to item:action is always being made on the last created item object. I’m pretty sure there’s a way to do this via the corretc use of closures, but can’t seem to get it right yet…
Any