如何从 Lua 事件处理函数中获取 'self'?
How to get 'self' from Lua event handler function?
local tbl = {a = 1}
-- Passed and executed function
function tbl:handleFunc(x, y)
print(self.a + x + y)
end
-- I know the above code is syntax sugar.
-- tbl["handleFunc"] = function(self, x, y)
-- print(self.a + x + y)
-- end
-- Register event handlers that I can't control the call
Frame:SetScript("OnClick", tbl.handleFunc)
-- Probably called when an event occurs.
tbl.handleFunc(2, 3)
-- Then it will be like this.
tbl.handleFunc(2, 3, nil)
-- So I wrote a function like this
function tbl.handleFunc(x, y)
local self = tbl -- This variable is too cumbersome
-- And this way, every time I call a function, I need to check whether the function definition is a dot (.) Or colon (:)
end
调用函数时,在无法通过self的情况下,有没有办法使用self?
如果没有,我该如何设计?
[已解决]我用了翻译器,但我想礼貌一点。谢谢你的好回答。
只需使用调用实际函数的匿名函数
Frame:SetScript("OnClick", function(x,y) tbl:handleFunc(x, y) end)
避免不必要工作的一种方法是编写一个函数,在您将其注册为处理程序之前为您包装该函数:
local tbl = {a = 1}
function tbl:handleFunc(x, y)
print(self.a + x + y)
end
function wrap_with(obj, func)
return function(...)
return func(obj, ...)
end
end
Frame:SetScript("OnClick", wrap_with(tbl, tbl.handleFunc))
local tbl = {a = 1}
-- Passed and executed function
function tbl:handleFunc(x, y)
print(self.a + x + y)
end
-- I know the above code is syntax sugar.
-- tbl["handleFunc"] = function(self, x, y)
-- print(self.a + x + y)
-- end
-- Register event handlers that I can't control the call
Frame:SetScript("OnClick", tbl.handleFunc)
-- Probably called when an event occurs.
tbl.handleFunc(2, 3)
-- Then it will be like this.
tbl.handleFunc(2, 3, nil)
-- So I wrote a function like this
function tbl.handleFunc(x, y)
local self = tbl -- This variable is too cumbersome
-- And this way, every time I call a function, I need to check whether the function definition is a dot (.) Or colon (:)
end
调用函数时,在无法通过self的情况下,有没有办法使用self?
如果没有,我该如何设计?
[已解决]我用了翻译器,但我想礼貌一点。谢谢你的好回答。
只需使用调用实际函数的匿名函数
Frame:SetScript("OnClick", function(x,y) tbl:handleFunc(x, y) end)
避免不必要工作的一种方法是编写一个函数,在您将其注册为处理程序之前为您包装该函数:
local tbl = {a = 1}
function tbl:handleFunc(x, y)
print(self.a + x + y)
end
function wrap_with(obj, func)
return function(...)
return func(obj, ...)
end
end
Frame:SetScript("OnClick", wrap_with(tbl, tbl.handleFunc))