OOP with modules

Hello guys, sorry in advance for my bad english. Today i just tried to embody little program with OOP with modules, and i have one trouble. Suppose there is such a code:

–class1.lua
local tab = {}
function tab.tap()
–some piece of code for which I’m too stupid to write
end
function tab:new(x,y)
local object ={}
setmetatable(object, self)
self.__index = self
object.image = display.newImageRect(“image”, x, y)
object.image.x, object.image.y = 300,300
object.image:addEventListener(“tap”, tab.tap)
end
return tab

–class2.lua 
local tab = {} 
function tab.print()
print()
end
function tab:new(x,y) 
local object ={} 
setmetatable(object, self) 
self.__index = self 
object.image = display.newImageRect(“image2”, x,y) 
object.image.x, object.image.y = 600,600 
end 
return tab 

–main.lua
class1 = require “class1”
class2 = require “class2”

object1 = class1:new(300,300)
object2 = class2:new(500,500)

How do I make it so that when I tap on object1 it calls object2.print and it print, as example, object1.image.x?
They out of scope of each other, and i dunno, what to do.
(i can define methods of every object in main.lua, but then modularity loses it meaning, i think?)
P.S. Sry for monkey code.
 

You don’t need to use metatables and proxy objects like that.  You can just write modules to do this work:

-- file: mod1.lua -- local m = {} local function tap( self, event ) print("tapped object at", self.x, self.y ) end function m.new( x, y, size )  local object = display.newImageRect("image.png", size, size )  object.x = x  object.y = y object.tap = tap object:addEventListener("tap") return object end end return m

Then later use it like this:

local m1 = require "mod1" local tmp = m1.new(300,300) local tmp = m1.new(500,500)

Hi,

If you are looking for a more structured approach to OOP with Lua, I highly recommend the 30Log library. I have been using it for years. Documentation can be found here.

-dev

You don’t need to use metatables and proxy objects like that.  You can just write modules to do this work:

-- file: mod1.lua -- local m = {} local function tap( self, event ) print("tapped object at", self.x, self.y ) end function m.new( x, y, size )  local object = display.newImageRect("image.png", size, size )  object.x = x  object.y = y object.tap = tap object:addEventListener("tap") return object end end return m

Then later use it like this:

local m1 = require "mod1" local tmp = m1.new(300,300) local tmp = m1.new(500,500)

Hi,

If you are looking for a more structured approach to OOP with Lua, I highly recommend the 30Log library. I have been using it for years. Documentation can be found here.

-dev