有一個很好的機會,我正在做奇怪的事情導致這個錯誤。(更新)LuaJ:無法在Lua腳本中調用'require'函數
下面的簡單示例失敗:
--> thingy.lua
function doThing()
print("Thing has been done.");
end
和
--> test.lua
require("thingy");
當thingy.lua被執行時,不存在任何問題。當執行test.lua,我看到以下錯誤:
script:2 module 'thingy' not found: thingy
no field package.preload['thingy']
thingy.lua
no class 'thingy'
在同一目錄中這兩個文件的存在,我可以運行使用賽特沒有錯誤兩個腳本(這是運行的Lua 5.1)。這似乎是一個路徑問題,所以我嘗試將package.path設置爲源文件的絕對路徑。
注:我設置的路徑,而不是追加,這樣我可以做出一定的賽特不是因爲現有的相對路徑「.lua?」的成功。我在LauJ(使用我自己的程序)和SciTE中進行了測試,發現SciTE能夠執行test.lua,而LuaJ仍然無法執行,從而產生與往常一樣的錯誤。
有什麼我應該做的(或不做)在Java代碼中可能會導致這種情況嗎?我已經成功從Lua腳本訪問Java,而不是其他 Lua腳本。只要手動運行包含它們的腳本,我就可以訪問LuaJ中的全局變量和函數。
只是爲了更好的衡量,這裏是我用來執行腳本的Java代碼。
// some fancy Java code
public void execute() throws ScriptException, LuaError
{
try
{
FileReader reader = new FileReader(filename);
Script_Engine.eval(reader);
reader.close();
}
catch(FileNotFoundException fnfe)
{
fnfe.printStackTrace();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
public void callFunction(String functionName, Object[] args) throws Exception
{
File scriptFile = new File(filename);
FileReader reader = new FileReader(scriptFile);
CompiledScript script = ((Compilable)Script_Engine).compile(reader);
script.eval(Script_Bindings);
LuaFunction lua_function = (LuaFunction)Script_Bindings.get(functionName);
LuaValue[] vals = new LuaValue[args.length];
for(int i = 0; i < args.length; i++)
{
vals[i] = CoerceJavaToLua.coerce(args[i]);
}
lua_function.invoke(vals);
reader.close();
}
兩個函數中使用的'文件名'變量是在外殼類的構造函數中創建的。我發現,無論問題是什麼,它都存在於LuaJ 3.0版(我使用的是JSE包)中。將3.0-alpha2 JAR文件替換爲較舊的2.03 JAR後,問題不再存在。雖然我很滿意現在可以繼續使用舊版本的LuaJ,但我仍然希望使用最新版本。
也有一些是在LuaJ自述發現here,上面寫着以下內容:
When require() is called, it will first attempt to load the module as a Java class that implements LuaFunction.
並根據發行說明部分:
3.0-alpha2
Supply environment as second argument to LibFunction when loading via require()
我強烈懷疑它是與這是因爲它是在版本3.0-alpha2中添加的,所以我下載了版本3.0-alpha1(正在使用3.0-alpha2),期待它的工作,但它沒有。
謝謝你的回答。我對此感到困惑,爲什麼這不起作用 - package.path實際上被忽略了(通過將其設置爲''「'並使用名爲* foo.lua *的文件運行require('foo')' – Qix