user3787574
user3787574

Reputation: 15

Creating multiple instances of a class object. Data of all objects are equal to the last object created

I have created a small class called Piece, which looks as follows

local Piece = {}
local Piece_mt = { __index = Piece}

function Piece.New(name, img, startPosX, startPosY)

    newPiece = {}
    newPiece.name = name;
    newPiece.img = display.newImage(img, startPosX, startPosY);
    print(newPiece.name);

    local function OnHit ( event )
        if event.phase == "ended" then
            print(newPiece.name);
        end
    end

    newPiece.img:addEventListener("touch", OnHit);

    return setmetatable( newPiece, Piece_mt )
end

return Piece

When I create the class, it prints the name, and it is correct (matches what I passed as a parameter). However, when I later click the image, and the name is printed as a result of the triggered OnHit function, the name printed is always the name of the last object I created, regardless of which of the objects I click on. Could someone explane why this happens and how to fix it?

Upvotes: 0

Views: 114

Answers (1)

Yu Hao
Yu Hao

Reputation: 122433

function Piece.New(name, img, startPosX, startPosY)
    newPiece = {}
    -- process    
    return setmetatable( newPiece, Piece_mt )
end

Here, you are assigning the global variable newPiece and return it every time. Instead, try use a local variable:

function Piece.New(name, img, startPosX, startPosY)
    local newPiece = {}
    -- process    
    return setmetatable( newPiece, Piece_mt )
end

Upvotes: 1

Related Questions