1 #define SOL_ALL_SAFETIES_ON 1
2 #include <sol/sol.hpp>
3
4
main(int,char * [])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 working
14 // 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, -sol::stack::push(L, sol::default_traceback_error_handler));
23 // then, you need the function
24 // to be on the stack
25 func_ref.push();
26 sol::stack_aligned_stack_handler_function func(L, -1, traceback_handler);
27 lua_pushinteger(L, 5); // argument 1, using plain API
28 lua_pushinteger(L, 6); // argument 2
29
30 // take 2 arguments from the top,
31 // and use "stack_aligned_function" to call
32 int result = func(sol::stack_count(2));
33 // function call pops function and arguments,
34 // leaves result on the stack for us
35 // but we must manually clean the traceback handler
36 // manually pop traceback handler
37 traceback_handler.pop();
38
39 // make sure everything is clean
40 sol_c_assert(result == 22);
41 sol_c_assert(lua.stack_top() == 0); // stack is empty/balanced
42
43 return 0;
44 }
45