So with that, I moved the following code snippet into my globals holding lua file. It now looks like the following :
--my global variables space local widget = require( "widget" ) local M = {} local createBackBtn = function(left, top) local backBtn = widget.newButton{ id = "back", left = left, top = top, defaultFile = "images/outline/previous.png", overFile = "images/solid/previous.png", width = 12, height = 20, onRelease = goBack } return backBtn end -- assign a reference to the above local function M.createBackBtn = createBackBtn return M
Now in each screen that requires a back button I simply put the following line and get my back button :
This works great and the button is created as expected. My only problem is the function that the button is supposed to call in the onRelease event. I have a function that I always call goBack which gets called by the button. Since the goBack function differs from scene to scene I can’t move it to my external module. So my backBtn’s onRelease event needs to call a function that lives in the scope that called it in the first place.
The button created through the external function above can’t see the goBack function in the calling code. I tried to use the parent. construct but could not get it to work. I would love to get some lua help on this one.
To be honest, I wouldn’t hold functions in globals unless I had a really good reason. It’s generally much better to put them in their own files, and then include them and shortcut them into globals.
-- globals.lua local backButton = require("ui.backbutton") local globals = {} globals.var1 = "happy" -- etc globals.makeBackButton = backButton.make return globals
And jospic, I think what he solved was by doing this:
local makeBackButton(x, y, callback) local backBtn = widget.newButton{ id = "back", left = left, top = top, defaultFile = "images/outline/previous.png", overFile = "images/solid/previous.png", width = 12, height = 20, onRelease = callback, } return backBtn end
That way, you can attach an onRelease function from wherever you are in the code.
To be honest, I wouldn’t hold functions in globals unless I had a really good reason. It’s generally much better to put them in their own files, and then include them and shortcut them into globals.
-- globals.lua local backButton = require("ui.backbutton") local globals = {} globals.var1 = "happy" -- etc globals.makeBackButton = backButton.make return globals
And jospic, I think what he solved was by doing this:
local makeBackButton(x, y, callback) local backBtn = widget.newButton{ id = "back", left = left, top = top, defaultFile = "images/outline/previous.png", overFile = "images/solid/previous.png", width = 12, height = 20, onRelease = callback, } return backBtn end
That way, you can attach an onRelease function from wherever you are in the code.