lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hello,

I just discovered that coroutines have their own independent set of
hooks, and don't inherit any from their creator, but I can't find where
it says so in the documentation.

Could the documentation perhaps make this obvious somehow, or am I just
blind?  And is there an easy way to make coroutines inherit hooks upon
creation?

I guess one ridiculous solution that jumps out at me is this:

local old_cr_create = coroutine.create
function coroutine.create(fn)
	local fn,mask,count = debug.gethook()
	return old_cr_create(function(...)
		debug.sethook(fn,mask,count)
		return fn(unpack(arg))
	end)
end

Except debug.gethook() returns the string "external hook" instead of a
function reference, because I did this in C.  Argh!  Well, I used a
variant of that continue my own work.  So I guess I answered my own
question.

I'm working on an allocation profiler (without calling lua from inside
realloc() this time... :]) and I noticed that coroutine.resume() was
making lots of garbage, but of course it obviously wasn't, because none
of the coroutine functions showed up at all.

If others are interested I will clean it up and add it to the wiki; it
displays a flat profile showing the line numbers that allocated the most
live memory and the line numbers that generated the most garbage.

-Andy


(trivial demonstration of coroutines not invoking hooks below)
------------------------------------
function hookfn(trigger, line)
    local info = debug.getinfo(2)
    print((info.name or '?').."["..info.source..":"..line.."]")
end

function crfn()
    local i
    print('coroutine started')
    for i=1,10 do
        print('hi i am a coroutine '..i)
    end
end

function test()
    debug.sethook(hookfn, "l")
    local x=1
    x = x + 1
    print('stuff')
    local cr = coroutine.create(crfn)
    coroutine.resume(cr)
end

test()