如何在main.lua中使用来自另一个类的函数?

我正在尝试在我的 main.lua 中使用另一个类的函数。根据我的研究,我写了一些代码,但它不能正常工作。你能帮我吗?谢谢。

fish.lua 代码:

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 代码:

require  "fish"

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

local fishImage = Fish(originalImage)

它显示了图像,但当对其进行触摸时没有作用(不打印“hi”)。

点赞
用户1276924
用户1276924

有两个问题:

function Fish:listen(event) 改为 function Fish.listen(event)

并且将 if phase =="began" then 改为 if event.phase =="began" then

2012-07-01 10:53:21