Lua回调到模块中
我的脚本使用回调函数注册自身,
require "cmodule"
index = 1
cmodule.RegisterSoftButtonDownCallback(index, "callbackFunc")
其中callbackFunc是回调函数的名称(字符串)。现在我把这个脚本变成了一个模块,但回调不再被调用,我假设是因为回调函数不在 cmodule 的范围内。我该如何解决这个问题? (Lua 新手)
cmodule 是一个具有 Lua 绑定的设备驱动程序。
编辑:我的完整解决方案基于以下 BMitch 的答案:
require "cmodule"
local modname = "myModule"
local M = {}
_G[modname] = M
package.loaded[modname] = M
local cmodule = cmodule
local _G = _G
setfenv(1,M)
function callbackFunc()
-- use module vars here
end
_G["myModule_callbackFunc"] = callbackFunc
index = 1
cmodule.RegisterSoftButtonDownCallback(index, "myModule_callbackFunc")
My script registers itself for a callback using
require "cmodule"
index = 1
cmodule.RegisterSoftButtonDownCallback(index, "callbackFunc")
where callbackFunc is the name (a string) of the callback function. Now I turned this script into a module, but the callback is not called anymore, I assume because the callback function is not in the scope of the cmodule. How can I solve this? (Lua newbie)
cmodule is a device driver that has Lua bindings.
Edit: My complete solution based in the answer from BMitch below:
require "cmodule"
local modname = "myModule"
local M = {}
_G[modname] = M
package.loaded[modname] = M
local cmodule = cmodule
local _G = _G
setfenv(1,M)
function callbackFunc()
-- use module vars here
end
_G["myModule_callbackFunc"] = callbackFunc
index = 1
cmodule.RegisterSoftButtonDownCallback(index, "myModule_callbackFunc")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要在全局空间中定义一些内容,以便将字符串计算回函数调用。
根据他们实现 RegisterSoftButtonDownCallback 的方式,您可能会陷入定义函数本身的困境,而不是像
myModule.callbackFunc
这样的表/字段组合。为了最大限度地减少命名空间污染,如果您不能使用myModule.callbackFunc
,那么我建议使用myModule_callbackFunc=myModule.callbackFunc
或类似的东西。所以你的代码看起来像:为了更好的修复,我将与 cmodule 开发人员合作,让他们的程序接受函数指针而不是字符串。那么你的代码将如下所示:
You need to have something defined in the global space for a string to be evaluated back to a function call.
Depending on how they implemented
RegisterSoftButtonDownCallback
, you may be stuck defining the function itself, rather than the table/field combination likemyModule.callbackFunc
. To minimize the namespace pollution, if you can't usemyModule.callbackFunc
, then I'd suggestmyModule_callbackFunc=myModule.callbackFunc
or something similar. So your code would look like:For a better fix, I would work with the cmodule developers to get their program to accept a function pointer rather than a string. Then your code would look like: