I am using the lua C-API to read in configuration data that is stored in a lua file.
I’ve got a nice little table in the file and I’ve written a query C-function that parses out a specific field in the table. (yay it works!)
It works by calling a few of these kinds of functions over and over:
...
lua_getglobal (...);
lua_pushinteger (...);
lua_gettable (...);
lua_pushstring (...);
lua_gettable (...);
lua_lua_getfield (...);
...
you get the idea.
After I am done querying my data like this, do I have to clean up the stack?
As long as your stack doesn’t grow without bound, you’ll be fine. When you return integer N from the C API into Lua, two things happen:
The Lua engine takes the top N values from the stack and considers them as the results of the call.
The Lua engine deallocates (and reuses) everything else on the stack.
David Seiler mentions the possibility of your C code being called from other C code and not from the Lua engine. This is an advanced technique, and if you are asking this question, you are unlikely to have to worry about that particular issue. (But the way it happens from Lua’s perspective is the same—when all the C code finishes executing, it has to return an integer, and Lua peels that many values off the stack and then deallocates the rest.)
If you use too many stack slots, your program will halt with a sane and sensible error message (as I know from experience).