A block is a named portion of your code. Blocks allow you to organise your code into smaller chunks which can be called on demand for specific tasks. A basic block is defined using the block keyword followed by the name of the block. As with conditionals and loops you indicate where your block ends using end. To ask MaSH to execute the code inside our block we need to call it which we can do just by referencing its name.
Natural
block sayHello
printline "Hello from mash"
end
sayHello
Standard
block sayHello() {
printline("Hello from mash")
}
sayHello()
Output
Hello from mash
Important – you should not use the same name for a block as for a variable, doing so will cause MaSH to throw an error and cancel execution of your script.
Input parameters
Blocks become a whole lot more useful when we pass data (parameters) into them to be processed. Parameters are similar to variables. We can then use their name to access their value inside the block. Parameters are declared after the block name as a simple list.
Natural
set myDictionary to { name: "Grace Hopper", occupation: "Computer Scientist" }
block sayHello message name
printline "{{ message }} {{ name }}"
end
sayHello "Hello from mash" myDictionary["name"]
Standard
myDictionary = { name: "Grace Hopper", occupation: "Computer Scientist" }
block sayHello(message, name) {
printline("{{ message }} {{ name }}")
}
sayHello("Hello from mash", myDictionary["name"])
Output
Hello from mash Grace Hopper
Returning Values
A common use case for blocks is to perform some work on a value and then return it to us so that we can use it elsewhere in our code. We can do this using a return statement. A return statement will stop any further execution of your block and provide the value or variable which you specify back to your script. When your block returns a value it can be assigned to a variable.
Natural
# We name our block "isEven" and define a parameter called "value"
# We use modulus operator to check whether our value is exactly divisible by two
block isEven value
if value % 2 is 0
return true
else
return false
end
end
#We define a variable answer and ask MaSH to call our isEven block with a parameter of 2. answer will then contain the value that our block returns
answer = isEven 496
printline answer
Standard
# We name our block "isEven" and define a parameter called "value"
# We use modulus operator to check whether our value is exactly divisible by two
block isEven(value) {
if (value % 2 == 0) {
return true
} else {
return false
}
}
# We define a variable answer and ask MaSH to call our isEven block with a parameter of 2. answer will then contain the value that our block returns
answer = isEven(496)
printline(answer)
Output
true