1 #define SOL_ALL_SAFETIES_ON 1
2 #include <sol/sol.hpp>
3
4 // Something that can't be collided with
5 static const auto& script_key = "GlobalResource.MySpecialIdentifier123";
6
7 struct GlobalResource {
8 int value = 2;
9 };
10
11 template <typename Handler>
sol_lua_check(sol::types<GlobalResource * >,lua_State * L,int,Handler && handler,sol::stack::record & tracking)12 bool sol_lua_check(sol::types<GlobalResource*>, lua_State* L, int /*index*/, Handler&& handler, sol::stack::record& tracking) {
13 // not actually taking anything off the stack
14 tracking.use(0);
15 // get the field from global storage
16 sol::stack::get_field<true>(L, script_key);
17 // verify type
18 sol::type t = static_cast<sol::type>(lua_type(L, -1));
19 lua_pop(L, 1);
20 if (t != sol::type::lightuserdata) {
21 handler(L, 0, sol::type::lightuserdata, t, "global resource is not present as a light userdata");
22 return false;
23 }
24 return true;
25 }
26
sol_lua_get(sol::types<GlobalResource * >,lua_State * L,int,sol::stack::record & tracking)27 GlobalResource* sol_lua_get(sol::types<GlobalResource*>, lua_State* L, int /*index*/, sol::stack::record& tracking) {
28 // retrieve the (light) userdata for this type
29
30 // not actually pulling anything off the stack
31 tracking.use(0);
32 sol::stack::get_field<true>(L, script_key);
33 GlobalResource* ls = static_cast<GlobalResource*>(lua_touserdata(L, -1));
34
35 // clean up stack value returned by `get_field`
36 lua_pop(L, 1);
37 return ls;
38 }
39
sol_lua_push(sol::types<GlobalResource * >,lua_State * L,GlobalResource * ls)40 int sol_lua_push(sol::types<GlobalResource*>, lua_State* L, GlobalResource* ls) {
41 // push light userdata
42 return sol::stack::push(L, static_cast<void*>(ls));
43 }
44
main()45 int main() {
46
47 sol::state lua;
48 lua.open_libraries(sol::lib::base);
49
50 GlobalResource instance;
51
52 // get GlobalResource
53 lua.set_function("f", [](GlobalResource* l, int value) { return l->value + value; });
54 lua.set(script_key, &instance);
55
56 // note only 1 argument,
57 // despite f having 2 arguments to recieve
58 lua.script("assert(f(1) == 3)");
59
60 return 0;
61 }
62