如何在目标协程中获取协程的名称?

我想要像这样:

local co1 = coroutine.create(function()
    local evt, _, _, nm, arg1 = event.pull("thread_msg", 2)
    -- 获取一个 "thread_msg" 事件。

    if(nm == coroutine_name)then
        print(evt, arg1) -- 打印事件名称和"thread_msg"发送的参数
    end
end)

coroutine.resume(co1)
event.push("thread_msg", "co1", "") -- 向协程发送一条消息

我需要协程的名称。"thread_msg"事件发送到所有正在运行的协程,coroutine.send也是如此。我需要在协程内部获取协程的名称。

使用mc版本1.12.2 forge的opencomputers。 CPU的架构是lua 5.3。 谢谢。

点赞
用户11740758
用户11740758

你可以使用load()函数加载 coroutine 的代码。

因为使用load()函数可以给函数起一个名字,并存储在debug.getinfo()表中的source中。

如果 coroutine /函数出现错误时,也会使用source信息显示出错的位置。

下面是在 Lua 交互控制台中,使用coroutine.wrap()函数构建 coroutine 函数的基本示例…

$ /usr/bin/lua
Lua 5.3.5  Copyright (C) 1994-2018 Lua.org, PUC-Rio
> code={}
> run={}
> code.co=[[return coroutine.wrap(function(...)
>> local args={...} -- args 保存传入函数的参数
>> args[0]=debug.getinfo(1).source -- 使用 `load(textcode, 'Name')` 给函数命名
>> print(args[0],'Going to yielding now')
>> coroutine.yield(args)
>> args=[0]=debug.getinfo(1).source -- 如果在循环中调用更多 coroutines ,则可以在此处更新 args[0]
>> print('Going to end:',args[0])
>> print(args[0],'Coroutine goes dead now')
>> return args
>> end)]]
> run[1]=load(code.co,'Megacoroutine')()
> run[1]()
Megacoroutine   Going to yielding now
table: 0x565e2890
> run[1]()
Going to end:   Megacoroutine
Megacoroutine   Coroutine goes dead now
table: 0x565e2890
> run[1]()
stdin:1: cannot resume dead coroutine
stack traceback:
    [C]: in field '?'
    stdin:1: in main chunk
    [C]: in ?
>

编辑:args 必须是local(已更正)

2021-08-09 09:00:22