2013-08-21 9 views
6

के साथ सी में एक लुआ टेबल Iterate मैं ऑर्डर्ड टेबल सरल उदाहरण का उपयोग करना चाहता हूं, मुझे लुआ-विकी साइट पर मिला। यहां the link है।एक कस्टम जोड़ी फ़ंक्शन

लुआ में यह इस के साथ ठीक iterates:

for i,v in t:opairs() do 
    print(i,v) 
end 

इसके बजाय बार-बार दोहराना lua में, मैं एक सी विधि को t गुजरती हैं और वहाँ मेज पुनरावृति चाहते हैं। सी एपीआई में मुझे मूल pairs इटेटर के लिए केवल lua_next मिला। मैं सी में इस लुआ कोड को कैसे पुन: स्थापित कर सकता हूं?

उत्तर

2

आप क्या कर सकते हैं एक कस्टम next सी फ़ंक्शन लिखना है जो lua_next की नकल करता है लेकिन opairs विधि के बजाय उस आदेशित तालिका पर काम करता है।

int luaL_orderednext(luaState *L) 
{ 
    luaL_checkany(L, -1);     // previous key 
    luaL_checktype(L, -2, LUA_TTABLE); // self 
    luaL_checktype(L, -3, LUA_TFUNCTION); // iterator 
    lua_pop(L, 1);      // pop the key since 
             // opair doesn't use it 

    // iter(self) 
    lua_pushvalue(L, -2); 
    lua_pushvalue(L, -2); 
    lua_call(L, 1, 2); 

    if(lua_isnil(L, -2)) 
    { 
    lua_pop(L, 2); 
    return 0; 
    } 
    return 2; 
} 

फिर आप lua_next सी समान में इसका इस्तेमाल कर सकते हैं:

int orderedtraverse(luaState *L) 
{ 
    lua_settop(L, 1); 
    luaL_checktype(L, 1, LUA_TTABLE); 

    // t:opairs() 
    lua_getfield(L, 1, "opairs"); 
    lua_pushvalue(L, -2); 
    lua_call(L, 1, 2); 

    // iter, self (t), nil 
    for(lua_pushnil(L); luaL_orderednext(L); lua_pop(L, 1)) 
    { 
    printf("%s - %s\n", 
      lua_typename(L, lua_type(L, -2)), 
      lua_typename(L, lua_type(L, -1))); 
    } 
    return 0; 
} 

ध्यान दें, मैं यह परीक्षण नहीं किया था, लेकिन यह काम करना चाहिए।

संबंधित मुद्दे