Tyler
Tyler

Reputation: 264

Lua Class keeping old values

I'm new to Lua so I'm sure I'm missing something but I have this class and it seems to be behaving unexpectedly.

Item = {elm = nil, __index = {}}

function Item:new(obj)
    setmetatable({}, Item)
    self.elm = obj.elm
    return self
end


function Item:collectItem()
    print(self.elm);
end

local itm = Item:new{elm = "val1"}
local itm2 = Item:new{elm = "val2"}

itm:collectItem()
itm2:collectItem()

This outputs:

>val2
>val2

When I would expect:

val1 val2

What am I missing here?

Upvotes: 3

Views: 137

Answers (1)

user142162
user142162

Reputation:

The issue here in that your Item:new function keeps modifying the same table: Item (self in the context of Item:new). What you want to do is create a new table for each new Item object you create. Here is one way you can do this:

Item = {elm = nil}

function Item:new(obj)
    -- Create a new table whose metatable's __index is the Item table
    local instance = setmetatable({}, {
        __index = self
    })
    -- Modify the new table, not Item (self)
    instance.elm = obj.elm
    -- Return the new object
    return instance
end

Upvotes: 2

Related Questions