在Lua C-API中创建表中的表

时间:2016-06-24 13:14:09

标签: lua lua-table lua-api jnlua

我使用此代码在Lua C-API中创建表(Like namespace)中的表:

JNIEXPORT void JNICALL Java_com_naef_jnlua_LuaState_lua_1import_1tables(JNIEnv *env,
        jobject obj, jstring namespace) {
    lua_State *L;

    JNLUA_ENV(env);
    L = getluathread(obj);

    char *   str= getstringchars(namespace);
    char ** res  = NULL;
    char *  p    = strtok (str, ".");
    int n_spaces = 0, i;

    while (p) {
      res = realloc (res, sizeof (char*) * ++n_spaces);

      if (res == NULL)
        exit (-1);

      res[n_spaces-1] = p;

      p = strtok (NULL, ".");
    }

    for (i = 0; i < (n_spaces); ++i) {
        if (i == 0) {
            lua_newtable(L);
        } else if (i == (n_spaces - 1)) {
            lua_pushlstring(L, res[i], (sizeof(res[i])/sizeof(char))-1);
            lua_getglobal(L, res[i]);
            break;
        } else {
            lua_pushlstring(L, res[i], (sizeof(res[i])/sizeof(char))-1);
            lua_newtable(L);
        }
    }

    for (i = (n_spaces - 2); i >= 0 ; i--) {
        if (i == 0) {
            lua_setglobal(L, res[i]);
            break;
        } else {
            lua_settable(L, -3);
        }
    }

    free(res);
}

这可以等于这个硬编码:

lua_newtable( L );  /* ==> stack: ..., {} */
{
  lua_pushliteral( L, "b" ); /* ==> stack: ..., {}, "b" */
  lua_newtable( L ); /* ==> stack: ..., {}, "b", {} */
  {
    lua_pushliteral( L, "c" ); /* == stack: ..., {}, "b", {}, "c" */
    lua_newtable( L ); /* ==> stack: ..., {}, "b", {}, "c", {} */
    {
      lua_pushliteral( L, "d" );
      lua_getglobal(L, "MyTable");
      lua_settable( L, -3 );
    }
    lua_settable( L, -3 ); /* ==> stack: ..., {}, "b", {} */
  }
  lua_settable( L, -3 ); /* ==> stack: ..., {} */
}
lua_setglobal( L, "a" ); /* ==> stack: ... */

当我发送i函数Java_com_naef_jnlua_LuaState_lua_1import_1tables()字符串看起来像"com.naef.jnlua.test.fixture.TestObject"// TestObject is equivalent "MyTable", other like "com" tables in tables and TestObject table - the last table

当我尝试执行此代码后,执行lua代码com.naef.jnlua.test.fixture.TestObject

attempt to index field 'naef' (a nil value)

我错了?

0 个答案:

没有答案