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的 then-expression 。
实际上,只有第一个条件评估为true才被评估为true。
Meta讨论FFL,(1)只要表达式内部应满足条件,并返回对应于真实条件的所有 then-expressions 列表,就有意义了。整个条件表达式没有执行触发器(bind_command
,;
等)?另外(2)是否已经存在(显然具有不同的签名)?
答案 0 :(得分:2)
我认为if函数可以评估并返回通过。我只看过2参数和3参数if函数在野外使用,因此我刚刚发现n参数参数版本时就无法评论。 (这似乎等同于“如果,否则,……,否则”。匈奴。)
对于条件/语句列表,我所知道的最接近的语法是:
on_create: "filter([
true and debug('cmd 1'),
false and debug('cmd 2'),
true and debug('cmd 3'),
], value)",
这将在屏幕上显示“ cmd 1”和“ cmd 3”。
之所以有效,是因为and
短路,并且仅返回要通过的第一件事或最后通过的失败。仅当您要使用filter()
和true
时才需要false
调用,否则可以使用true和null并丢弃filter()
。请注意,您也可以在此结构中使用;
,我认为它的结果是一个命令序列,您可以像正常命令一样使用和处理该命令序列。例如:
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)",
在屏幕上打印“ cmd 1”,“ cmd 4”和“ cmd 5”。
这等效于:
on_create: "[
if(true, debug('cmd 1')),
if(false, debug('cmd 2'); debug('cmd 3')),
if(true, debug('cmd 4'); debug('cmd 5')),
]",
还将在屏幕上打印“ cmd 1”,“ cmd 4”和“ cmd 5”。如果您需要从列表中消除null元素,则可以像第一个示例一样使用filter。
答案 1 :(得分:0)
您想要的是一系列if
语句。通过将多个if语句放在一行中已经很容易实现。用其他语言看是非常清楚和普遍的。为此,具有自定义结构将是多余的,只会降低清晰度。
另一方面,实现重复的else-if的结构对于减少嵌套非常有用。 (过多的嵌套会引起可读性问题,并造成混乱的机会。)
if condition, then action
else-if condition, then action (optional)
...
else-if condition, then action (optional)
else action (optional)