我不知道該怎麼做,在痛飲模板,但我設法堵塞__call
痛飲生成調用luaopen_module
後由C的metatable ++:
SWIG_Lua_get_class_metatable(L_, PointVector);
SWIG_Lua_add_function(L_, "__call", lua_vector_iterator);
所以矢量可以作爲迭代器。有點笨拙2合1,但工作原理:
> = 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)
迭代器返回索引和值,如在Python enumerate()
,和Lua傳遞指數回下一個時間(在堆棧上第三ARG)迭代。我沒有看到這種行爲記錄,所以我可能依靠實施細節。
這裏是用作__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;
}