Session 10: Script Files and Function Files [June 9, 2011, 1:41 a.m.]
Objectives
In this session, you will learn the following:
- Difference between a script file and a function file
- Writing a script file
- Developing a simple function to calculate the length of a line segment
Introduction
Script files are comparable to shell scripts in *nix and batch files in Windows. They are executable files containing statements that are valid Scilab commands. It is simply the non-interactive version of the interactive sessions with Scilab that we are used to up to now. Thus, when you need to type a series of Scilab commands one after the other, not just once, but a number of times, then the best way to do it is to put all those Scilab commands in a text file with a .sce extension and ask Scilab to execute the commands in that file.
On the other hand, a function file is intended to be modular in the sense that it takes certain input, processes that input and generates certain output. Thus, the main difference is the thought that goes into:
- Identifying what the function is expected to do,
- What input should the function take,
- What output should the function generate, and
- What steps (algorithm) and commands are required to process the input in order to generate the required output
Once a function is properly designed, it can then be treated as a black box, focus mainly on what input to give and what output to expect and forget the details of how it is implemented.
Therfeore, the main difference is the way script files and functions exchange data with Scilab. Whatever input data a script file accesses is taken from Scilab workspace. Whatever data a script file outputs is put into Scilab workspace. The semantics of input data, local variables being visible only within the function and output variables being handed to the parent function is not applicable to a script file.
Writing a Script File
The rules for writing a script file are as follows:
- Script file must contain only valid Scilab statements,
- The first word in the script file must not be the keyword function,
- Script file must be text file (typically with the extension .sce)
To execute a script file, one of the following methods can be used:
- From the main menu, choose File -> Execute. This opens a dialog box. Pick the script file and press OK to execute the script file
-
Use the command exec(). To execute a script file test.sce, located in the current working directory, the command is
-->exec('test.sce')
Knowing about current working directory (Session 3) is important. - From the main menu choose File -> Open. This opens a dialog box. Pick the script file and press OK to open the script file in SciNotes, the built-in code editor. From the main menu of SciNotes, choose Execute -> ... file with echo or Execute -> ... file with no echo.
Remember that statements in a script file are executed by Scilab as if they were typed interactively at the Scilab prompt.