title: How to work with tables passed as an argument to a lua C function?
body: <p>I'm going to implement a function with C language and which will be called by Lua script.</p>
  
  <p>This function should receive a lua table as the argument, so I should read the fields in the table.I try to do like below, but my function is crashing when I run it. Can anyone help my find the problem?</p>
  
  <pre>
  <code>
  /*
   function findImage(options)
      imagePath = options.imagePath
      fuzzy = options.fuzzy
      ignoreColor = options.ignoreColor;
  
  
   end
  
   Call Example:
  
    findImage {imagePath="/var/image.png", fuzzy=0.5, ignoreColor=0xffffff}
  
   */
  
  
  // implement the function by C language
  static int findImgProxy(lua_State *L)
  {
      luaL_checktype(L, 1, LUA_TTABLE);
  
      lua_getfield(L, -1, "imagePath");
      if (!lua_isstring(L, -1)) {
          error();
      }
      const char * imagePath = lua_tostring(L, -2);
      lua_pop(L, 1);
  
      lua_getfield(L, -1, "fuzzy");
      if (!lua_isnumber(L, -1)) {
          error();
      }
      float fuzzy = lua_tonumber(L, -2);
  
      lua_getfield(L, -1, "ignoreColor");
      if (!lua_isnumber(L, -2)) {
          error();
      }
      float ignoreColor = lua_tonumber(L, -2);
  
      ...
  
      return 1;
  }
  </code>
  </pre>
  
  <p><em><strong>How about return a table from C to Lua:</em></strong></p>
  
  <pre>
  <code>
  struct Point {
      int x, y;
  }
  typedef Point Point;
  
  
  static int returnImageProxy(lua_State *L)
  {
      Point points[3] = {{11, 12}, {21, 22}, {31, 32}};
  
      lua_newtable(L);
  
      for (int i = 0; i  3; i++) {
          lua_newtable(L);
          lua_pushnumber(L, points[i].x);
          lua_rawseti(L, -2, 0);
          lua_pushnumber(L, points[i].y);
          lua_rawseti(L, -2, 1);
          lua_settable(L,-3);
      }
  
      return 1;   // I want to return a Lua table like :{{11, 12}, {21, 22}, {31, 32}}
  }
  </code>
  </pre>