lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

David Dunham wrote:
> I'm in C, and want to copy all fields from one table into another
> one. Sort of the moral equivalent of 
> for k,v in pairs(a) do b.k = v end
> (which I don't think is correct in Lua).
> It seems like lua_next would be the way to iterate the table and get
> its keys and values -- it leaves them on the stack in such a way
> everything is ready for a call to lua_settable. But that pops the
> key, so that I can't then make the next lua_next call. (And I can't
> just push the key an extra time after lua_next, because then
> lua_settable wouldn't work.)     
> Am I missing something?

Here is a complete (untested) example:

function f(a, b)
  for k,v in pairs(a) do b[k] = v end

int f(lua_State* L)
  luaL_checktype(L, 1, LUA_TTABLE); /* a */
  luaL_checktype(L, 2, LUA_TTABLE); /* b */
  lua_pushnil(L); /* nil key to start iteration, stack:abk */
  while (lua_next(L, 1)) /* stack:abkv */
    lua_pushvalue(L, -2); /* copy key, stack:abkvk */
    lua_insert(L, -2); /* swap key and value, stack:abkkv */
    lua_settable(L, 2); /* stack:abk */
  return 0;