FBSL's official tutorial PDF here

Arrays. 5. Procedures and functions. Procedures. Local variables and global variables. Functions ... contains flavours of Visual BASIC, QBasic, PHP, Pascal and C++. ... Here an example of this script with accompanying notes: (a. (b. (c. (d. (e. (f.
838KB taille 97 téléchargements 379 vues
Discovering FBSL By a beginner for beginners

FBSL (Freestyle BASIC Language Script) © 2001-2008 by Gerome GUILLEMIN, Mehdi BOUAZIZ and Mike LOBANOVSKY

Contents Introduction 1. Basics First steps To calculate with FBSL 2. Data and variables Assignment To display the value of a variable Reassignment Multiple assignments Operators and expressions Composition 3. Supervise implementation Flow Control Repetitions in loop 4. Principal types of data Numbers Character strings Arrays 5. Procedures and functions Procedures Local variables and global variables Functions Default values for the parameters Optional parameters Passing arguments by value or by Reference 6, graphic interfaces (GUI) To display a message box To communicate with the computer To open a window A basic example of application 7. Files Using Files Working with files. Include files Namespaces

8. Types and classes Definition of a type of data item A type can in hiding another Classes and methods Inheritance Similarity and uniqueness Overloading operators 9. Meta-directives Definitions (#Define) Declarations (Declares) Macros 10. Creating executables Conclusion

1

Introduction These basic lessons are intended to introduce FBSL. They are directed towards beginners and hopefully they will enable them to become familiar with, and, to use the basics of this straightforward and powerful language. FBSL means “Freestyle BASIC Language Script”. Like many modern programming languages contains flavours of Visual BASIC, QBasic, PHP, Pascal and C++. It is a kind of hybrid language hence the “Freestyle”. It is especially designed for the win32 platform (Windows 95 SR2 to Windows VISTA). It is compatible with, and completely functional under, LINUX Wine. Do not hesitate with to download the last version of FBSL. And to join the forum if you have questions, suggestion about FBSL, or even criticisms… of this document. Remarks on the presentation of the document : The code with a pale yellow background contain complete scripts which one can copy/paste into a text editor and save with the extension .fbs. You can then execute the program by a doubleclick on the icon or directly from the editor if it allows (Eclecta is one such editor) The code fragments with a pale blue background contains pieces of code intended to be analysed and/or inserted in complete scripts to be able to test them. The diagrams with a black background represent the result of script As it seen on the screen.

Contents

2

Chapter 1. Basics This chapter demonstrates the fundamental knowledge needed to write your first program in FBSL.

First steps We will start exploring FBSL using the “console” mode. Scripts can be written in any text editor that gives plain text “notepad.exe” for example. But the FBSL distribution offers more specialised editors, in the standard installation look in "C:\Program Files\FBSLv3\Samples" and select sub-directories starting with IDE. You can also launch 'FBSLv3 Editor (Eclecta Editor)' from start/Programs/Freestyle BASIC Script Language. Then click on File/New or on in the bar of icon:

On the first line type: #apptype console to tell FBSL this one will use the console mode. then type: pause, this prevents the console closing immediately. This first script does not do anything in particular it is only to open one console.

Contents

3

Now on click on Compile and Run Script or simply press on the key, you get the following window:

Press the key, and the console is closed. The console mode is useful for testing small fragments of code, algorithms and writing small utility programs. Always insert your code between #App Type Console and Pause

←Enter your code here

From here on we will use the Console mode quite extensively to demonstrate How to use FBSL

Contents

4

To calculate with FBSL FBSL can evaluate all the basic arithmetic operations. Symbol + * / ^

Operation Addition Subtraction Multiplication Division Exponentiation

Turn on the editor now and test this: print print print print print

5+3 2-9 7 + 3 * 4 (7+3) * 4 20/3

Do not forget to insert these lines between #AppType Console and Pause. The command print displays rest of the line on the screen. Note that spaces are optional between the figures and the operators (the editor adds automatically spaces to make the code more readable) but space is essential between the command print and what follows. Click on Compile/Run Script or type on , you obtain the following window:

Contents

5

Here an example of this script with accompanying notes:

(a

(b

(c

(d (e

(f (a (b (c (d

Indicates that the application is to be of type “console” The print instruction causes the following characters to be displayed on the console. Causes the program to wait for the Enter key to be pressed. enclosed in quotes you can print the operation code in front of the result. Characters in quotes are printed “as is”, that is, literally (e Remark - Literal text is typed between quotation marks - The elements of the post (quoted part, calculated part) are separated by commas (f prints a blank line. The colon “:” indicates a separate instruction Note that characters which are typed after the apostrophe (') are comments and are ignored by FBSL when the program is executed. They make it possible to explain in plain language what the instructions do and can also contribute to the legibility of script by separating the various sections from the program. The comments can also be preceded by a double oblique bar // instead of the apostrophe. One can also write comments on several lines, which will form a block framed by /* at the beginning and */ at the end. It is a good idea to comment anything that is a bit unusual or complicated; it is surprising how quickly one forgets. Blank lines can be used between lines of code to make it easier to read It is possible to write several instructions on the same line by separating them by : (colon).

Contents

6

FBSL performs calculations following a hierarchy of operations. The acronym PEMDAS: is a useful mnemonic to help memorise the order of priority for calculations

-

P for parentheses. This is the highest priority. Any calculations surrounded by parentheses are performed first. This makes it possible to ensure that calculations are performed in the required sequence 2* (3-1) = 2*2 = 4 FBSL → ? 2 * (3 - 1) (1+1) ^ (5-2) = 2^3 = 8 FBSL → ? (1 + 1) ^ (5 - 2)

-

E for exponentiation. This is evaluated before other operations 2^1+1 = (2^1) + 1 = 3 and not 4 FBSL → ? 2 ^ 1 + 1 3*1^10 = 3 * (1^10) = 3 and not 59049 FBSL → ? 3 * 1 ^ 10

-

M and D for multiplication and division, which have the same priority. 2*3-1 = 5 and not 4 FBSL → ? 2 * 3 - 1 2/3-1 = -0.3333 FBSL → ? 2/3 – 1

-

A and S for addition and subtraction, which are carried out last

-

If two operators have the same priority, the evaluation is done from left to right. 59*100/60 = 5900/60 = 98.3333 FBSL → ? 59 * 100/60

? is a short cut for print. There is also another synonym of print: echo which means the same thing. The syntactic flexibility of FBSL makes it a rich language and makes it easy to convert between other programming languages to FBSL, and, from FBSL to other programming languages.

Contents

7

Chapter 2. Data and variables A computer program mainly handles data. The program accesses this data using “variables” of various types. A variable generally consists of a variable name which the computer uses as a reference to the address in memory that contains the actual data. At this address one value is stored, it is data itself. That could be a number, a character string, an array, a user defined type (UDT) etc. Variable names can be freely chosen, but is preferable to keep the names short and descriptive. The names should clearly show the type of information held. For example, ‘age’ is preferable to A, and ‘name’ to X. Variables names can be made up of more than one word, but no spaces are allowed within the variable. It is necessary to ensure that the variable name is readable. Imagine that you wish to use a variable to record the name at birth. There are two conventions: nameBirth – the so called camel code, capitalise the first letter of all words after the first. name_birth – use an underscore between words. Avoid where possible: namebirth, as it is less readable.

Assignment Having chosen a suitable name for the variable, it is now required to “assign” a value to it. The assignment operator is the equals sign “=” Dim numbers, message numbers = 7 'give numbers the value 7 message = “Hello” ' assign the value “Hello” to message While it is possible to just start using a variable, having FBSL create the variable as it is needed, it is preferable to choose and control the names yourself, using auto creation it is possible (likely) to get strange errors through misspelling the name, to do this use #Option Implicit at the head of the script. CAUTION! since version 3.31.6 FBSL, Explicit is the default option , it is thus necessary to declare variables with Dim to avoid any error.

Explicit assignment means that when you have chosen a variable name you must declare to FBSL what the variable is the statement used is Dim (short for dimension) so that if you dim a variable and make it a specific type of variable the exact amount of memory can be reserved. It is possible but not compulsory that the value be assigned at this time. Dim numbers = 7, message = “Hello” See the chapter on Variable Declaration

To display the value of a variable To display the value of a variable in the console, the command print or one of its synonyms is used. Test: #Option Implicit #AppType Console N = 7 msg = “Hello” Print N Print msg Pause N.B. : You can copy/paste the lines of code above in the editor. Then possibly use Format/Check Syntax before launching script in order to check that there are no errors of syntax or typing errors

Contents

8

Reassignment You can change the value stored in a variable at any time and as often as needed. The new value replaces the old values a shown in the next example: #Option Implicit #AppType Console outdistance = 320 print distance outdistance = 375 print distance Pause If you want to protect the value in a variable you can declare it as a constant by using the command CONST instead of Dim. This is also useful for values that are used throughout a program, for example, Const tax_rate = 10/100. Then when the rate changes you can simply change the value in one place and the new value will be inserted whenever the tax_rate variable is used. Test: #AppType Console Const C = 100 Print C C = 1 Print C Pause You should obtain this result: 100 [SV] Var protected : 'c' Print “To add an element to array “days: ” “ Print “days [Count (days)] = "" Saturday """,days [Count (days)] = “Saturday” 'Printing the array to see the modification: ForEach E In days Print E, ““; Next Print: Print Print “Cuts array =”, Count (days) Print: Pause To add elements to a dynamic array it is sufficient to use a higher index then the maximum. The minimum index for days is 0 (zero) and maximum is 6, 7 elements in all, the function Count() returns the number of indices 7. This is an easy way to track the number of elements. There are other useful functions to manage and handle arrays among which Lbound () and Ubound () which return respectively smallest and the largest index of the array specified between brackets. See the handbook of FBSL: FBSL Language → ARRAY Functions to discover other functions and to test examples. Do not hesitate either to explore the folder of the many examples provided in the distribution of FBSL (file ). They are, for the majority very short and easy to include/understand.

19

Contents

Chapter 5. Procedures and functions Procedures or subroutines make it possible to break a long or complex program into smaller more easily managed sections. This also very useful where a sequence of commands is repeated several times in a program. In the last example of the last chapter a routine could be create to print out the array in place of rewriting the same for each loop several times. #AppType Console Dim days [] = {“Monday”, “Tuesday”, “Wednesday”, 1800, 20.357, “Thursday”, “Friday”} 'Modification of the 4th element of array : Print “days [3] = days [3] + 47 " days [3] = days [3] + 47 'Displaying the array to see the modification: GoSub Show_jours Print 'Replacement of the 4th element of array : Print “days [3] = July” days [3] = “July” 'Displaying the array to see the modification: GoSub Show_jours Print 'Addition of an element in array < days> Print “To add an element to array “days: ” “ Print “days [Count (days)] = "" Saturday """ days [Count (days)] = “Saturday” 'Displaying the array to see the modification: GoSub Show_jours Print Print “Cuts array =”, Count (days) Print: Pause 'Routine to display array : Show_jours Dim J Print “days =”; ForEach J In days Print J, ““; Next Print Return The command GoSub direct the flow of the program towards a label indicated by colon and a name, here : Show_jours, and carries out the commands which follow until the command Return who returns it program with the line which follows the command GoSub . You already met functions integrated into the language itself: Len () which calculates the real length of a variable or StrLen () which returns the number of characters of a string or Count () which counts the number of elements of a array. It is of course difficult and even useless to integrate all the functions possible and conceivable in the body standard of FBSL because their number is infinite. Only functions likely to be frequently used have vocation to be integrated into the language, the others could be created by the user and possibly gathered in non-standard files (auxiliary files with the extension .inc). Those will be able then to be charged or included in scripts thanks to the order #Include. It should be noted that contrary to one procedure (or a routine) which is satisfied with to carry out an end of program (a subroutine), one function must to return a value. A true function thus can to be used with the right-hand side of the sign equal in expressions like y = Sin (pi) for example. Here the Sin function () turn over a value (the sine of argument pi) which is assigned to variable Y.

20

Procedures One can define a procedure in an “elegant” way more that in the preceding example using command Sub which allows, in addition to including a list of parameters specifying which information one must to provide to the procedure at the time of its use (this list can remain empty if no argument is necessary). This procedure can then be used like any instruction FBSL: call subroutine is consisted of the name of the procedure followed by brackets surrounding zero, one or more arguments. Example: #AppType Console Sub Table7 () Dim %n For N = 1 To 10 print N * 7, ““; Next Print End Sub Table7 () Print: Pause One can use this procedure in the definition of another procedure: #AppType Console Table7_Triple () Print: Pause Sub Table7 () Dim %n For N = 1 To 10 print N * 7, ““; Next Print End Sub Sub Table7_Triple () Print “the table of 7 in exemplary triple: “ Repeat 3: Table7 (): End Repeat End Sub If we want to now display the array of 9, we have the choice between entirely rewriting preceding procedure or to define a new procedure which can display any array with ask. It will thus be necessary to indicate to this procedure which array we want to display. This information which will be transmitted to the procedure at the time when we will call it is called one argument. In the definition of the procedure one will have to envisage a particular variable which will receive the transmitted argument. This variable is called a parameter. It is about a name of variable which will be placed between the brackets who accompany the definition by the function. Example: #AppType Console Count (9) Count (13) Print: Pause Sub Counts (base) Dim %n For N = 1 To 10 Print N * base, ““;

21

Next Print End Sub Procedure Count () use the parameter base to calculate the first ten terms of the array of corresponding multiplication. The value indicated between brackets at the time of the call of the procedure is automatically assigned to the parameter base. In the body of the procedure, base play the same part as any other variable. The argument used in the call of a procedure can be also a variable: In this example, the argument passed to the procedure Count () is the contents of the variable has. Inside the procedure this argument is assigned with the parameter base who is another variable. The name of a variable passed like argument have nothing to do has nothing to do with the name of the corresponding parameter of the procedure or of function. #AppType Console Dim %a For has = 1 To 20 Count (has) Next Print: Pause Sub Counts (base) Dim %n For N = 1 To 10 Print N * bases, ““; Next Print End Sub One can still improve the procedure Count () by adding additional parameters to him for to display more or less of ten terms: #AppType Console ArrayMulti (8, 13, 17) Print: Pause Sub ArrayMulti (bases, beginning, end) Dim %n Print “Fragment of the multiplication table by “, bases,”: “ For N = fine To beginning Print N, “X”, bases, “ = “, N * bases Next End Sub

Local variables and global variables The variables defined inside the procedure are accessible only to the procedure itself. One says that it is about local variables. It is the case of the variables base, begin, finish preceding example but still of n because declared (with Dim) within the procedure. If one types print base just after the call of the procedure TableMulti () a message will be obtained: [n° line] Variable Missing name “base”! On the other hand the variables defined in the outside of a procedure or a function are global variables.. They are “ visible everywhere” even inside a procedure. Example: #AppType Console Dim p = 15, Q = 38 Mask () Print p, ““, Q Print: Pause Sub Mask () Dim p = 20

22

Print p, ““, Q End Sub 20 38 Result: 20 38 15 38 Type Enter key to continue... Two variables p and Q are defined with the values 15 and 38. They are global variables that were defined at the principal level, apart from any procedure. In the procedure Mask () a variable is defined p with for value 20. It is about a local variable with procedure since it was defined in the interior of this one. The same name of variable p two times were used to define two different variables, one total and the other local one. The preceding example shows well that it acts of distinct and independent variables,obeying moreover one rule of priority which wants that inside a procedure they are the variablesdefined locally which has priority (this which makes it possible to avoid any conflict between these variables). When the procedure is called Mask (), the variable Q y is accessible since its value is correctly displayed. But it is the local value of p who is displayed. However procedure Mask () did not modify contents of the global variable p. The following instruction shows it by displaying the initial value of global variable p. In the example according to the variable has used inside procedure Increment () is accessible and modifiable because it is about an global variable (the statement of the variable is made at the total level). #AppType Console Dim a = 15 Increment () Increment () Print: Pause Sub Increment () a = a + 1 Print a End Sub

Functions Like that was known as at the beginning of this chapter, a function must return a result : #AppType Console Dim %b B = Cube (9) Print B Print: Pause Function Cube (N) Return N * N * N End Function The command return indicate the value which must be returned by the function. This one is built like a procedure but by using the word function instead of the word sub. Here how one could modify the Table procedure (), previously definite, in a function so that it returns a value: #AppType Console Dim tab9, item tab9 = Table (9) ForEach item In tab9

23

print item, ““; Next Print: Pause Function Counts (bases) Dim result [] = {}, %n For N = 1 To 10 result [Count (result)] = N * bases Next Return result End Function This example at the same time enables us to re-examine them tables and to include/understand how one can use the returned value from a function. Here one assigns to the variable tab9 the value (result) returned by function Count (), it is about a array including/understanding the first 10 terms of the multiplication table of 9. One can also print or handle the elements of this table individually: #AppType Console Dim tab9, %i tab9 = Table (9) Print tab9 [0] Print tab9 [3] For I = 2 To 4 print tab9 [I], ““; Next Print: Pause Function Counts (bases) Dim result [] = {}, %n For N = 1 To 10 result [Count (result)] = N * bases Next Return result End Function

Default values for the parameters In the definition of a procedure or a function, it is possible to define an argument by default for each parameter. One can thus call the function with a part only of the arguments listed. #AppType Console Print Greetings (“Dupont”) Print Greetings (“Dubois”, “Madam”) Print: Pause Function Greetings (name, title = “Mister”) Return “Please accept,” & title & ““& name &”, my greetings.“ End Function N.B.: One can define a default value for all the parameters or only one part of them. In this case the parameters without default value must precede the others in the list.

Optional parameters ParamArray allows to pass an unspecified number of arguments (up to 1024) to a function or one procedure (see the help file FBSL v3, ARRAY Functions) : #AppType Console Sub TestPA (ParamArray Pa) Dim E ForEach E In Pa Print E Next

24

End Sub TestPA (1, 2, 3, 4, “Hello”, “FBSL! ”) Pause In the definition of the procedure Pa corresponds to the table of parameters which passed to the procedure TestPA (). In this array one finds the arguments registered between brackets at the time of the call of procedure.

Passing arguments by value or reference. Parameters of a function or a procedure, which are thus local variables with this function/procedure can pass the arguments, definite at the time of the call of the function/procedure, by reference or by value. '=========================== 'ByRef: by reference '=========================== #AppType Console Dim %i = 10 Print “i =”, i Test (i) Print “Now i =”, i Print: Pause Sub Test (ByRef %x) x = x + 2 Print “In Test () x =”, x End Sub In the first case, the parameter of the function/procedure will make reference with the same value contained in the variable given in argument to the function/procedure. If the function/procedure modifies the value of sound parameter, it will modify also the variable passed in argument. Result i = 10 x = 12 i = 12 Type Enter key to continue... Here I is the argument of Test () of which the parameter X takes the value of I by reference (command ByRef in the definition of the procedure). Variables I and X point on the same value. If one modifies value using one of the variables, the other variable will point then on this new value. '========================== 'ByVal: by value '========================== #AppType Console Dim %i = 10 Print “I =”, I Test (I) Print “I =”, I Print: Pause Sub Test (ByVal %x) X = X + 2 Print “X =”, X End Sub

In the second case, the parameter of the function/procedure will make a copy of value variable data in argument with the function/procedure and this one could not be modified within function/procedure.

25

Result: I = 10 x = 12 i = 10 Type Enter key to continue... Here the parameter X of Test () copy the value of I (command ByVal in the definition of the procedure). The global variable I and the local variable X are distinct well that they contain the same value or rather an equivalent value. If one modifies the value of the one of the variables, the other variable will not be affected since it is about a copy. N.B.: by default the arguments of the procedures/functions passed by reference.

26