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

Function main

examples/source/coroutine_state.cpp:6–53  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

4#include <iostream>
5
6int main(int, char*[]) {
7 std::cout << "=== coroutine state transfer ==="
8 << std::endl;
9
10 sol::state lua;
11 lua.open_libraries();
12 sol::function transferred_into;
13 lua["f"] = [&lua, &transferred_into](
14 sol::object t, sol::this_state this_L) {
15 std::cout << "state of main : "
16 << (void*)lua.lua_state() << std::endl;
17 std::cout << "state of function : "
18 << (void*)this_L.lua_state() << std::endl;
19 // pass original lua_State* (or
20 // sol::state/sol::state_view) transfers ownership from
21 // the state of "t", to the "lua" sol::state
22 transferred_into = sol::function(lua, t);
23 };
24
25 lua.script(R"(
26 i = 0
27 function test()
28 co = coroutine.create(
29 function()
30 local g = function() i = i + 1 end
31 f(g)
32 g = nil
33 collectgarbage()
34 end
35 )
36 coroutine.resume(co)
37 co = nil
38 collectgarbage()
39 end
40 )");
41
42 // give it a try
43 lua.safe_script("test()");
44 // should call 'g' from main thread, increment i by 1
45 transferred_into();
46 // check
47 int i = lua["i"];
48 SOL_ASSERT(i == 1);
49
50 std::cout << std::endl;
51
52 return 0;
53}

Callers

nothing calls this directly

Calls 4

open_librariesMethod · 0.80
scriptMethod · 0.80
safe_scriptMethod · 0.80
lua_stateMethod · 0.45

Tested by

no test coverage detected