【问题标题】:Luaj attempt to index ? (a function value)Luaj 尝试索引? (一个函数值)
【发布时间】:2014-04-03 14:54:28
【问题描述】:

我正在尝试编译具有两个要调用并从中获取一些信息的函数的 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

【问题讨论】:

    标签: java lua luaj


    【解决方案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();
    }
    

    【讨论】:

      猜你喜欢
      • 2021-05-08
      • 2017-04-22
      • 2016-05-09
      • 1970-01-01
      • 2015-10-25
      • 1970-01-01
      • 2017-02-07
      • 2020-04-08
      • 2019-10-10
      相关资源
      最近更新 更多