Update syntax-list-comprehensions.md

This commit is contained in:
James Napora 2022-02-13 16:45:12 -08:00 committed by GitHub
parent 37da546e8d
commit 6cefa03519
Signed by: DevComp
GPG key ID: 4AEE18F83AFDEB23

View file

@ -7,13 +7,14 @@ Introduce a form of list comprehension using `n for-in-do` syntax.
List comprehensions would bring several benefits and prevent code smell. List comprehensions would bring several benefits and prevent code smell.
In Lua you are encouraged to not modify tables during traversal. In Lua you are encouraged to not modify tables during traversal.
When traversing a table to exclude all the odd numbers you'd be creating a large statement to get rid of them, with list comprehensions this could be shortened and cleaner When traversing a table to exclude all the odd numbers you'd be creating a large statement to get rid of them, with list comprehensions this could be shortened and cleaner.
## Design ## Design
To solve these problems, I propose a `n for-in-do` expression form that is syntactically similar to a for statement, but lacks terminating `end`. To solve these problems, I propose a `n for-in-do` expression form that is syntactically similar to a for statement, but lacks terminating `end`.
The `n for-in-do` expression must match ``<identifier> for <identifier> in <expr> do`` The `n for-in-do` expression must match ``<identifier> for <identifier> in <expr> do``.
A ``if <expr> then`` expression might be required.
Example: Example:
```lua ```lua
@ -28,14 +29,14 @@ end
-- list comprehensions -- list comprehensions
local t = {1,2,3,4,5,6,7,8,9} local t = {1,2,3,4,5,6,7,8,9}
local onlyEven = {for n in t do if n%2 == 0 then n} local onlyEven = {n for n in t do if n%2 == 0}
``` ```
## Drawbacks ## Drawbacks
List comprehensions may be misused. List comprehensions may be misused.
The list comprehensions have similar drawbacks to the if expression drawbacks The list comprehensions have similar drawbacks to the if expression drawbacks.
https://github.com/Roblox/luau/blob/master/rfcs/syntax-if-expression.md https://github.com/Roblox/luau/blob/master/rfcs/syntax-if-expression.md
## Alternatives ## Alternatives
@ -62,7 +63,7 @@ let vector = c![x, for x in 1..10, if x % 2 == 0];
``` ```
## Function syntax ## Function syntax
List comprehensions could be implemented as functions with ``table.map`` or ``table.filter`` List comprehensions could be implemented as functions with ``table.map`` or ``table.filter`` .
### Examples: ### Examples: