This project is read-only.

Assigning parameter in simple lamda throws exception

Dec 31, 2009 at 2:49 PM

I've been toying around with the for a short while now, I've modified the Sympl-example language back and forth, and read a lot of the IronPython and IronRuby source code. So today I sat down to try to start creating my own toy language.

Hit a brick wall after five minutes. Kind of dampened by spirit, but maybe some of you here can explain what I'm doing wrong (both in code and in reasoning). The code I have is


            // ... snipped for brevity

            using Ast = System.Linq.Expressions;

            // ... snipped for brevity 

            var exprs = new List<Ast.Expression>();

                    Ast.Expression.Parameter(typeof(string), "foo"),

            var action = Ast.Expression.Lambda<Action>(Ast.Expression.Block(exprs)).Compile();

When I try to compile this code on the second last line, all I get is an exception saying "variable 'foo' of type 'System.String' referenced from scope '', but it is not defined", I'm missing something basic here I know, but I just can't figure it out. 

The code above is shortened from what my real code does, basically it tries to compile this variable declaration: "var foo ='bar';" which means the foo variable needs to be defined. I have a feeling that what I'm trying to do above is assigning to an already existing parameter/variable, and not actually creating it in the first place... or something along those lines.

Dec 31, 2009 at 3:59 PM
Edited Dec 31, 2009 at 4:03 PM

You're very close. You just need to add the variable declaration to the block definition:

var exprs = new List<Ast.Expression>();
var foo = Ast.Expression.Parameter(typeof(string), "foo");
exprs.Add(Ast.Expression.Assign(foo, Ast.Expression.Constant("bar")));
var action = Ast.Expression.Lambda<Action>(Ast.Expression.Block(new [] { foo }, exprs)).Compile();

For clarity, it would also be good to use Expression.Variable instead of Expression.Parameter. These are nearly identical, but "Variable" does a better job of expressing the intent of your code.