【问题标题】:How to get access to variables from outer Block in nested one?如何从嵌套块中的外部块访问变量?
【发布时间】:2021-12-15 21:52:14
【问题描述】:

我尝试使用 C# 扩展树编写一些简单的 Brainf*ck 执行器。 但我不能让循环工作。

我有这样的输入:++++++++++++++++++++[>>+<++<-]>.>. 在 CST 建设之后:

() => {
    int index;
    LazyDictionary<int, char> lent;
    index = 0;
    lent = #LazyDictionary<int, char>;
    lent[index] = (char)(lent[index] + 20);
    while (true) {
        if (lent[index] == '') {
            break;
        } else {
            index += (int)2;
            lent[index] = (char)(lent[index] + 1);
            index -= (int)1;
            lent[index] = (char)(lent[index] + 2);
            index -= (int)1;
            lent[index] = (char)(lent[index] - 1);
        }
    };
    index += (int)1;
    Console.Write(lent[index]);
    index += (int)1;
    Console.Write(lent[index]);
}

看起来应该可以,但问题是变量。

while 循环中的语句是嵌套的ExpressionBlock,任何使用lentindex 都会导致以下异常:

从范围“”引用的“System.Int32”类型的变量“索引”,但未定义

我构建循环的代码是这样的

cstLoopNode.Inner.Visit(this);

var prebody = Buffer.Pop();
var breakLabel = Expression.Label();
var condition = Expression.Equal(CurrentLentValueExpression, Expression.Constant('\0'));
var loopStopper = Expression.IfThenElse(condition, Expression.Break(breakLabel), prebody);

Buffer.Push(Expression.Loop(loopStopper, breakLabel));

变量prebody 包含一个内部语句块。如果我在创建块时添加变量,它会在正文中创建具有相同名称的新变量。如果我不添加它们,我就没有这个变量,也无法访问外部块中的变量。

有没有办法创建一个嵌套的语句块,可以从外部块访问变量?

【问题讨论】:

    标签: c# expression-trees


    【解决方案1】:

    当你使用Expression.Block 创建一个块时,你会给出一个局部变量的集合。这些应该在块和任何子块中可见。如果您在遍历之前不知道所需的变量,则必须将所需的变量冒泡到 Block 的声明中。

    BlockExpression.Variables

    【讨论】:

      猜你喜欢
      • 2015-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-08
      • 1970-01-01
      相关资源
      最近更新 更多