From 0603800a4114ed8b4c9572a7d7852995c9b9f334 Mon Sep 17 00:00:00 2001 From: Li Jin Date: Wed, 21 May 2025 11:44:54 +0800 Subject: Added break with value syntax. --- doc/docs/doc/README.md | 27 +++++++++++++++++++++++++++ doc/docs/zh/doc/README.md | 27 ++++++++++++++++++++++++++- 2 files changed, 53 insertions(+), 1 deletion(-) (limited to 'doc/docs') diff --git a/doc/docs/doc/README.md b/doc/docs/doc/README.md index c275c52..dac96ee 100755 --- a/doc/docs/doc/README.md +++ b/doc/docs/doc/README.md @@ -29,6 +29,16 @@ inventory = * name: "bread" count: 3 +-- list comprehension +map = (arr, action) -> + [action item for item in *arr] + +filter = (arr, cond) -> + [item for item in *arr when cond item] + +reduce = (arr, init, action): init -> + init = action init, item for item in *arr + -- pipe operator [1, 2, 3] |> map (x) -> x * 2 @@ -2324,6 +2334,23 @@ doubled_evens = for i = 1, 20 +In addition, for loops support break with a return value, allowing the loop itself to be used as an expression that exits early with a meaningful result. + +For example, to find the first number greater than 10: + +```moonscript +first_large = for n in *numbers + break n if n > 10 +``` + +
+first_large = for n in *numbers
+  break n if n > 10
+
+
+ +This break-with-value syntax enables concise and expressive search or early-exit patterns directly within loop expressions. + You can also filter values by combining the for loop expression with the continue statement. For loops at the end of a function body are not accumulated into a table for a return value (Instead the function will return nil). Either an explicit return statement can be used, or the loop can be converted into a list comprehension. diff --git a/doc/docs/zh/doc/README.md b/doc/docs/zh/doc/README.md index 11dc108..850afed 100755 --- a/doc/docs/zh/doc/README.md +++ b/doc/docs/zh/doc/README.md @@ -29,6 +29,16 @@ inventory = * name: "bread" count: 3 +-- 列表推导 +map = (arr, action) -> + [action item for item in *arr] + +filter = (arr, cond) -> + [item for item in *arr when cond item] + +reduce = (arr, init, action): init -> + init = action init, item for item in *arr + -- 管道操作符 [1, 2, 3] |> map (x) -> x * 2 @@ -2286,9 +2296,24 @@ doubled_evens = for i = 1, 20 +此外,for循环还支持带返回值的break语句,这样循环本身就可以作为一个表达式,在满足条件时提前退出并返回有意义的结果。 + +例如,查找第一个大于10的数字: + +```moonscript +first_large = for n in *numbers + break n if n > 10 +``` + +
+first_large = for n in *numbers
+  break n if n > 10
+
+
+ 你还可以结合for循环表达式与continue语句来过滤值。 -注意出现在函数体末尾的for循环,不会被当作是一个表达式,并将循环结果累积到一个列表中作为返回值(相反,函数将返回nil)。如果要函数末尾的循环转换为列表表达式,可以使用返回语句加for循环表达式。 +注意出现在函数体末尾的for循环,不会被当作是一个表达式并将循环结果累积到一个列表中作为返回值(相反,函数将返回nil)。如果要函数末尾的循环转换为列表表达式,可以显式地使用返回语句加for循环表达式。 ```moonscript func_a = -> for i = 1, 10 do print i -- cgit v1.2.3-55-g6feb