Search code examples
lualuaj

LuaJ loading two functions with the same name from two different LuaScripts


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.


Solution

  • 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();