How to implement lexical closures?

grom <grom358@gmail.com>
Thu, 6 May 2010 21:22:21 -0700 (PDT)

          From comp.compilers

Related articles
How to implement lexical closures? grom358@gmail.com (grom) (2010-05-06)
Re: How to implement lexical closures? sleepdev@gmail.com (andy johnson) (2010-05-09)
Re: How to implement lexical closures? gneuner2@comcast.net (George Neuner) (2010-05-09)
Re: How to implement lexical closures? cr88192@hotmail.com (BGB / cr88192) (2010-05-09)
Re: How to implement lexical closures? torbenm@diku.dk (2010-05-10)
Re: How to implement lexical closures? grom358@gmail.com (grom) (2010-05-11)
Re: How to implement lexical closures? cr88192@hotmail.com (BGB / cr88192) (2010-05-12)
[10 later articles]
| List of all articles for this month |
From: grom <grom358@gmail.com>
Newsgroups: comp.compilers
Date: Thu, 6 May 2010 21:22:21 -0700 (PDT)
Organization: Compilers Central
Keywords: parse, question
Posted-Date: 09 May 2010 12:20:38 EDT

I'm working on a toy interpreter (http://code.google.com/p/zemscript/)
and trying to implement lexical closures (http://code.google.com/p/
zemscript/source/browse/#svn/branches/lexical_scope) . Currently when
the function is created it copies the symbol table. So the following
code works:
newCounter = function() {
        i = 0;
        return function() {
                i = i + 1;
                return i;
        };
};


c1 = newCounter();
c2 = newCounter();
println(c1() ~ " == 1");
println(c1() ~ " == 2");
println(c2() ~ " == 1");
println(c1() ~ " == 3");
println(c2() ~ " == 2");


However since it copies the symbol table the following does *not*
work:
create = function() {
        x = 0;
        return {
                "get" : function() { return x; },
                "set" : function(v) { x = v; }
        };
};


o = create();
o["set"](42);
println(o["get"]()); // Should print 42


What I can't work out is how I can get the second example to work
without breaking the first example.


Ant build file: http://pastebin.com/qDaZethE


Post a followup to this message

Return to the comp.compilers page.
Search the comp.compilers archives again.