问题
I have two Lua Scripts containing functions with the same name:
luaScriptA:
function init()
print( 'This function was run from Script A' )
end
luaScriptB:
function init()
print( 'This function was run from Script B' )
end
I would like to load both these functions using LuaJ into the globals environnment, for one script I usually do it as follows:
LuaValue chunk = globals.load(new FileInputStream(luaScriptA), scriptName, "t",
globals);
chunk.call();
This will load the function init() into globals and I can execute this function from java with:
globals.get("init").call();
The problem comes in when I load a second script, this will overwrite all functions with the same name previously declared. Is there any way I can prevent this and easily distinguish between the two functions? For example something like:
globals.get("luaScriptA").get("init").call(); //Access the init function of script A
globals.get("luaScriptB").get("init").call(); //Access the init function of script B
Please note that the script contains other functions as well and my goal is to run individual functions within the script, not the complete script at once.Working on the JME platform.
回答1:
Put your functions in a table
luaScriptA:
A = {} -- "module"
function A.init()
print( 'This function was run from Script A' )
end
luaScriptB:
B = {} -- "module"
function B.init()
print( 'This function was run from Script B' )
end
Then you would do
globals.get("A").get("init").call();
globals.get("B").get("init").call();
回答2:
The code below loads scripts in their own environment, which inherits from the global one for reading but not for writing. In other words, you can call print
but each defines its own init
. You'll probably have to do something to use it in LuaJ, but I don't know what.
local function myload(f)
local t=setmetatable({},{__index=_G})
assert(loadfile(f,nil,t))()
return t
end
local A=myload("luaScriptA") A.init()
local B=myload("luaScriptA") B.init()
来源:https://stackoverflow.com/questions/22073216/luaj-loading-two-functions-with-the-same-name-from-two-different-luascripts