Forループ

提供: AutoHotkey Wiki
移動: 案内検索

実行制御 | GUI表示 | 演算・変数 | メモリ・DLL操作 | 文字列操作 | キーボード | マウス | シェル | ウィンドウ | ウィンドウグループ
ステータスバー | コントロール | サウンド | ファイル | INIファイル | レジストリ | 環境変数 | AutoHotkey | その他 | 設定関係 | オブジェクト

Forループ [AHK_L 59+][編集]

AHKL 指定のオブジェクトのキーと値の各組に対して一連のコマンドを繰り返す。

For, Key [, Value] in Expression

Parameters[編集]

Key 繰り返し毎にキー名を格納させる変数を指定する。
Value 繰り返し毎にフィールド値を格納させる変数を指定する。
Expression オブジェクトを返す式、あるいはオブジェクトを格納する式変数を指定する。

Remarks[編集]

Expression はループ前に一度だけ評価される。
Expression がオブジェクトを返さない場合はループ本体はスキップされる。
そうでない場合は、オブジェクトの NewEnum() メソッド経由でEnumerator オブジェクトを取得しループで利用することになる。
各繰り返しの直前に、Enumerator の Next() メソッドを利用しキーと値の組が取り出される。
Next() メソッドの戻り値が偽の場合にループは終了する。

リビジョン59より前のバージョンで同様の事を行うには以下のようにする:

_enum := (Expression)._NewEnum()
While _enum.Next(Key, Value)
{
  ...
}

Forループは繰り返しの本体となる一連の処理命令をブロック{...}として持つのが普通であるが、繰り返し処理が単一行で終わる場合はブロック記号({...})を省略することが出来る。(他のループやIfなどの仕様と同様である)

中括弧を次行に書かずに、ステートメントの末尾に配置する書き方も利用可能である。例) 「for x,y in z{

他のループ系と同様に、Break, Continue および A_Index が利用できる。

COM Objects[編集]

Since Key and Value are passed directly to the enumerator's Next() method, the values they are assigned depends on what type of object is being enumerated. For COM objects, Key contains the value returned by IEnumVARIANT::Next() and Value contains a number which represents its variant type. For example, when used with a Scripting.Dictionary object, each Key contains a key from the dictionary and Value is typically 8 for strings and 3 for integers. See ComObjType for a list of type codes.

[v1.0.96.00+]: When enumerating a SafeArray, Key contains the current element and Value contains its variant type.

Related[編集]

Enumerator object, Object.NewEnum(), Whileループ, Loop, Until, Break, Continue, Blocks

Example(s)[編集]

; List the key-value pairs of an object:
colours := Object("red", 0xFF0000, "blue", 0x0000FF, "green", 0x00FF00)
; The above expression could be used directly in place of "colours" below:
For k, v in colours
    s .= k "=" v "`n"
MsgBox % s
; List all open Explorer and Internet Explorer windows:
For window in ComObjCreate("Shell.Application").Windows
    windows .= window.LocationName " :: " window.LocationURL "`n"
MsgBox % windows