lua-users home
lua-l archive

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


I am trying to use threads/coroutines, but it looks like local
variables are getting overwritten... it's behaving as if a single
local variable exists, when I expected each coroutine to have it's own
local variables.  The original was much more complicate (using the Lua
C API, etc...), but I've managed to simplify it to a Lua-only script
that reproduces the problem.  It's obviously just a toy example, but
it replicates my problem.

I've been beating my head against this for a bit now, and I am at a
loss... hopefully someone can figure out what I'm doing wrong (or
confirm it as a Lua bug).

I create 2 separate tables, which I pass into 2 separate coroutines.
The same function is usedwhich are using the same function).
Everything works like I expected the first time I resume (start) each
coroutines.  But on the second resume of the first coroutine
(obj1.thread), it appears to get the local variables from the second
coroutine.  The local variable I am taking about is the argument
"obj".

  Thanks for any help,
    Ian

function thecoroutine( obj )
    function check()
        if obj.thread ~= coroutine.running() then
            print( "bad object for thread: " .. tostring(obj) .. "
thread = " .. tostring(obj.thread) .. " running = " ..
tostring(coroutine.running())  )
        else
            print( "good object for thread: " .. tostring(obj) .. "
thread = " .. tostring(obj.thread) .. " running = " ..
tostring(coroutine.running())  )
        end
    end

    print( "Script started " .. tostring(obj) .. " thread = " ..
tostring(obj.thread) .. "   running = " ..
tostring(coroutine.running()) )
    check()

    while true do
        coroutine.yield()
        check()
    end
end

local obj1 = { thread = coroutine.create( thecoroutine ) }
local obj2 = { thread = coroutine.create( thecoroutine ) }

coroutine.resume( obj1.thread, obj1 )
coroutine.resume( obj2.thread, obj2 )
coroutine.resume( obj1.thread, obj1 )