---
title: "C++读取lua table"
author: "mrjeye"
date: "2015-02-02T14:36:26Z"
tags: []
categories: ["移动开发"]
slug: "c-lua-table"
draft: false
lastmod: "2015-02-02T14:36:26Z"
id: 2182560
url: "https://mrjeye.iteye.com/blog/2182560"
---

```
lua_pushnil(tolua_S);
      int index = lua_gettop(tolua_S);
      
      map<string, string> dict;
      // 现在的栈：-1 => nil; index => table
      index = index - 1;
      while (lua_next(tolua_S, index))
      {
          // 现在的栈：-1 => value; -2 => key; index => table
          // 拷贝一份 key 到栈顶，然后对它做 lua_tostring 就不会改变原始的 key 值了
          lua_pushvalue(tolua_S, -2);
          // 现在的栈：-1 => key; -2 => value; -3 => key; index => table
          
          const char* key = lua_tostring(tolua_S, -1);
          const char* value = lua_tostring(tolua_S, -2);
//          if (lua_isstring(tolua_S, -2)) {
//              dict->setObject(CCString::create(lua_tostring(tolua_S, -2)), key);
//          } else if (lua_isnumber(tolua_S, -2)) {
//              dict->setObject(CCDouble::create(lua_tonumber(tolua_S, -2)), key);
//          }
          dict[key] = value;
          
          // 弹出 value 和拷贝的 key，留下原始的 key 作为下一次 lua_next 的参数
          lua_pop(tolua_S, 2);
          // 现在的栈：-1 => key; index => table
      }
```