user1901873
user1901873

Reputation: 35

Lua and object spawning

My gut tells me that I'm making an obvious mistake, but it's escaping me. I'm attempting to make 'child' objects from a specified 'parent' object by use of the following example code.

local Ad = {
    __index = Ad,
    __tostring = function(self) return self.msg end,
    __concat = function(a, b) return tostring(a)..tostring(b) end,
    Initialize = function(self, msg, wgt)
        if msg and msg ~= "" then
            wgt = wgt or 1
            self.msg, self.wgt, self.ranLog = msg, wgt, {}
        end
    end,
    Increase = function(self)
        if self.wgt < 9 then self.wgt = self.wgt + 1 end
    end,
    Decrease = function(self)
        if self.wgt > 1 then self.wgt = self.wgt - 1 end
    end
}

local function new(src, ...)
    local o = setmetatable({}, src)
    if src.Initialize then o:Initialize(...) end
    return o
end

local ad = new(Ad, "Test Message")
print("Object - "..ad)
for k, v in pairs(ad) do print("", k, v) end
ad:Increase()
print("Modified Object - "..ad)
for k, v in pairs(ad) do print("", k, v) end

So that's verbatim what fails with an attempt to call method Initialize which is a nil value. Given that before this edit my sample code did work, is it a matter of how table Ad has been defined? Or do I have a syntax error in here somewhere?

Upvotes: 2

Views: 690

Answers (1)

Rob N
Rob N

Reputation: 1015

The problem is this:

local Ad = {
    __index = Ad,
    ...
}

At the time __index is assigned, Ad is nil, because the table is constructed in full before being assigned to Ad. Since __index is unset, the lookup for Initialize fails.

Instead, do something like:

local Ad = {
    ...
}
Ad.__index = Ad

Upvotes: 4

Related Questions