[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Coroutine bug?
- From: Lorenzo Donati <lorenzodonatibz@...>
- Date: Mon, 20 Jun 2011 07:13:12 +0200
On 20/06/2011 6.08, Ian Godin wrote:
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.
You forgot a "local" in front of function "check". This way "check" is a
global function and you are redefining it every time you create a coroutine.
is just syntactic sugar for:
check = function()
and, without that "local" declaration, the variable "check" is global.
Every time the statement "function check()" is executed, you assign a
new closure (with obj as upvalue) to global var "check".
Therefore you overwrite "check" when the second coroutine is first
started (second "resume"), so the "obj" upvalue for the first coroutine
is lost together with the first closure assigned to "check".
When you resume the second coroutine for the second time (third call to
resume), its execution resumes where it yielded (in the while loop), but
then you call check (global), which retains the closure created _in the
second coroutine_ (with ITS obj upvalue, i.e. that created in the second
call to resume), so "check" prints out the data for the "obj" argument
of the second coroutine.