Nimrod Programming/Blocks
So many blocks it seems like Minecraft
[edit | edit source]Now we will introduce a feature so fundamental there's few major languages without this it. This feature is the block. Before we know what this does let's try to understand the problem it solves. If you look at past examples you will see we have been only giving one command for if/elif/else, so we solve it by using blocks. Blocks aren't entirely new to us as we have seen them in the last chapter:
elif theresEnoughMoney():
buyCoffee()
makeSomeCoffee()
As you may see nimrod's blocks are fairly easy as they are a new line and then add an indentation ( space preceding the code) of two spaces, tabs ( that keyboard key with two arrows ) can't be used and they will be traten as an error.
Blocks have one particularity, anything declared outside them will be available inside them , however, anything declared inside them it's not available outside! Check this code:
var firstVariable = "Hello World."
if SomethingIsTrue():
var secondVariable = "Hi there."
echo ("We can access from inside the block the values of both variables")
echo (firstVariable, secondVariable)
echo ("But we can't access outside the block the variable declared inside")
echo (secondVariable)
Now, if you try to execute that what you will get from the compiler is an error because it can't access secondVariable because it is inside the block.
Finally, blocks can be nested ( put one inside another ) for doing so you will only need to sum the indentation to the existing one. If you want to close a block just reduce in two spaces the indentation.
Finally if we want to create our own blocks we can do this way:
block myBlock:
echo ("Hey this is a block!")
As you can see you make a block and put a label in this case we named it myBlock, though the label is completely optional.
block:
echo ("Hey this is a block!")