1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <fstream>
#include <iostream>
int main(int, char*[]) {
std::cout << "=== running lua code ===" << std::endl;
{
std::ofstream out("a_lua_script.lua");
out << "print('hi from a lua script file')";
}
sol::state lua;
lua.open_libraries(sol::lib::base);
// load and execute from string
lua.script("a = 'test'");
// load and execute from file
lua.script_file("a_lua_script.lua");
// run a script, get the result
int value = lua.script("return 54");
SOL_ASSERT(value == 54);
auto bad_code_result = lua.script("123 herp.derp",
[](lua_State*, sol::protected_function_result pfr) {
// pfr will contain things that went wrong, for
// either loading or executing the script Can
// throw your own custom error You can also just
// return it, and let the call-site handle the
// error if necessary.
return pfr;
});
// it did not work
SOL_ASSERT(!bad_code_result.valid());
// the default handler panics or throws, depending on your
// settings uncomment for explosions: auto bad_code_result_2
// = lua.script("bad.code", &sol::script_default_on_error);
std::cout << std::endl;
{ std::remove("a_lua_script.lua"); }
return 0;
}
|