1

lua/std_vector.iSWIG 2.0.8 评论中说:

并且不支持迭代器和插入/擦除

但也许有人知道该怎么做?

例如,可以#通过定义添加长度运算符__len(它可能是偶然的,我通过反复试验找到了它):

%include "std_vector.i"
%extend std::vector { int __len(void*) { return self->size(); } }
namespace std {
    %template(PointVector) vector<fityk::Point>;
}

我已经尝试过类似的技巧__call,但我被卡住了。SWIG 包装妨碍了。我已经尝试使用%native,但无法使其与%extend.

4

1 回答 1

0

I don't know how to do it in SWIG template, but I managed to plug __call to SWIG-generated metatable from C++, after calling luaopen_module:

    SWIG_Lua_get_class_metatable(L_, PointVector);
    SWIG_Lua_add_function(L_, "__call", lua_vector_iterator);

So the vector can be used as iterator. A bit awkward 2 in 1, but works:

> = points
<PointVector userdata: 190FBE8>
> for n, p in points do print(n, p) end
0       (24.0154; 284; 16.8523)
1       (24.0541; 343; 18.5203)

The iterator returns index and value, like enumerate() in Python, and Lua passes the index back to the iterator next time (3rd arg on the stack). I haven't seen this behaviour documented, so I may rely on implementation details.

Here is the function used as __call():

// SWIG-wrapped vector is indexed from 0. Return (n, vec[n]) starting from n=0.
static int lua_vector_iterator(lua_State* L)
{
    assert(lua_isuserdata(L,1)); // in SWIG everything is wrapped as userdata
    int idx = lua_isnil(L, -1) ? 0 : lua_tonumber(L, -1) + 1;

    // no lua_len() in 5.1, let's call size() directly
    lua_getfield(L, 1, "size");
    lua_pushvalue(L, 1); // arg: vector as userdata
    lua_call(L, 1, 1);   // call vector<>::size(this)
    int size = lua_tonumber(L, -1);

    if (idx >= size) {
        lua_settop(L, 0);
        return 0;
    }

    lua_settop(L, 1);
    lua_pushnumber(L, idx); // index, to be returned
    lua_pushvalue(L, -1);   // the same index, to access value
    lua_gettable(L, 1);     // value, to be returned
    lua_remove(L, 1);
    return 2;
}
于 2012-10-26T22:35:25.260 回答