开发者

Lua callback into module

开发者 https://www.devze.com 2023-03-18 03:29 出处:网络
My script registers itself for a callback using require \"cmodule\" index = 1 cmodule.RegisterSoftButtonDownCallback(index, \"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开发者_JAVA技巧
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")


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 like myModule.callbackFunc. To minimize the namespace pollution, if you can't use myModule.callbackFunc, then I'd suggest myModule_callbackFunc=myModule.callbackFunc or something similar. So your code would look like:

require "cmodule"
index = 1
myModule_callbackFunc=myModule.callbackFunc
cmodule.RegisterSoftButtonDownCallback(index, "myModule_callbackFunc")

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:

require "cmodule"
index = 1
cmodule.RegisterSoftButtonDownCallback(index, myModule.callbackFunc)
0

精彩评论

暂无评论...
验证码 换一张
取 消