开发者

how do I clean up my lua state stack?

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


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.


additionally, instead of using pushstring or pushinteger followed by a gettable, use lua_getfield and lua_rawgeti respectivly (the raw will not invoke metamethods though, incase you wanted that...)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜