Last time, on glorious scripting for whizz kids we discussed chunking your scripts up into function, method, subroutine, or whatever your language might call them. I also left you with a challenge to write as complex/clever a program you could, using only the syntax we'd already discussed. Sadly I hadn't given you one of the most important things you need in order to write useful programs -- namely the ability to make decisions.

The mechanisms of controlling program flow when programming are typically referred to as control structures, and each of Python, Perl, and Lua share some common structure concepts (with moderately different syntax in each case). Also, naturally, each language has some other unique control structures just for themselves.

We're going to use the most fundamental control structure (and most commonly shared one too) in order to extend our cleverness with function to be able to calculate something useful -- fibonacci numbers. For our purposes we'll define the first (1th) and second (2th) numbers in the sequence as both being 1 and that the user of our function will never ask us for the 0th or earlier. We're also going to extend our understanding of function by using a very powerful programming concept called recursion

Python

>>> def fib(n):
...     if n < 2:
...         return 1
...     else:
...         return fib(n-1) + fib(n-2)
...
>>> fib(6)
8
>>> fib(20)
6765
>>>

Perl

$_ sub fib {
>   my $n = shift;
>   if ($n <= 2) {
>     return 1;
>   } else {
>     return fib($n-1) + fib($n-2)
>   }
> }
$_fib(6)
8$_ fib(20)
6765$_

Lua

> function fib(n)
>>   if n <= 2 then
>>     return 1
>>   else
>>     return fib(n-1) + fib(n-2)
>>   end
>> end
> =fib(6)
8
> =fib(20)
6765
>

Challenge

Using the power of the simple control structure exhibited here, and the incredible versatility of recursion, most if not all other control structures and thus programs can be built. Of course that'd often be exceedingly long winded and uncomfortable to do, and as such each of the scripting languages we are discussing have plenty of other control structures. Your challenge is to root out all of the control structures you can find for the language(s) you have chosen, and practice using them ready for our next lesson.