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")
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.callbackFuncor 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: