gibbss
gibbss

Reputation: 2033

How to pop / clean Lua call stack from C

I want to pop / clean the Lua call stack while within a C function called from Lua. Is this possible?

Background:
I want my C library and its extension scripts to use the same test framework. (I am aware various unit testing tools exist for Lua. I don't care; I want one report) I'm wrapping CUnit in a thin layer of Lua. CUnit provides a choice of fatal and non-fatal test assertions. Fatal assertions cause an immediate longjmp out of the test and back into the framework runner. This seems like it would do bad things to the Lua VM if I did not clean the stack first.

The stack will probably look something like:

#0. C:   assert_wrapper_fcn(test, fatal)
#1. Lua: assert_fcn(bool)
#2. Lua: test_fcn()
#3. C:   runner(&test_fcn)

I want to clean up everything between #0 and #3. I know the method signatures of test_fcn() and assert_fcn(bool), but that's it.

Upvotes: 3

Views: 2461

Answers (3)

Hisham H M
Hisham H M

Reputation: 6798

My suggestion is to use Lua's own assert system, and then trap that in your runner and then forward the error to your unit testing framework:

Launch your Lua code with lua_pcall.

From within your Lua code, trigger fatal errors with the standard assert command.

From where you launched your Lua code, check the result of lua_pcall and when you get != 0, trigger your CUnit fatal assertion failure.

This will avoid mixing any longjmp's between Lua and CUnit.

Upvotes: 2

prapin
prapin

Reputation: 6877

To empty the stack is really easy. Just use lua_settop with 0 as argument.

lua_settop(L, 0);

Upvotes: 8

Graham Perks
Graham Perks

Reputation: 23400

Not sure I'm understanding the question quite right... but to clear out Lua's stack:

int stackSize = lua_gettop(L);
lua_pop(L, stackSize);

Upvotes: 2

Related Questions