1

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

August Lilleaas
  • 54,010
  • 13
  • 102
  • 111
FunFair
  • 63
  • 1
  • 10

3 Answers3

2

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
jhocking
  • 5,527
  • 1
  • 24
  • 38
1

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
jpjacobs
  • 9,359
  • 36
  • 45
1

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

Jane T
  • 2,081
  • 2
  • 17
  • 23
  • sorry im new in programming, so basically this callback is at my main.lua, i call menu.binary_op(5, 3, plus), it will call another local function, and return something to me right? what im trying to do is in my menu.lua, it will draw a button, when user click on it, it trigger a function, how do i let my main.lua know that the function inside menu.lua have been trigger ? – FunFair Jul 28 '11 at 02:18
  • There are several ways to do it. The simplest is probably, you define the functions you want the menu to trigger in your main program and then pass them as parameters to the menu function. – Jane T Jul 28 '11 at 07:40
  • In my answer I posted example code for passing functions as parameters to other functions. – jhocking Jul 29 '11 at 12:14
  • yea i done by passing a function from main.lua to menu.lua when main.lua calling the init() function at menu.lua. thx!! =) – FunFair Aug 01 '11 at 03:41