I don't know if this is what you are trying to do, but...
Replace:
lua_pushstring(L, "value (item 2)"); // push
lua_settable(L, -3); // pop 2
lua_setglobal(L, "2ndtable"); // pop 1
lua_getglobal(L, "2ndtable"); // push 1
lua_settable(L, -3); // push 2
lua_setglobal(L, "testtable");
with:
lua_pushstring(L, "value (item 2)"); // push
lua_settable(L, -3); // pop 2
lua_pushvalue(L, -1);
lua_setglobal(L, "2ndtable"); // pop 1
lua_settable(L, -3); // push 2
lua_setglobal(L, "testtable");
I have not tested, but might work.
--rb