获取用于在Lua中创建协同程序/线程的函数



是否可以获得用于创建协同程序的原始函数?

thread = coroutine.create(function()
   -- Code
end)
f = get_function_from_thread(thread) 

你不能开箱即用,但你总是可以重新定义coroutine.create:

local create=coroutine.create
local created={}
function coroutine.create(f)
   local t=create(f)
   created[t]=f
   return t
end
function get_function_from_thread(t)
   return created[t]
end

如果您创建了许多协同程序,请考虑将created设置为弱表。

值得一提的是,可以使用debug.getinfo开箱即用地执行此操作,但仅当协程处于屈服或运行状态时。

func = function () for i = 1, 4 do coroutine.yield(4) end end
co = coroutine.create(func)
assert(debug.getinfo(co, 1) == nil, "must have resumed at least once")
coroutine.resume(co)
assert(debug.getinfo(co, 1).func == func, 
    "getinfo can get the func from its stack")
while coroutine.status(co) ~= "dead" do coroutine.resume(co) end
assert(debug.getinfo(co, 1) == nil, "its stack is gone after returning")

确认使用Lua 5.1和LuaJIT 2.1.0。

最新更新