class - 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()
我收到的错误消息:尝试调用方法“测试”(零值)
解决方案
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
变量。
推荐阅读
- javascript - 如何从 iframe 中仅删除水平滚动?
- javascript - JavaScript 输入 keyUp 事件监听器 Promise 仅在第一次返回,在每个 keyUp 承诺值未更新后
- postgresql - OSX:将 Postgres db 从一台 Mac 迁移到另一台
- python - 如何按顺序计算列表的重复数
- javascript - 仅在 page.goto(url) 实际加载页面时执行 page.evaluate()
- php - 用 php 代码对 php 代码进行基准测试是一种可靠的方法吗?
- git - 如何在不推送到远程的情况下将 origin/master 带到最新的提交?
- c - 如何用 BNO055 测量 Z 轴的方向差?
- python-3.x - ModuleNotFoundError:没有名为“aiohttp”的模块
- proxy - 将快递应用重定向到外部网站,导致代理错误