将 Lua 方法定义为初始化
在Lua语言中,我能够在表中定义函数,比如
table = { myfunction = function(x) return x end }
我想知道我是否可以通过这种方式创建方法,而不是像
function table:mymethod() ... end
我相当确定可以通过这种方式添加方法一样,但是我我不确定这种技术的正确名称,并且我无法找到它来寻找“lua”和“方法”等。
我的目的是将一个表传递给一个函数,例如 myfunction({data= stuff, name = returnedName, ?method?init() = stuff})。
不幸的是,我尝试了几种与冒号方法声明的组合,但它们都不是有效的语法。
那么……这里有人知道吗?
In the Lua language, I am able to define functions in a table with something such as
table = { myfunction = function(x) return x end }
I wondered if I can created methods this way, instead of having to do it like
function table:mymethod() ... end
I am fairly sure it is possible to add methods this way, but I am unsure of the proper name of this technique, and I cannot find it looking for "lua" and "methods" or such.
My intention is to pass a table to a function such as myfunction({data= stuff, name = returnedName, ?method?init() = stuff})
.
Unfortunately I have tried several combinations with the colon method declaration but none of them is valid syntax.
So...anyone here happens to know?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当然:
table:method()
只是table.method(self)
的语法糖,但你必须处理self
参数。如果这样做,那么
tab:f(x)
将不起作用,因为这实际上是tab.f(tab,x)
,因此将返回tab< /code> 而不是
x
。您可以查看面向对象的 lua 用户 wiki 或 PiL 第 16 章。
Sure:
table:method()
is just syntactic sugar fortable.method(self)
, but you have to take care of theself
argument. If you dothen
tab:f(x)
won't work, as this actually istab.f(tab,x)
and thus will returntab
instead ofx
.You might take a look on the lua users wiki on object orientation or PiL chapter 16.