github.com/lmorg/murex@v0.0.0-20240217211045-e081c89cd4ef/docs/user-guide/scoping.md (about) 1 # Variable and Config Scoping 2 3 > How scoping works within Murex 4 5 ## Description 6 7 A 'scope' in Murex is a collection of code blocks to which variables and 8 config are persistent within. In Murex, a variable declared inside an `if` or 9 `foreach` block will be persistent outside of their blocks as long as you're 10 still inside the same function. 11 12 For example lets start with the following function that sets a variable called 13 **foo** 14 15 ``` 16 function example { 17 if { true } then { set foo=bar } 18 out $foo 19 } 20 ``` 21 22 In here the value is getting set inside an `if` block but its value is is 23 retrieved outside of that block. `out` and `set` have different parents but 24 the same scoping. 25 26 Then lets set **foo** outside of that function and see what happens: 27 28 ``` 29 » set foo=oof 30 » $foo 31 oof 32 33 » example 34 bar 35 36 » $foo 37 oof 38 ``` 39 40 Despite setting a variable named **foo**, the value inside **example** does not 41 overwrite the value outside **example** because they occupy different scoping. 42 43 ## What Instantiates A New Scope? 44 45 A new scope is instantiated by anything which resembles a function. This would 46 be code inside events, dynamic autocompletes, open agents, any code blocks 47 defined in `config`, as well as public and private functions too. 48 49 Code inside an `if`, `switch`, `foreach` and `source` do not create a new 50 scope. Subshells also do not create a new scoping either. 51 52 ## See Also 53 54 * [Reserved Variables](../user-guide/reserved-vars.md): 55 Special variables reserved by Murex 56 * [`autocomplete`](../commands/autocomplete.md): 57 Set definitions for tab-completion in the command line 58 * [`config`](../commands/config.md): 59 Query or define Murex runtime settings 60 * [`event`](../commands/event.md): 61 Event driven programming for shell scripts 62 * [`foreach`](../commands/foreach.md): 63 Iterate through an array 64 * [`function`](../commands/function.md): 65 Define a function block 66 * [`if`](../commands/if.md): 67 Conditional statement to execute different blocks of code depending on the result of the condition 68 * [`let`](../commands/let.md): 69 Evaluate a mathematical function and assign to variable (deprecated) 70 * [`openagent`](../commands/openagent.md): 71 Creates a handler function for `open` 72 * [`private`](../commands/private.md): 73 Define a private function block 74 * [`set`](../commands/set.md): 75 Define a local variable and set it's value 76 * [`source`](../commands/source.md): 77 Import Murex code from another file of code block 78 * [`switch`](../commands/switch.md): 79 Blocks of cascading conditionals 80 81 <hr/> 82 83 This document was generated from [gen/user-guide/scoping_doc.yaml](https://github.com/lmorg/murex/blob/master/gen/user-guide/scoping_doc.yaml).