gpt4 book ai didi

java - Luaj 尝试索引? (一个函数值)

转载 作者:行者123 更新时间:2023-11-30 11:21:41 25 4
gpt4 key购买 nike

我正在尝试编译具有两个函数的 Lua 代码,我想调用这两个函数并从中获取一些信息,但是当我在 LuaValue 对象上使用 invokemethod 时,出现此错误

LuaError: attempt to index ? (a function value)

代码在我为方便起见创建的 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 ? (函数值) 出现在 return compiledcode.invokemethod(func); 行,其中 "getSameTiles" 作为 func< 的字符串传递

这是我的Lua代码

function getSameTiles()
--My code here
end

最佳答案

有几个问题需要解决。

首先,在 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();
}

关于java - Luaj 尝试索引? (一个函数值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22131855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com