1

同じ名前の関数を含む 2 つの Lua スクリプトがあります。

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 に答える