【发布时间】:2020-02-05 16:39:29
【问题描述】:
有没有办法将数据附加到协程,或者至少以某种方式识别不同的协程?
我正在尝试实现一个计时器 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;
}
【问题讨论】: