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.

4

2 回答 2

2

把你的函数放在一个表中

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

然后你会做

globals.get("A").get("init").call();
globals.get("B").get("init").call();
于 2014-02-27T16:20:43.017 回答
0

下面的代码在自己的环境中加载脚本,该环境继承自全局环境,用于读取但不用于写入。换句话说,您可以调用print,但每个都定义了自己的init. 您可能必须做一些事情才能在 LuaJ 中使用它,但我不知道是什么。

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()
于 2014-02-27T16:54:54.587 回答