跳转至内容

Rexx 编程/Rexx 指南/循环

来自维基教科书,开放的书籍,为开放的世界

循环是控制结构,允许代码段根据循环的控制条件重复执行。Rexx 脚本语言支持迭代循环和条件循环。

迭代循环

[编辑 | 编辑源代码]

迭代循环在迭代器遍历一系列值时,重复执行一组指令。迭代循环的类型包括 for 循环和 foreach 循环。以下是一个传统的迭代 for 循环示例

do count = 1 to 10
  say count
end

在上面的示例中,say 块运行十次,迭代器变量count在每次连续循环中递增。

当迭代循环逐步循环其代码时,可以将迭代器变量增加的值设置为 1 以外的数字。by 关键字位于每次迭代要增加的值之前。

/* Count by 2's */
do count = 2 to 10 by 2
  say count
end

或者,可以使用for 关键字告诉 Rexx 迭代循环的次数。我们可以列出前 20 个正奇数,如下所示

do count = 1 by 2 for 20
  say count
end

条件循环

[编辑 | 编辑源代码]

条件循环测试循环周围的条件,并在条件为真时重复执行一组指令。条件循环的类型包括 while 循环和 until 循环。

count = 0
do while count <= 10
 say count
 count = count + 1
end

while 循环只有在条件为真时才会启动。

/* Nothing happens! */
count = 100
do while count <= 10
 say "Whatever, you're not going to see this message anyway."
end

Until 循环用于启动代码块,并在满足某些条件之前继续执行。

/* Ask the user to enter a number until they actually do. */
do until entry_is_valid
  say "Please enter a number below."
  pull entry
  entry_is_valid = datatype(entry, "NUM")
end
/* The user will always be asked at least once. */

循环控制

[编辑 | 编辑源代码]

迭代循环和条件循环都可以通过循环修改语句来控制,例如 leave、iterate 和 signal(我们还有 next、last 和 redo 吗?)。这些允许循环内的正常执行流程重新启动或终止。

LEAVE 指令停止循环。

/* This function will keep adding up numbers as long the user keeps entering them. */
say "Enter as many numbers as you want!"
say "Put each one on a line by itself."
total = 0
do forever
  entry = LineIn()
  if DataType(entry) = "NUM" then
    say "Cool, you entered another number!"
  else
    leave
  total = total + entry
  say "The new total is" total"."
end
say "The final total is" total"."

ITERATE 指令跳到下一步,而不完成当前步骤。

/* Let's pretend 3 and 4 are boring. */
do number = 1 to 5
  if number = 3 then iterate
  if number = 4 then iterate
  say "I found an interesting number. It is" number"."
  say "Do you agree that it is interesting?"
  answer = LineIn()
  if answer = "yes" then do
    say "I'm glad you agree."
    say "Good thing it wasn't 3 or 4."
  end
end

嵌套循环

[编辑 | 编辑源代码]

Rexx 脚本语言允许使用嵌套循环结构。这些结构由一个或多个嵌套在其他循环中的循环组成。

华夏公益教科书