luapico-8

Fields and methods of metatable are not visible on table right after setmetatable


This is Pico-8 lua. I have the following function, which fails at the marked assert. I do not understand how this can happen. I have used setmetatable on two other occasions and it is working there. I have no clue here.

function particle:new(o)
    setmetatable(o, self)
    assert(self.spd, "works")
    assert(getmetatable(o).spd, "works")
    assert(o.spd, "this fails") -- < this assert fails, the ones above succeed
    add(anims,o)
end

Solution

  • Looks like you forgot

    self.__index = self
    

    Without this o.spd will not refer to particle.spd, if o.spd is nil.