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

Function main

examples/source/basic.cpp:6–79  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

4#include <iostream>
5
6int main() {
7 std::cout << "=== basic ===" << std::endl;
8 // create an empty lua state
9 sol::state lua;
10
11 // by default, libraries are not opened
12 // you can open libraries by using open_libraries
13 // the libraries reside in the sol::lib enum class
14 lua.open_libraries(sol::lib::base);
15 // you can open all libraries by passing no arguments
16 // lua.open_libraries();
17
18 // call lua code directly
19 lua.script("print('hello world')");
20
21 // call lua code, and check to make sure it has loaded and
22 // run properly:
23 auto handler = &sol::script_default_on_error;
24 lua.script("print('hello again, world')", handler);
25
26 // Use a custom error handler if you need it
27 // This gets called when the result is bad
28 auto simple_handler =
29 [](lua_State*, sol::protected_function_result result) {
30 // You can just pass it through to let the
31 // call-site handle it
32 return result;
33 };
34 // the above lambda is identical to sol::simple_on_error,
35 // but it's shown here to show you can write whatever you
36 // like
37
38 //
39 {
40 auto result = lua.script(
41 "print('hello hello again, world') \n return 24",
42 simple_handler);
43 if (result.valid()) {
44 std::cout << "the third script worked, and a "
45 "double-hello statement should "
46 "appear above this one!"
47 << std::endl;
48 int value = result;
49 SOL_ASSERT(value == 24);
50 }
51 else {
52 std::cout << "the third script failed, check the "
53 "result type for more information!"
54 << std::endl;
55 }
56 }
57
58 {
59 auto result
60 = lua.script("does.not.exist", simple_handler);
61 if (result.valid()) {
62 std::cout << "the fourth script worked, which it "
63 "wasn't supposed to! Panic!"

Callers

nothing calls this directly

Calls 4

open_librariesMethod · 0.80
scriptMethod · 0.80
whatMethod · 0.80
validMethod · 0.45

Tested by

no test coverage detected