protect¶
routine to mark a function / variable as requiring safety
template <typename T>
auto protect( T&& value );
sol::protect( my_func ) allows you to protect a function call or member variable call when it is being set to Lua. It can be used with usertypes or when just setting a function into sol. Below is an example that demonstrates that a call that would normally not error without Safety features turned on that instead errors and makes the Lua safety-call wrapper pcall fail:
1#define SOL_ALL_SAFETIES_ON 1
2#include <sol/sol.hpp>
3
4
5int main(int, char*[]) {
6
7 struct protect_me {
8 int gen(int x) {
9 return x;
10 }
11 };
12
13 sol::state lua;
14 lua.open_libraries(sol::lib::base);
15 lua.new_usertype<protect_me>(
16 "protect_me", "gen", sol::protect(&protect_me::gen));
17
18 lua.script(R"__(
19 pm = protect_me.new()
20 value = pcall(pm.gen,"wrong argument")
21 )__");
22 bool value = lua["value"];
23 SOL_ASSERT(!value);
24
25 return 0;
26}