| 18 | }; |
| 19 | |
| 20 | int main() { |
| 21 | std::cout << "=== functions ===" << std::endl; |
| 22 | |
| 23 | sol::state lua; |
| 24 | lua.open_libraries(sol::lib::base); |
| 25 | |
| 26 | // setting a function is simple |
| 27 | lua.set_function("my_add", my_add); |
| 28 | |
| 29 | // you could even use a lambda |
| 30 | lua.set_function( |
| 31 | "my_mul", [](double x, double y) { return x * y; }); |
| 32 | |
| 33 | // member function pointers and functors as well |
| 34 | lua.set_function("mult_by_ten", multiplier {}); |
| 35 | lua.set_function("mult_by_five", &multiplier::by_five); |
| 36 | |
| 37 | // assert that the functions work |
| 38 | lua.script("assert(my_add(10, 11) == 21)"); |
| 39 | lua.script("assert(my_mul(4.5, 10) == 45)"); |
| 40 | lua.script("assert(mult_by_ten(50) == 500)"); |
| 41 | lua.script("assert(mult_by_five(10) == 50)"); |
| 42 | |
| 43 | // using lambdas, functions can have state. |
| 44 | int x = 0; |
| 45 | lua.set_function("inc", [&x]() { x += 10; }); |
| 46 | |
| 47 | // calling a stateful lambda modifies the value |
| 48 | lua.script("inc()"); |
| 49 | SOL_ASSERT(x == 10); |
| 50 | if (x == 10) { |
| 51 | // Do something based on this information |
| 52 | std::cout << "Yahoo! x is " << x << std::endl; |
| 53 | } |
| 54 | |
| 55 | // this can be done as many times as you want |
| 56 | lua.script(R"( |
| 57 | inc() |
| 58 | inc() |
| 59 | inc() |
| 60 | )"); |
| 61 | SOL_ASSERT(x == 40); |
| 62 | if (x == 40) { |
| 63 | // Do something based on this information |
| 64 | std::cout << "Yahoo! x is " << x << std::endl; |
| 65 | } |
| 66 | |
| 67 | // retrieval of a function is done similarly |
| 68 | // to other variables, using sol::function |
| 69 | sol::function add = lua["my_add"]; |
| 70 | int value = add(10, 11); |
| 71 | // second way to call the function |
| 72 | int value2 = add.call<int>(10, 11); |
| 73 | SOL_ASSERT(value == 21); |
| 74 | SOL_ASSERT(value2 == 21); |
| 75 | if (value == 21 && value2 == 21) { |
| 76 | std::cout << "Woo, value is 21!" << std::endl; |
| 77 | } |
nothing calls this directly
no test coverage detected