zoukankan      html  css  js  c++  java
  • Lua C API 遍历 table

    http://timothyqiu.com/archives/lua-note-table-traversal-using-c-api/

    C API 遍历 Table

    1 lua_getglobal(L, t);
    2 int index = lua_gettop(L);
    3 lua_pushnil(L);
    4 while (lua_next(L, index)) {
    5     /* 此时栈上 -1 处为 value, -2 处为 key */
    6     lua_pop(L, 1);
    7 }

    lua_next 函数针对 -2 处(参数指定)的 Table 进行遍历。弹出 -1 处(栈顶)的值作为上一个 key(为 nil 时视为请求首个 key),压入 Table 中的下一个 key 和 value。返回值表示是否存在下一个 key。

    lua_next 原理详解

    另外在循环中处理值时要记得随时清理栈,否则 Table 就不在 -2 了。(也可以考虑在 lua_getglobal 后用lua_gettop 存下 Table 的正数索引。)

  • 相关阅读:
    HDU --1251
    POJ -- 2436
    POJ -- 3140
    POJ 3107
    POJ -- 2002
    POJ -- 1655
    lintcode154
    lintcode192
    lintcode582
    lintcode901
  • 原文地址:https://www.cnblogs.com/hangj/p/5192588.html
Copyright © 2011-2022 走看看