how to call function between 2 .lua

情到浓时终转凉″ 提交于 2019-12-11 07:48:46

问题


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


回答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




回答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



回答3:


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


来源:https://stackoverflow.com/questions/6840154/how-to-call-function-between-2-lua

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!