this is how i call a function from menu.lua at main.lua
local menu = require("menu")
menu.drawMenu()
but how i gonna call a function from main.lua at menu.lua ? is it possible ? or set a listener or something like that
You can set a callback function by passing a function as a parameter to another function. So expanding on your example code:
-- main.lua
local menu = require("menu")
function drawMain()
print("main")
end function
menu.drawMenu(drawMain)
-- menu.lua
menu = {}
menu.drawMenu = function(callback)
print("menu")
callback()
end
return menu
You could do it by juggling a bit with environments, though this might have repercussions and is not directly portable to Lua 5.2:
-- main.lua
mainfunction = function() print"main function" end
menu = require"menu"
env=getfenv(menu.drawmenu) -- get the original environment
env=setmetatable(env,{__index=_G}) -- look up all variables not existing in that
-- environment in the global table _G
menu.drawmenu()
-- menu.lua
menu={}
menu.drawmenu=function()
print'drew menu'
mainfunction()
end
return menu
If you are simply looking to provide actions for the menu, would it not be better to use a set of call back functions (as used when building GUI elements) to be triggered when menu items are clicked?
This link may help you. http://www.troubleshooters.com/codecorn/lua/luacallbacks.htm