1

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.

Monolo
  • 18,205
  • 17
  • 69
  • 103
AvdB
  • 65
  • 7

2 Answers2

2

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();
Oliver
  • 27,510
  • 9
  • 72
  • 103
0

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()
lhf
  • 70,581
  • 9
  • 108
  • 149