Skip to content

Commit e0a6d4f

Browse files
committed
some destructuring docs
1 parent c9b121c commit e0a6d4f

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

docs/reference.md

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1293,6 +1293,82 @@ statement in its body.
12931293
}
12941294
```
12951295

1296+
## Destructuring Assignment
1297+
1298+
Destructuring assignment is a way to quickly extract values from a table by
1299+
their name or position in array based tables.
1300+
1301+
Typically when you see a table literal, `{1,2,3}`, it is on the right hand side
1302+
of an assignment because it is a value. Destructuring assignment swaps the role
1303+
of the table literal, and puts it on the left hand side of an assign
1304+
statement.
1305+
1306+
This is best explained with examples. Here is how you would unpack the first
1307+
two values from a table:
1308+
1309+
```moon
1310+
thing = {1,2}
1311+
1312+
{a,b} = thing
1313+
print a,b
1314+
```
1315+
1316+
In the destructuring table literal, the key represents the key to read from the
1317+
right hand side, and the value represents the name the read value will be
1318+
assigned to.
1319+
1320+
```moon
1321+
obj = {
1322+
hello: "world"
1323+
day: "tuesday"
1324+
length: 20
1325+
}
1326+
1327+
{hello: hello, day: the_day} = obj
1328+
print hello, the_day
1329+
```
1330+
1331+
This also works with nested data structures as well:
1332+
1333+
```moon
1334+
obj2 = {
1335+
numbers: {1,2,3,4}
1336+
properties: {
1337+
color: "green"
1338+
height: 13.5
1339+
}
1340+
}
1341+
1342+
{numbers: {first, second}} = obj2
1343+
print first, second, color
1344+
```
1345+
If the destructuring statement is complicated, feel free to spread it out over
1346+
a few lines. A slightly more complicated example:
1347+
1348+
```moon
1349+
{
1350+
numbers: { first, second }
1351+
properties: {
1352+
color: color
1353+
}
1354+
} = obj2
1355+
```
1356+
1357+
It's common to extract values from at table and assign them the local variables
1358+
that have the same name as the key. In order to avoid repetition we can use the
1359+
`:` prefix operator:
1360+
1361+
```moon
1362+
{:concat, :insert} = table
1363+
```
1364+
1365+
This is effectively the same as import, but we can rename fields we want to
1366+
extract by mixing the syntax:
1367+
1368+
```moon
1369+
{:mix, :max, random: rand } = math
1370+
```
1371+
12961372
## Function Stubs
12971373

12981374
It is common to pass a function from an object around as a value, for example,

0 commit comments

Comments
 (0)