| 3 | |
| 4 | |
| 5 | int main(int, char*[]) { |
| 6 | sol::state lua; |
| 7 | lua.script("function func (a, b) return (a + b) * 2 end"); |
| 8 | |
| 9 | sol::reference func_ref = lua["func"]; |
| 10 | |
| 11 | // maybe this is in a lua_CFunction you bind, |
| 12 | // or maybe you're trying to work with a pre-existing system |
| 13 | // maybe you've used a custom lua_load call, or you're |
| 14 | // working with state_view's load(lua_Reader, ...) call... |
| 15 | // here's a little bit of how you can work with the stack |
| 16 | lua_State* L = lua.lua_state(); |
| 17 | |
| 18 | // this is a handler: |
| 19 | // stack_aligned_stack_handler, |
| 20 | // as its type name explains so verbosely, |
| 21 | // expects the handler on the stack |
| 22 | sol::stack_reference traceback_handler(L, |
| 23 | -sol::stack::push( |
| 24 | L, sol::default_traceback_error_handler)); |
| 25 | // then, you need the function |
| 26 | // to be on the stack |
| 27 | func_ref.push(); |
| 28 | sol::stack_aligned_stack_handler_function func( |
| 29 | L, -1, traceback_handler); |
| 30 | lua_pushinteger(L, 5); // argument 1, using plain API |
| 31 | lua_pushinteger(L, 6); // argument 2 |
| 32 | |
| 33 | // take 2 arguments from the top, |
| 34 | // and use "stack_aligned_function" to call |
| 35 | int result = func(sol::stack_count(2)); |
| 36 | // function call pops function and arguments, |
| 37 | // leaves result on the stack for us |
| 38 | // but we must manually clean the traceback handler |
| 39 | // manually pop traceback handler |
| 40 | traceback_handler.pop(); |
| 41 | |
| 42 | // make sure everything is clean |
| 43 | SOL_ASSERT(result == 22); |
| 44 | SOL_ASSERT( |
| 45 | lua.stack_top() == 0); // stack is empty/balanced |
| 46 | |
| 47 | return 0; |
| 48 | } |