我正在尝试编译具有两个函数的Lua代码,我想调用它并从中获取一些信息但是当我在LuaValue对象上使用invokemethod时,我收到此错误
LuaError:尝试索引? (函数值)
代码位于我为方便起见而创建的LuaScript类中
首先调用此方法来编译文件
public void compile(File file) {
try {
Globals globals = JmePlatform.standardGlobals();
compiledcode = globals.load(new FileReader(file), "script");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
然后这用于从我的lua脚本中调用函数getSameTiles
public Object invoke(String func, Object... parameters) {
if (parameters != null && parameters.length > 0) {
LuaValue[] values = new LuaValue[parameters.length];
for (int i = 0; i < parameters.length; i++)
values[i] = CoerceJavaToLua.coerce(parameters[i]);
return compiledcode.invokemethod(func, LuaValue.listOf(values));
} else
return compiledcode.invokemethod(func);
}
错误LuaError: attempt to index ? (a function value)
发生在return compiledcode.invokemethod(func);
行,其中"getSameTiles"
作为func
这是我的Lua代码
function getSameTiles()
--My code here
end
答案 0 :(得分:1)
有几个问题需要修复。
首先,在lua中,load()
返回一个函数,然后您需要调用该函数来执行该脚本。
其次,脚本的作用是向全局表_G
添加一个函数。为了调用该函数,您需要从Globals
表中获取函数并调用它。
以下代码执行此操作
Globals globals = JmePlatform.standardGlobals();
public void compile(File file) {
try {
globals.load(new FileReader(file), "script").call();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public Object invoke(String func, Object... parameters) {
if (parameters != null && parameters.length > 0) {
LuaValue[] values = new LuaValue[parameters.length];
for (int i = 0; i < parameters.length; i++)
values[i] = CoerceJavaToLua.coerce(parameters[i]);
return globals.get(func).call(LuaValue.listOf(values));
} else
return globals.get(func).call();
}