3

我正在尝试设置一个条件来评估几个文本列表的值。这工作,使用开关:

options: ["" "" "" ""]

view layout [
    text-list "one" "two" "three" "four" [poke options 1 value]
    button "test" [switch/default options/1 [
        "one" [alert "first"]
        "two" [alert "second"]
        "three" [alert "third"]
        "four" [alert "fourth"]
        ] [alert "pick a number!"]
    ]
]

但是由于某种原因,这个不起作用:

options: ["" "" "" ""]

view layout [
    text-list "one" "two" "three" "four" [poke options 1 value]
    button "test" [
        either options/1 <> 0 [
          alert "you have picked a number!"
        ][alert "pick a number!"]
    ]
]

如果我将其作为条件,则 EITHER 评估始终执行第一个块,如果我将options/1 <> 0其作为条件,则始终执行第二个块options/1 = 0,这显然不是它应该如何工作的。

这是怎么回事?

4

2 回答 2

3

您正在使用空字符串来表示“无”状态。正如@iceflow19 指出的那样,字符串和整数永远不会比较相等。如果您想知道字符串是否为空,请使用 EMPTY? ""or 与or进行逐字比较{}

(注意:我自己通常更喜欢花括号字符串,并且{It's cool that they {nest better} and can do "quotes" and apostrophe's [sic] without escaping.}

Rebol 有另一种表示虚无的可能性,那就是类型为 NONE! 的值。一个不错的财产,没有!价值在于它将表现得像一个逻辑!就 IF、UNLESS 和 EITHER 而言,false 值会起作用。

value: none

if value [print {this won't run}]

unless value [print {this will run}]

一些例程使用 NONE! 值作为它们的返回值,以指示正常的“失败”情况。IF 和 UNLESS 是这样的例程:

>> print if 1 < 2 [{math is working}]
math is working

>> print if 1 > 2 [{math is broken}]
none ;-- Rebol2 prints out the string representation of NONE!

(注意:如果 IF、UNLESS 或 EITHER 是单个值,则 Rebol3 不要求您将条件放入块中。)

所以你可以写:

options: reduce [none none none none]

view layout [
    text-list {one} {two} {three} {four} [poke options 1 value]
    button {test} [
        alert either options/1 [
            {you have picked a number!}
        ][{pick a number!}]
    ]
]

之所以需要 REDUCE,是因为默认情况下不对块进行评估......并且您会出现四次none(相对于 NONE! 类型的值,NONE 绑定到该值)。

另请注意,您可以将 SWITCH 或 EITHER 的结果传递给警报,它将是运行的分支的最后一个评估值。如果没有分支运行,则没有 - 如上所示。

(注意:你可能很快就会想要的构造——如果你还没有发现的话——是CASE 和 ALL。)

于 2015-08-28T19:04:17.773 回答
2

它工作正常,条件本身就是问题。单词 'value 将引用一个字符串值。(“一”、“二”、“三”或“四”)

When "one" is selected, it will insert the string "one" into the options block in position 1.

>> probe options
== ["one" "" "" ""]

>> probe options/1
== "one"

您的不等式是比较字符串类型的值!到整数类型的值 0!字符串永远不会等于整数,因此条件将始终评估为真。因此,将始终运行 ' 上的第一个代码路径。

当您使用切换比较选项/1(一个字符串!)到字符串“一”、“二”、“三”和“四”时。例如,如果 options/1 = "two",第一种情况会失败,因为 "two" <> "one",但第二种情况会成功,因为 "two" = "two"(无论是值还是类型)​​。

于 2015-08-28T16:29:07.663 回答