I have an issue where I want to have a table full of objects each containing a unique sprite from a sprite sheet I have made. But every time a new item is entered into the table, all items before it become the same as the last.
Here is the function that does the table insertion:
local IngredientTemplate = require("ingredient") local allIngredients = { } function spriteSheetLoader() -- Load in 'all ingredients' list. local ingredients = loadIngredientList() -- Each sprite is 32 x 32 with all icons in a single, long column. local sheetData = { width = 32, height = 32, numFrames = #ingredients, sheetContentWidth = 32, sheetContentHeight = 32 \* #ingredients } spriteSheet = graphics.newImageSheet("food.png", sheetData) -- Iterate all ingredients in list retrieved from database. for i = 1, #ingredients do --New sprite from sheet. local sprite = display.newImage(spriteSheet, i) --New ingredient object. local newIngredient = Ingredient:new(nil, sprite, ingredients[i]) -- Insert a new Ingredient into the table for use. table.insert(allIngredients, newIngredient) --Test what has been inserted so far. for i = 1, #allIngredients do print(allIngredients[i]:getName()) end print("\n") end end
Here is the constructor for the Ingredient object:
Ingredient = { sprite, name } local FoodLoader = require("foodLoader") function Ingredient:new(o, sprite, name) o = o or { } setmetatable(o, self) self.\_\_index = self self.sprite = sprite self.name = name return o end
I have also attached an image of what the function prints out during creating the table.
Any help is much appreciated, thanks.