This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
tesla1889's profile picture

get function from coroutine

Started by tesla1889, 25 November 2013 - 04:36 PM
tesla1889 #1
Posted 25 November 2013 - 05:36 PM
say there is a coroutine C created from the function F:
C = coroutine.create(F)
is there any way to get the function F, given only the coroutine C?
Papa_Beans #2
Posted 25 November 2013 - 07:00 PM
You are setting C to equal the coroutine of F, am I correct? So arent you getting the function F if you declare C? Trick question?
Lyqyd #3
Posted 25 November 2013 - 08:15 PM
I'm fairly certain that what you're asking is impossible. Why do you ask?
tesla1889 #4
Posted 25 November 2013 - 10:32 PM
i would like to implement the UNIX fork function:

function fork()

local C = coroutine.running()

local F = someMagic(C)

local C_child = coroutine.create(F)

passCoroutineBackToScheduler(C_child)

end

or something similar such that one simply has to call fork to branch into two coroutines
Edited on 25 November 2013 - 09:33 PM
Bubba #5
Posted 26 November 2013 - 10:02 AM
Why not simply store the function in a table upon using coroutine create - perhaps use function overwriting?



coroutine.native = {} for i,v in pairs(coroutine) do if type(v) == "function" then coroutine.native[i] = v end end

coroutine.active = {}
coroutine.create = function(...)
  table.insert(coroutine.active, {...})
  return {#coroutine.active, coroutine.native.create(...)}
end

coroutine.resume = function(co, ...)
  return coroutine.native.resume(co[2],...)
end

--#Reimplement other coroutine functions here

function fork()
  local c = coroutine.running()
  local f = coroutine.active[1][c[1]]
  local c_child = coroutine.create(f)
  passCoroutineBackToScheduler(c_child)
end

Not tested, but you get the idea. Of course, if you wanted to get the function of any coroutine created before running this code, that is still impossible. However for most purposes I think this would work fine.
Edited on 27 November 2013 - 08:15 AM
jay5476 #6
Posted 26 November 2013 - 03:32 PM
Couldn't you just do something like this

oldCreate = coroutine.create
function coroutine.create(func)
  local t = oldCreate(func)
  t.function = func
  return t
end
Edited by
Bubba #7
Posted 26 November 2013 - 03:50 PM
Couldn't you just do something like this

oldCreate = coroutine.create
function coroutine.create(func)
  local t = oldCreate(func)
  t.function = func
  return t
end

Coroutine.create returns a thread, not a table.
Edited on 26 November 2013 - 03:00 PM
Kingdaro #8
Posted 26 November 2013 - 05:24 PM
I'm not sure if this would solve your problem, but you could use coroutine.wrap() instead of coroutine.create(), which returns a function that works the same as a coroutine, and "coroutine.resume(co)" would be "co()" using a wrapped coroutine.