Figen Güngör
Figen Güngör

Reputation: 12559

How to use functions from another class in main.lua?

I am trying to use functions of another class in my main.lua. I wrote some code according to my research but it's not working properly. Can you help me out? Thanks.

fish.lua code:

function class()
  local cls = {}
  cls.__index = cls
  return setmetatable(cls, {__call = function (c, ...)
      instance = setmetatable({}, cls)
      if cls.__init then
          cls.__init(instance, ...)
      end
      return instance
  end})
end


 Fish= class()

 function Fish:listen(event)
  if phase =="began" then
          print("hi")
  end
 end

function Fish:__init(image)
    self.image=display.newImage(image,30,30)
    self.image: addEventListener("touch",self.listen)
end

main.lua code:

  require  "fish"

  originalImage="fish.small.red.png"
  differentImage="fish.small.blue.png"

  local fishImage=Fish(originalImage)

It displays the image but does not work(prints "hi" ) when it is touched.

Upvotes: 0

Views: 272

Answers (1)

royi
royi

Reputation: 554

A couple of problems:

Change function Fish:listen(event) to function Fish.listen(event)

and if phase =="began" then should be if event.phase =="began" then

Upvotes: 2

Related Questions