如何在给定Lua代码中使用冒号(:)函数语法调用command方法?
解决Lua中冒号语法调用的问题
首先明确Lua冒号语法的核心:obj:method(...)完全等价于obj.method(obj, ...),作用是自动将调用者obj作为第一个参数(也就是函数里的self)传入。
你的原调用NE.Commands.command(NE)是把NE作为self传给NE.Commands.command,之前尝试的两种写法都不对:
NE:Commands.command(NE):Lua不支持这种跨层级的冒号写法,冒号只能作用在最后一个方法名前,这行代码本身语法错误。NE.Commands:command(NE):这等价于NE.Commands.command(NE.Commands, NE),此时函数里的self是NE.Commands,而它并没有Functions字段,所以运行时会找不到self.Functions而出错。
下面是两种可行的解决方案:
方案一:不修改函数定义,通过绑定实现冒号调用
把NE.Commands.command赋值给NE的一个字段,让NE成为调用者,就能用冒号自动传递NE作为self:
NE = { Functions = { test = function (x) print(x) end }, Commands = { command = function(self) self.Functions.test("x") end } } NE.command = NE.Commands.command -- 将command函数绑定到NE表 NE:command() -- 等价于原调用NE.Commands.command(NE)
方案二:修改函数定义,适配子表调用
如果想直接用NE.Commands:command()的形式,需要给NE.Commands添加指向NE的引用,并调整函数内部逻辑:
NE = { Functions = { test = function (x) print(x) end }, Commands = { command = function(self) self.Parent.Functions.test("x") -- 通过Parent字段访问NE end } } NE.Commands.Parent = NE -- 给Commands子表添加父表引用 NE.Commands:command() -- 等价于NE.Commands.command(NE.Commands),此时self是NE.Commands,通过Parent拿到NE
内容的提问来源于stack exchange,提问作者LeFruJohn
相关产品推荐
相关产品推荐

