![](/img/trans.png)
[英]Passing in a WIdget constructor function as an object parameter in Dart
[英]Passing a function as a variable and assigning it to an object still able to reference “self” in Lua
所以,我正在嘗試編寫一個接受函數作為參數的函數,並將它們設置為Lua中的“對象”方法。 是否有一個我不知道的特定語法?
local function createObjectWithMethods(method1, method2)
local object = {}
object.meth1 = method1
object:meth2 = method2 --this throws an error expecting parameters
return object
end
還有另一種方法可以解決這個問題嗎? 我知道我可以硬編碼對象的方法,但是這段代碼需要將函數作為參數傳遞,其中一些函數需要能夠引用self。 有任何想法嗎?
你需要編寫傳入的方法而不需要自動化的self
語法糖。
那就是你不能用:
function obj:meth1(arg1, arg2)
-- code that uses self
end
(除非這些函數在某個其他對象上定義並交叉應用於新對象)。
相反,你需要為自己寫出上面的糖。
function meth1(self, arg1, arg2)
-- code that uses self
end
function meth2(self, arg1, arg2)
-- code that uses self
end
然后你可以正常調用函數並正常分配函數。
local function createObjectWithMethods(method1, method2)
local object = {}
object.meth1 = method1
object.meth2 = method2
return object
end
createObjectWithMethods(meth1, meth2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.