Tonight I played around with coroutines in Lua. After some Googling I figured out how to create and communicate with a Lua-thread from C++. It turned out to be really simple.
The lua program “loop.lua”
1
2
3
4
5
6
7
8
9
10
|
counter =
0
function
loop()
while
counter
do
print("Sending " .. counter);
coroutine
.
yield(counter);
counter = counter +
1
;
end
end
|
The C++ program
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
#include <stdio.h>
extern
"C"
{
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
int
main (
void
)
{
lua_State *L = lua_open();
luaL_openlibs(L);
if
(!luaL_loadfile(L,
"loop.lua"
)) {
lua_pcall(L, 0, 0, 0);
lua_State *L2 = lua_newthread(L);
lua_getglobal(L2,
"loop"
);
while
(1) {
puts
(
"while top"
);
int
res = lua_resume(L2, 0);
if
(res != 0) {
break
;
}
if
(lua_isnumber(L2, lua_gettop(L2)) == 1) {
printf
(
"Got %d\n"
,
lua_tonumber(L2, lua_gettop(L2))
);
}
}
}
lua_close(L);
return
0;
}
|