代码之家  ›  专栏  ›  技术社区  ›  1737973

高级ffl:条件表达式然后激活表达式

  •  2
  • 1737973  · 技术社区  · 7 年前

    以下是来自 https://github.com/anura-engine/anura/blob/55bc02244f0faba5e0831578a3c1c9a82e7bf569/src/formula_function.cpp#L923-L931 :

        FUNCTION_DEF(if, 2, -1, "if(a,b,c)")
    
            const int nargs = static_cast<int>(NUM_ARGS);
            for(int n = 0; n < nargs-1; n += 2) {
                const bool result = EVAL_ARG(n).as_bool();
                if(result) {
                    return EVAL_ARG(n+1);
                }
            }
    

    如我们所见,如果有多个条件评估为真,则只有 然后表达式 对应于第一个条件求值为true的返回。

    实际上,只有求值为true的第一个条件才被求值为true。

    元讨论FFL,(1)表达式应该计算所有条件并返回所有条件的列表是否有意义 然后表达式 与真条件相对应,只要整个条件表达式的内部没有执行触发器( bind_command , ; 等等)?还有(2)这个已经存在了吗(显然有不同的签名)?

    2 回复  |  直到 7 年前
        1
  •  2
  •   Zoe - Save the data dump 张群峰    7 年前

    我认为if函数计算并返回passing是有意义的。我只见过2参数和3参数if函数在野外使用,所以我不能评论n参数版本,因为我刚刚发现它。(它似乎相当于“if,else if,else”。哼。)

    我所知道的条件/语句列表最接近的语法如下:

    on_create: "filter([
        true and debug('cmd 1'),
        false and debug('cmd 2'),
        true and debug('cmd 3'),
    ], value)",
    

    这将在屏幕上打印“命令1”和“命令3”。

    这有效是因为 and 短路,只返回第一个通过或最后一个失败的东西。这个 filter() 只有当您想使用 true 和 false ,否则可以使用true、null和drop 筛选器() . 注意,您还可以使用 ; 有了这个构造,我认为它的计算结果是一个命令序列,您可以像普通命令一样使用和处理它。例如:

    on_create: "filter([
        true and debug('cmd 1'),
        false and (debug('cmd 2'); debug('cmd 3')),
        true and (debug('cmd 4'); debug('cmd 5')),
    ], value)",
    

    将“命令1”、“命令4”和“命令5”打印到屏幕上。

    这相当于:

    on_create: "[
        if(true, debug('cmd 1')),
        if(false, debug('cmd 2'); debug('cmd 3')),
        if(true, debug('cmd 4'); debug('cmd 5')),
    ]",
    

        2
  •  0
  •   Patrick Parker    7 年前

    你想要的是 if 声明。通过将多个if语句放在一行中已经很容易实现了这一点。在其他语言中,这是非常清楚和常见的。因此,有一个自定义的结构将是多余的,只会降低清晰度。

    另一方面,实现重复else if的结构对于减少嵌套非常有用。(过多的嵌套会导致可读性问题,并造成混淆的机会。)

    if condition, then action
    else-if condition, then action (optional)
    ...
    else-if condition, then action (optional)
    else action (optional)