首页 > 解决方案 > Lua 类方法

问题描述

我正在尝试创建 Ball 类并在类中有一些方法,但我找不到正确的语法

尝试阅读:https ://www.lua.org/pil/16.html

MovingObj = {}

function MovingObj:new(o)
  return o
end

ball = MovingObj:new {}

MovingObj.test = function (self)
  print ("Test!")
end

ball:test()

我收到的错误消息:尝试调用方法“测试”(零值)

标签: classlua

解决方案


o只是一个空表,您不要对其应用元表,这将允许访问MovingObj

new您可以通过在函数期间应用元表来纠正此问题:

MovingObj = {}

function MovingObj.new(o) 
  o = o or {}

  local meta = {
    __index = MovingObj -- when o does not have a given index check MovingObj for that index.
  }

  return setmetatable(o, meta) -- return o with the new metatable applied.
end

ball = MovingObj.new({type = "ball"})

function MovingObj:test()
  print ("Test! I'm a " .. self.type)
end

ball:test()

也没有必要使用:这个函数的语法new,我们没有使用self变量。


推荐阅读