1

Lua スクリプトから呼び出される関数を C 言語で実装します。

この関数は、引数として (配列を含む) lua テーブルを受け取る必要があるため、テーブル内のフィールドを読み取る必要があります。誰でも問題を見つけるのを手伝ってもらえますか?


/*
 function findImage(options)
    imagePath = options.imagePath
    fuzzy = options.fuzzy
    ignoreColors = options.ignoreColor;
    ...
 end

 Call Example:

 findImage {
              imagePath="/var/image.png", 
              fuzzy=0.5,
              ignoreColors={
                             0xffffff, 
                             0x0000ff, 
                             0x2b2b2b
                           }
            }

 */

static int findImgProxy(lua_State *L)
{
    lua_settop(L, 1);
    luaL_checktype(L, 1, LUA_TTABLE);

    lua_getfield(L, -1, "imagePath");
    lua_getfield(L, -2, "fuzzy");
    lua_getfield(L, -3, "ignoreColors");

    const char *imagePath = luaL_checkstring(L, -3);
    double fuzzy    = luaL_optint(L, -2, -1);

    int count  = lua_len(L, -1); // how to get the member count of ignoreColor array

    int colors[count];
    for (int i=0; i count; i++) {
        lua_rawgeti(L, 4, i);
        colors[i] = luaL_checkinteger(L, -1);
        lua_pop(L, 1);
    }

    lua_pop(L, 2);

    ...
    return 1;
}

4

2 に答える 2

1
int count  = lua_len(L, -1); // how to get the member count of ignoreColor array

int colors[count];
for (int i=0; i count; i++)
{
    colors[i] = luaL_checkinteger(L, -1-i);
}

このコード セグメントは正しくないようです (ループ内に比較演算子がないことは気にしないでください)。テーブルの長さを取得するための正しい関数は ですlua_objlen。「ignoreColor」から数値を取得しようとしているようですが、最初にスタックに配置していません。その結果、スタック上の間違ったインデックスluaL_checkinteger(L, -1-i);にアクセスすることになります。

たとえば、これに近いものが必要になるでしょう。

int count  = lua_objlen(L, -1);
std::vector<int> colors(count);
for (int i = 0; i < count; lua_pop(L, 1))
{
  lua_rawgeti(L, 4, ++i);
  colors.push_back( luaL_checkinteger(L, -1) );
}

Lua 5.2 を使用している場合は、次のように置き換えますlua_objlen

int count  = lua_rawlen(L, -1);

テーブルから多くの要素を移動する場合は、スタックに十分なスペースがあることを確認してください。例えば。lua_checkstack

于 2013-09-05T13:32:01.997 に答える