0

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")
2
  • What is cmodule? That's not part of Lua 5.1. Where does it come from? Is it a global variable or a local one? Commented Jul 8, 2011 at 20:27
  • cmodule is a device driver that has Lua bindings. I do a require "cmodule" at the start of the script (loading cmodule.dll). It is not developed by me. If it is important to know what exactly it does I could try to contact the author. Commented Jul 9, 2011 at 9:35

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this set me on the right track. I will add my solution to the original question so that others can benefit from it. If you think it can be improved upon then please comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.