如何解决lua错误:"attempt to index ? (a nil value)"

有很多关于这种错误的帖子,大多数人都说它和表和数组索引问题有关。但我根本没有使用表格,我只是尝试调用我制作的库函数,然后我得到了这个错误。这是从 Java 调用的 Lua 脚本:

String script = new String (
             "function event_touch (  )"
            + "   pb.open_form ('view_monster');"
            + "   print ('I ran the lua script');"
            + "end");

PBLUAengine.run_script(script, "event_touch");

当捕获异常时,这会给我以下错误:

"function event_touch ( ) pb.open_form ('view_monster'); print ('I ran the lua script');end:1 attempt to index ? (a nil value)"

run_script()函数像这样调用脚本(我正在使用 luaj):

public static LuaValue run_script ( String script )
    {
        try
        {
            LuaValue chunk = s_globals.load( script );
            return chunk.call();
        }
        catch ( Exception e)
        {
           Gdx.app.error ("PBLUAengine.run_script()", e.getMessage() );
        }

        return null;
    }

库方法是这样的,当从 Java 调用时,相同的代码块起作用:

static class open_form extends OneArgFunction
{
        public LuaValue call (LuaValue formname)
        {
            String tmpstr = (String ) CoerceLuaToJava.coerce(formname, java.lang.String.class );

            try
            {
                PBscreen_game.hide_subscreen(PBscreen_game.MENU_SUBS);
                PBscreen_game.show_subscreen ( PBscreen_game.FORM_SUBS);
                PBsubscreen_form.open_form ( new PBform_regular ( tmpstr ) );
            }
            catch (Exception e)
            {
                Gdx.app.error("PBLUAlibrary.open_form", e.getMessage());
            }

            return valueOf ( 0 );
        }
    }

它基本上将 lua 参数转换为字符串,创建一个新式样,并将字符串作为参数传递。

库函数的声明如下:

public LuaValue call( LuaValue modname, LuaValue env )
    {
        LuaValue library = tableOf();
        library.set( "open_form", new open_form() );
        library.set( "open_system_form", new open_system_form() );
        env.set( "pb", library );
        return library;
    }

这可能是我在整个系统中看到的唯一的“表格”。这通常用于将正确的类与正确的函数名称链接起来。

有什么想法吗?

原文链接 https://stackoverflow.com/questions/31666659

点赞
stackoverflow用户501459
stackoverflow用户501459

大多数人说这与表格和数组索引问题有关。如果您尝试索引一个对象,而该对象为 nil,则会出现此错误:

我根本没有使用表格[…]这是 lua 脚本:

pb.open_form

正在对 pb 进行索引,它很可能是 nil

2015-07-28 19:27:44
stackoverflow用户4230413
stackoverflow用户4230413

似乎通过添加 require 行以引入库解决了问题。所以新的脚本为:

String script = new String (
            "require 'com.lariennalibrary.pixelboard.library.PBLUAlibrary'"
            + "function event_touch ()"
            + "   pb.open_form ('view_monster');"
            + "   print ('我运行了下一步按钮的lua脚本');"
            + "end");

这要求包括我的库类,它将添加所有的“pb.*”函数。我可能不小心删除了这行,或者在没有它的情况下以某种方式使它工作。由于这个库将被所有脚本所需,我可能会在尝试运行每个脚本之前默认追加它。

再次感谢。

2015-07-29 23:49:07