如何在 SWIG typemap 中检测表格是否具有字符串键

我试图为一个接受 Lua 表格作为参数的函数创建一个 SWIG typemap。

以下是我使用数字键的 typemap,它能够正常工作。

%typemap(in) (int argc, t_atom *argv)
{
    if (!lua_istable(L, $input))
        SWIG_exception(SWIG_RuntimeError, "argument mismatch: table expected");
    lua_len(L, $input);
    $1 = static_cast<lua_Integer>(lua_tointeger(L, -1));
    if (!$1) SWIG_exception(SWIG_RuntimeError, "table is empty");
    $2 = static_cast<t_atom *>(getbytes($1 * sizeof(t_atom)));
    for (int i = 0; i < $1; ++i)
    {
        lua_pushinteger(L, i + 1);
        lua_gettable(L, $input);
        if (lua_isboolean(L, -1))
        {
            $2[i].a_type = A_FLOAT;
            $2[i].a_w.w_float = static_cast<t_float>(lua_toboolean(L, -1));
        }
        else if (lua_isnumber(L, -1))
        {
            $2[i].a_type = A_FLOAT;
            $2[i].a_w.w_float = static_cast<t_float>(lua_tonumber(L, -1));
        }
        else if (lua_isstring(L, -1))
        {
            $2[i].a_type = A_SYMBOL;
            $2[i].a_w.w_symbol = gensym(lua_tostring(L, -1));
        }
        else
        {
            SWIG_exception(SWIG_RuntimeError, "unhandled argument type");
        }
    }
}
%typemap(freearg) (int argc, t_atom *argv)
{
    freebytes($2, $1 * sizeof(t_atom));
}

但是,当该函数接受带有字符串键的表格时,它只打印 SWIG_RuntimeError:table is empty

我想在打印该错误之前检测表格是否具有字符串键。

我尝试了以下条件,但它不起作用:

if (lua_type(L, -2) == LUA_TSTRING)

我该如何正确检测 SWIG typemap 中的表格参数是否至少具有一个字符串键?

点赞
用户11226352
用户11226352

一旦你知道表的长度为0(这意味着它没有整数键),你可以使用lua_next()获取下一个键值对。如果它返回任何值,那么你就知道表至少包含一个非整数键。

/* 表在栈的索引't'处,已知没有整数键 */
lua_pushnil(L);  /* 第一个键 */
if (lua_next(L, t) != 0) {
    /* 表包含非整数键 */
    lua_pop(L, 2);  /* 丢弃键值对 */
    /* 在这里做些事情 */
}

然而,关键字可能是表、浮点数或任何允许作为键的其他类型,因此如果您需要显式检查字符串键的出现,则必须在循环中调用lua_next()并检查每个返回的键的类型,直到找到字符串键或耗尽循环。

has_stringkey = false;
/* 表在栈的索引't'处 */
lua_pushnil(L);  /* 第一个键 */
while (lua_next(L, t)) {
    lua_pop(L, 1);  /* 丢弃值 */
    if (lua_type(L, -1) == LUA_TSTRING) {
        has_stringkey = true;
        lua_pop(L, 1);  /* 在退出循环之前丢弃关键字 */
        break;
    }
}
if (has_stringkey) { /* 做一些事情 */ }
2019-08-19 12:31:42