Lesson 11: Writing Scripts
Toka can be used to write scripts. Start your code with the following:
#! /usr/bin/toka
And set the permissions to executable (+x), and you can run your code directly at the command line (assuming that Toka is installed). Note the space following the shebang (#!). This is necessary to invoke the #! function and avoid an error message when the script is loaded.
To make the most of your scripts, you will probably want to handle command line arguments. Toka allows for this using the following words:
#args ( -n ) Returns the number of command line arguments arglist ( -a ) An array containing the arguments array.get ( ia-n ) Return a pointer to an element in the array
Toka accepts a command line like the following:
toka <script> <arg1> <arg2> ... <argN>
If no arguments are given to Toka, #args will be set to 0. In any other case, #args will contain the total number of arguments, including the script name. For example, in the following example, #args will return 4:
toka foo.toka apple banana carrot
The breakdown in the arglist will then be as follows:
- Element 0 is the name of the script, in this case foo.toka
- Element 1 is apple
- Element 2 is banana
- Element 3 is carrot
You can loop over the arguments to process them. For instance, if we wanted to display each of the script arguments (but not the name of the script), we could do:
1 #args [ i arglist array.get type cr ] countedLoop