MCPcopy Create free account
hub / github.com/ThePhD/sol2 / main

Function main

examples/source/tutorials/quick_n_dirty/running_lua_code.cpp:7–48  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

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

Callers

nothing calls this directly

Calls 5

removeFunction · 0.85
open_librariesMethod · 0.80
scriptMethod · 0.80
script_fileMethod · 0.80
validMethod · 0.45

Tested by

no test coverage detected