用 Lua 在单行中将函数与 self 绑定

huangapple go评论50阅读模式
英文:

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 用 Lua 在单行中将函数与 self 绑定
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})

huangapple
  • 本文由 发表于 2023年2月18日 18:44:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75492784.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定