| 4 | #include <iostream> |
| 5 | |
| 6 | int main() { |
| 7 | const auto& co_lua_script = R"( |
| 8 | function loop() |
| 9 | while counter ~= 30 |
| 10 | do |
| 11 | coroutine.yield(counter); |
| 12 | counter = counter + 1; |
| 13 | end |
| 14 | return counter |
| 15 | end |
| 16 | )"; |
| 17 | |
| 18 | sol::state lua; |
| 19 | lua.open_libraries(sol::lib::base, sol::lib::coroutine); |
| 20 | /* |
| 21 | lua.script_file("co.lua"); |
| 22 | we load string directly rather than use a file |
| 23 | */ |
| 24 | lua.script(co_lua_script); |
| 25 | sol::coroutine loop_coroutine = lua["loop"]; |
| 26 | // set counter variable in C++ |
| 27 | // (can set it to something else to |
| 28 | // have loop_coroutine() yield different values) |
| 29 | lua["counter"] = 20; |
| 30 | |
| 31 | // example of using and re-using coroutine |
| 32 | // you do not have to use coroutines in a loop, |
| 33 | // this is just the example |
| 34 | |
| 35 | // we start from 0; |
| 36 | // we want 10 values, and we only want to |
| 37 | // run if the coroutine "loop_coroutine" is valid |
| 38 | for (int counter = 0; counter < 10 && loop_coroutine; |
| 39 | ++counter) { |
| 40 | // Alternative: counter < 10 && cr.valid() |
| 41 | |
| 42 | // Call the coroutine, does the computation and then |
| 43 | // suspends once it returns, we get the value back from |
| 44 | // the return and then can use it we can either leave |
| 45 | // the coroutine like that can come to it later, or |
| 46 | // loop back around |
| 47 | int value = loop_coroutine(); |
| 48 | std::cout << "In C++: " << value << std::endl; |
| 49 | } |
| 50 | |
| 51 | return 0; |
| 52 | } |
nothing calls this directly
no test coverage detected