Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua Class keeping old values

Tags:

lua

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?

like image 836
Tyler Avatar asked Apr 17 '26 10:04

Tyler


1 Answers

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

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!