| 1 |
# Mutability |
| 2 |
|
| 3 |
In scripting mode mutability rules are relaxed slightly. `list` and `dict` |
| 4 |
types may be mutated by reference. |
| 5 |
|
| 6 |
```meson |
| 7 |
# Mutating a list with + and +=: |
| 8 |
list = [0, 2, 3] |
| 9 |
list[0] = 1 |
| 10 |
assert(list == [1, 2, 3]) |
| 11 |
list[0] += 1 |
| 12 |
assert(list == [2, 2, 3]) |
| 13 |
``` |
| 14 |
|
| 15 |
```meson |
| 16 |
# Mutating a dict with + and +=: |
| 17 |
dict = {'a': 1} |
| 18 |
dict['a'] = 2 |
| 19 |
assert(dict == {'a': 2}) |
| 20 |
dict['a'] += 1 |
| 21 |
assert(dict == {'a': 3}) |
| 22 |
dict['b'] = 4 |
| 23 |
assert(dict == {'a': 3, 'b': 4}) |
| 24 |
``` |
| 25 |
|
| 26 |
Dictionaries may also be indexed using the `.` operator in scripting mode so the |
| 27 |
above example could be rewritten as: |
| 28 |
|
| 29 |
```meson |
| 30 |
# some asserts removed |
| 31 |
dict = {'a': 1} |
| 32 |
dict.a = 2 |
| 33 |
dict.a += 1 |
| 34 |
dict.b = 4 |
| 35 |
assert(dict == {'a': 3, 'b': 4}) |
| 36 |
``` |
| 37 |
|
| 38 |
Re-assigning creates a copy[^copynote], mutations do not affect the copied variables. |
| 39 |
|
| 40 |
```meson |
| 41 |
list = [0, 1] |
| 42 |
list2 = list |
| 43 |
list[0] += 1 |
| 44 |
|
| 45 |
assert(list == [1, 1]) |
| 46 |
assert(list2 == [0, 1]) |
| 47 |
``` |
| 48 |
|
| 49 |
[^copynote]: Muon implements this using copy-on-write but the effect should be |
| 50 |
the same. |