尝试对?(一个函数值)进行索引的Luaj。

我正在尝试编译 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 ? (a function value) 发生在 return compiledcode.invokemethod(func); 这一行,其中 getSameTiles 被作为 func 字符串传递。

这是我的 Lua 代码:

function getSameTiles()
    --My code here
end
点赞
用户2279620
用户2279620

有一些需要修复的问题。

首先,在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();
}
2014-03-03 18:12:36