Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I clean up my lua state stack?

Tags:

c++

c

lua

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?

like image 489
ohmyfromage Avatar asked Feb 18 '10 21:02

ohmyfromage


2 Answers

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).

like image 150
Norman Ramsey Avatar answered Oct 03 '22 23:10

Norman Ramsey


It depends.

If your C function is called from Lua, the values you leave behind will be the values that your C function returns to Lua. If your C function is called by another C function that uses the Lua stack, then those values will still be on the stack, and you can do anything or nothing with them.

But if after you've called your C function you're done with Lua altogether, and from your question it sounds as though you are, then you don't have to clean up your Lua stack. Just close the Lua context, and it will clean up your stack for you.

like image 20
David Seiler Avatar answered Oct 03 '22 23:10

David Seiler