有没有办法将数据附加到协程,或者至少以某种方式识别不同的协程?
我正在尝试实现一个计时器 API,其中计时器由主机控制,在 Lua 端如下所示:
function callback()
local timer = ElapsedTimer()
...
end
function main()
local timer = CreateTimer(...)
StartTimer(timer, callback, ...)
end
StartTimer()
调用将计时器和回调发送到 C 端,C 端最终将在新的协程中调用回调。
对ElapsedTimer()
的调用需要返回特定于此协程/线程的数据,即在本例中为计时器。
在伪代码中:
int StartTimer(lua_State* L) {
auto timer = ...;
auto coroutine = ???
coroutine.userdata = &timer; // But probably store an actual structure with more pointers
return 0;
}
int ElapsedTimer(lua_State* L) {
auto coroutine = ???
auto timer = (Timer*)coroutine.userdata;
lua_pushlightuserdata(L, timer)
return 1;
}
这就是用户数据的用途:
int StartTimer(lua_State* L) {
TimerStruct timer = (TimerStruct*)lua_newuserdata(L, sizeof(TimerStruct));
//allocates some memory and returns pointer to it
timer->//...
// lua_setuservalue will let you bind the callback to the timer
return 1; //actually return it
}
此外,传递计时器也会更容易
function callback(timer)
...
end
这样,lua 代码就不需要查询该值。它已经明白了。
我刚刚意识到我需要使用lua_newthread
来创建协程,这意味着我有一个单独的lua_State
对象。 这意味着我始终可以在协程的状态和我想要的主机语言(例如映射数据结构(之间创建映射