英文:
Bind function with self in single line in Lua
问题
我想要一个函数指针(不知道 Lua 中的术语是什么),其中包含了 self 指针。
一个概念示例
x = {text = "hello there"}
function x.hello(self)
print(self.text)
end
--- 这是我遇到困难的地方
function_pointer = ???
function_pointer() -- 期望的行为是调用 x:hello(),但如何实现呢?
是否有可能将 self 指针嵌入到函数(指针)中?像这样?
英文:
I would like to have a function pointer (don't know what the term is in Lua) that has the self pointer baked in.
A concept example
x = {text = "hello there"}
function x.hello(self)
print(self.text)
end
--- This is where I'm stuck
function_pointer = ???
function_pointer() -- Expected behaviour is to call x:hello() but how
Is there any way possible to bake the self pointer into a function (pointer)? Like that?
答案1
得分: 1
另一种(简单/懒惰)方法是将表本身构造为其内容的函数。 这可以通过使用setmetatable()
和__call
元方法来完成。
x = setmetatable({text = "Hello there"}, {__call = function(self) print(self.text) end})
x() -- Hello there
-- 指针将是...
fp = getmetatable(x).__call
fp(x) -- Hello There
附注:您完全可以选择self
的名称。
x = setmetatable({text = "Hello there"}, {__call = function(this) print(this.text) end})
...尤其是'基本人'将使用this
;-)
它只是参数链中的第一个元素...
local func = function(...) print(({...})[1].text) end -- 匿名的“self”
x = setmetatable({text = "Hello there"}, {__call = func})
英文:
Another (easy/lazy) way is to construct the table itself as a function for its content.
This is done with setmetatable()
and the __call
Metamethod.
x = setmetatable({text = "Hello there"}, {__call = function(self) print(self.text) end})
x() -- Hello there
-- A pointer will be...
fp = getmetatable(x).__call
fp(x) -- Hello There
PS: You are totally free to choose the Name for self
x = setmetatable({text = "Hello there"}, {__call = function(this) print(this.text) end})
...especially the 'Basic People' will using this
It is only the first Element in the Chain of Arguments...
local func = function(...) print(({...})[1].text) end -- Anonymous "self"
x = setmetatable({text = "Hello there"}, {__call = func})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论