【问题标题】:Getting function used to create coroutine/thread in Lua获取用于在 Lua 中创建协程/线程的函数
【发布时间】:2015-05-03 18:35:55
【问题描述】:

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

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

f = get_function_from_thread(thread) 

【问题讨论】:

  • 给你的匿名函数起一个名字,这样你以后可以参考它。然后在coroutine.create 时通过该名称引用该函数。你到底想做什么?
  • 我有一些函数包含上值(在另一个模块的另一个函数中创建)。我正在编写的函数接收协程/线程,但我想访问存储在原始函数中的上值
  • debug.getlocaldebug.get(set)upvalue 之类的东西可能有助于使用这些调试功能,因为这是代码异味。

标签: lua coroutine


【解决方案1】:

您无法开箱即用,但您始终可以重新定义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 设置为弱表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-03
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    • 2011-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多