lua - want to call a function in main.lua from another module
I want a to call a function that is defined in main.lua from a module that is required (included) in main.lua. What's the 开发者_如何学运维best/cleanest way to do this?
Edit:
I eventually went down the dispatch event route. That seems to be a neat way of doing it.
There are two options as far as I can see:
- Define the function A first, then
require()
the module, and call function A there. require()
the module first, and have the module define a function B that calls the function A in your main file. Call function B whenever you are ready to call it (i.e. function A is defined) in your main file.
The latter seems cleaner, but that would be a matter of personal preference.
Move that function to a separate module. This is the cleanest way.
Otherwise, use a global variable to store that function.
Make it available in the global table. For example:
--main.lua
require "myModule"
myModule.someFunc()
function mainFunc(...)
--...
end
--myModule.lua
module(myModule)
mainFunc(parameters)
As long as the module doesn't define the same variable name locally (and if it does, you can use _G.mainFunc
to get it), you should be fine.
精彩评论