By now, you have probably noticed that working with the Lua stack can get a bit confusing. Some functions push and pop values onto the stack and others don't. You can find out how each function manipulates the stack by reading through the Lua reference manual, available at: https://www.lua.org/manual/5.2/.
If you scroll down the manual page a bit, every Lua function is listed. Clicking on any of the C API functions will show the signature of the function, a description of how the function works, and some stack information. The manual page for the lua_setfield function as follows:
The stack information is called out in the upper right of the function. There are always three entries in this information box. The first one is how many elements the function removes from the stack, the second number is how many elements the function adds to the stack, and the...