Skip to main content

This documentation is for an older version of this product. See the latest version of this content.Opens in a new tab

For 文 (1)

For 文を使用すると、コードのセクションを繰り返し実行できます。For の引数はカウンタ変数で、開始値、増分値、終了値が割り当てられています。すべての値は正、または負で、コロンで区切られています。For に続くコード・ブロックは、変数に割り当てられた各値を繰り返します。また、For の引数は値のリストを割り当てる変数とすることもできます。この場合、コード・ブロックはそれぞれのリスト項目を、変数に繰り返し割り当てます。For は、他の文と同様、コンマで区切られた複数の引数を持つことができます。また、1 つの For にカウンタとリスト引数の両方を持つことができます。For 文の構文は以下のとおりです。


for variable = start:increment:stop {code}
for variable = val_1, val_2, ..., value_N {code}

For のコード・ブロック内では、Continue コマンドを使用できます。これは現在の繰り返しを停止しますが、ループは継続します。

値を終了せずに For のカウンタ引数を指定できます。通常、これは無限ループとなります。しかし、コード・ブロック内に Quit または Return を配置し、For 文を終了させます。この場合、繰り返し内でカウンタを使用します。しかし、カウンタ値を条件にしない For も制御できます。カウンタの必要がない場合、引数なしFor を使用します。この場合も、コード・ブロック内に Quit または Return が必要になります。このような For の使い方は、条件が 1 (True) に等しい While または Do/While 文を使用することと同じです。

先ほど、QuitReturn が同じであることを学習しました。しかし、For のコード・ブロック内で使用した場合、これらのコマンドは異なる動作をします。

  • Quit はループを終了するだけです。

  • Return はループを終了し、さらに現在のクラス・メソッド、プロシージャ、またはルーチンも終了します。

For の例:

VS Code - ObjectScript


/// examples for ObjectScript Tutorial
Class ObjectScript.Examples
{
 
/// demos of the For construct
ClassMethod For()
{
    for i = 1:1:8 {
        write !, "I ", i, " the sandbox."
    }
    write !!
    for b = "John", "Paul", "George", "Ringo" {
        write !, "Was ", b, " the leader? "
        read yn
    }
    write !!
    for i = 1:1 {
        read !, "Capital of MA? ", a
        if (a = "BOSTON") {
            write "...did it in ", i, " tries"
            quit
        }
    }
    write !!
    for i = 1:1 {
        read !, "Capital of TX? ", a
        continue:(a '= "AUSTIN")
        write "...did it in ", i, " tries"
        quit
    }
    write !!
    for {
        read !, "Know what? ", wh
        quit:(wh = "NO!")
        write "   That's what!"
    }    
}
}
ターミナルを使用したテスト


USER>do ##class(ObjectScript.Examples).For()

I 1 the sandbox.
I 2 the sandbox.
I 3 the sandbox.
I 4 the sandbox.
I 5 the sandbox.
I 6 the sandbox.
I 7 the sandbox.
I 8 the sandbox.
 
 
Was John the leader? y
Was Paul the leader? n
Was George the leader? n
Was Ringo the leader? n
 
 
Capital of MA? BAHSTON
Capital of MA? WORCESTER
Capital of MA? SPRINGFIELD
Capital of MA? BOSTON...did it in 4 tries
 
 
Capital of TX? HOUSTON
Capital of TX? SAN ANTONIO
Capital of TX? AUSTIN...did it in 3 tries


Know what? WHAT?   That's what!
Know what? WHAT?   That's what!
Know what? WHAT?   That's what!
Know what? NO!
USER>

FeedbackOpens in a new tab