How will I be able to obtain the coroutine's name in the targetted coroutine?

Viewed 132

I want something like this:

local co1 = coroutine.create(function()
    local evt, _, _, nm, arg1 = event.pull("thread_msg", 2)
    -- Pull a "thread_msg" event.

    if(nm == coroutine_name)then
        print(evt, arg1) -- Print the event name and the argument sent by "thread_msg"
    end
end)

coroutine.resume(co1)
event.push("thread_msg", "co1", "") -- Sends a message to the coroutine

I need the coroutine's name. "thread_msg" event sends to all of the running coroutines, same for coroutine.send. I need to obtain the name of coroutine inside the coroutine.

Working with opencomputers with mc version 1.12.2 forge. The architecture of the CPU is lua 5.3. Thanks.

1 Answers

You can load() the coroutine' code.
Because with load() you can give functions a name that will be stored in source of debug.getinfo()' table.
This source will also be used if an error occurs in the coroutine/function traceback.
I give you a basic example for the Lua interactive console with the easy/lazy coroutine.wrap() function to construct the coroutine function...

$ /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 is holding arguments
>> args[0]=debug.getinfo(1).source -- Name given by load(textcode,'Name')
>> print(args[0],'Going to yielding now')
>> coroutine.yield(args)
>> args=[0]=debug.getinfo(1).source -- Update args[0] here if called more coroutines in loop
>> 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 ?
>

EDIT: args has to be local (corrected)

Related