lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi,

I'm trying to use OO in Lua. I wrote the following code:

require('Product')

MockJSonParser = {}
function MockJSonParser:new()
    instance = {}

    setmetatable(instance, self)
    self.__index = MockJSonParser

    instance:setMockProductList()
    return instance
end

function MockJSonParser:setMockProductList()
    self.mockProducts = {}
    self.mockProducts[#self.mockProducts + 1] = Product:new(1,'Android', 10)
    self.mockProducts[#self.mockProducts + 1] = Product:new(2,'R2D2', 15)
    self.mockProducts[#self.mockProducts + 1] = Product:new(3,'C3PO', 500)
    self.mockProducts[#self.mockProducts + 1] = Product:new(4,'Azimo', 2500)
    self.mockProducts[#self.mockProducts + 1] = Product:new(5,'Transformer', 10000)
end

function MockJSonParser:parse()
    print('hi')
    return self.mockProducts
end
---------------------------------------------
parser = MockJSonParser:new()
print(parser)
table.foreach(parser,print)
list = parser:parse()
print(list)
table.foreach(list, print)


Where Product is a table that represents products, which has 3 fields: id, name and price

For some strange reason the "new" method is returning the last Product I've added to mockProducts list.

Here  is the output I got when I run this file:

/usr/bin/lua5.1: ...kspace/T-CommerceClient/media/lua/MockJSonParser.lua:31: attempt to call method 'parse' (a nil value)
stack traceback:
    ...kspace/T-CommerceClient/media/lua/MockJSonParser.lua:31: in main chunk
    [C]: ?
table: 0x8949fd0
id    5
name    Transformer
price    10000


Can anyone tell me what I'm doing wrong?

Thanks

--
João E. Hornburg