[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: RE: Copying one table into another (in C)
- From: "Jerome Vuarand" <jerome.vuarand@...>
- Date: Wed, 15 Aug 2007 21:20:55 -0400
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
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;
}