lua-users home
lua-l archive

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


On Tue, 12 Jan 2010 08:23:28 +0200, Juris Kalnins <juris@mt.lv> wrote

do
   a=1
   do
     a=2
     g() -- access to a gives 2
   end
   -- a == 1
end

ugh, correcting myself. what I wrote mixes up definitions and assignments, I should have written:

do a=1
  do dynamic a=2
    g() -- access to a gives 2
  end   -- a == 1
end

where 'dynamic' is like 'local' in perl :)
There are already many ways to do it right now. Usually code has to pass around some context as an
extra argument, and the above looks like:

do ctx.a=1
  do
    local prev_a = ctx.a
    ctx.a = 2
    g(ctx)
    ctx.a = prev_a
  end
end

You can even "smuggle" 'ctx' through functions that are not aware of it (e.g. gsub), by capturing it as
upvalue.
When writing parser or GUI code, there is a lot of such 'ctx' passing and value saving.
Dynamic scoping makes writing such code very natural.