This chapter describes the following variants of the IF control structure:
The syntax for the IF control structure in the second part represents the cases in which only one (conditional) selection is formulated in a row:
IF Expression [ { AND IF | OR IF } Expression ... ] [ THEN ] ... [ ELSE IF Expression [ { AND IF | OR IF } Expression ... ] [ THEN ] ... ] [ ELSE ... ] ENDIF
IF Expression [ { AND IF | OR IF } Expression ... ] THEN ... IF Expression [ { AND IF | OR IF } Expression ... ] THEN ... ELSE …
The following examples show mainly Gambas source code excerpts and are commented on briefly. Some of the examples are preceded by pseudo-code, which is intended as a readable interpretation of the syntax of the IF-control structure (? 10.2.1.1 syntax).
In one-way selection, the statement or statement block is only executed if the expression is true. There is no alternative.
IF expression is true, THEN execute this statement(s) END of the selection
IF Len(txbFarbwert.Text) = 0 THEN txbFarbwert.MaxLength = 6 Return ENDIF
IF expression is true, THEN execute this instruction(s) IF Key.Code = Key.F1 THEN btnHelp_Click()
IF expression is NOT true, THEN execute this instruction(s) IF NOT txbFarbwert.Text Then Message.Warning("Enter a color value!")
If variant 1 was selected via the RadioButton, then this variant is used for calculation, otherwise the second variant is used:
IF expression is true, THEN Execute this statement (s) (and exit the control structure) ELSE Execute those statement(s) End of selection
IF optV1.Value = True THEN Calculate_V1(iAZahl, iEZahl) ELSE Calculate_V2(iAZahl, iEZahl) ENDIF
The alternative notation of the IF control structure in one line triggers a syntax error in the second line, because no ENDIF is allowed at the end of the line:
(1) IF optV1.Value = True THEN Calc_V1(iAZahl, iEZahl) ELSE Calc_V2(iAZahl, iEZahl) (2) IF optV1.Value = True THEN Calc_V1(iAZahl, iEZahl) ELSE Calc_V2(iAZahl, iEZahl) ENDIF ' Error!
Here is an IF control structure for three (→ k=3) incompatible cases in which you are sure that exactly one of the three cases applies:
IF expression_1 is true, THEN Execute this statement (s)_1 (and exit control structure) ELSE IF expression_2 is true, THEN Execute this statement (s)_2 (and exit control structure) ... ELSE IF expression_k is true, THEN Execute that statement (s)_k END OF the selection
Public Function Calculate(fP As Float, fQ As Float) As Variant[] Dim fDiskriminante As Float = 0 Dim fX1, fX2 As Float Dim fXC1, fXC2 As Complex fDiskriminante = (fP * fP) / 4 - fQ IF Sgn(fDiskriminante) = 1 THEN ' D>0 fX1 = - fP / 2 - Sqr(fDiskriminante) fX2 = - fP / 2 + Sqr(fDiskriminante) Return [fX1, fX2] ELSE IF Sgn(fDiskriminante) = 0 Then ' D=0 fX1 = - fP / 2 fX2 = fX1 Return [fX1, fX2] ELSE IF Sgn(fDiskriminante) = -1 Then ' D<0 fXC1 = Complex(- fP / 2, - Sqr(- fDiskriminante)) fXC2 = fXC1.Conj() Return [fX1, fX2] ENDIF End ' Calculate(fP As Float, fQ As Float) As Variant[]
Example
IF expression_1 is true, THEN Execute this statement(s)_1 (and exit control structure) ELSE IF expression_2 is true, THEN Execute this statement(s)_2 (and exit control structure) ... ELSE unconditionally execute that instruction(s)! END of the selection
Public Sub GetStatus(sStatus As String) IF sStatus Like "[+Pp]*" THEN Message.Info(IIf(sStatus Begins "+", "Status: positiv", "Status: " & sStatus)) ELSE IF sStatus Like "[-Nn]*" THEN If sStatus Begins "-" Then sStatus = "negativ" Message.Info("Status: " & sStatus) ELSE Message.Error("Der Status konnte NICHT ermittelt werden!") ENDIF End ' GetStatus(sStatus As String)
The unconditional use of ELSE is often used for error messages.
Example
Several expressions linked via' AND IF' or' OR IF' are used in a procedure in the following examples:
WENN Ausdruck_1 wahr ist UND WENN auch Ausdruck_2 wahr ist, DANN diese Anweisung(en) ausführen ENDE der Auswahl
Public Sub txbFarbwert_KeyPress() IF (Key.Control AND Key.Code = Key.F1) THEN btnHelp_Click() IF (Key.Code = Key.Return OR Key.Code = Key.Enter) AND IF (txbFarbwert.Text) THEN Message.Info("The characters entered are:\n\n" & Upper(txbFarbwert.Text)) IF Left(txbFarbwert.Text, 1) = "&" THEN txbFarbwert.MaxLength = 7 ELSE txbFarbwert.MaxLength = 6 ENDIF ENDIF ' Key.Code = Key.Return OR Key.Code = Key.Enter AND ...? IF (Key.Code = Key.BackSpace) AND IF (Len(txbFarbwert.Text) > 0) THEN txbFarbwert.Text = Left(txbFarbwert.Text, Len(txbFarbwert.Text) - 1) ENDIF ' Key.Code = Key.BackSpace AND Len(txbFarbwert.Text) > 0 ? ' Permissible characters for a color value in hexadecimal representation IF Key.Text NOT Like "[&0-9a-fA-F]" THEN Stop Event ENDIF ' Key.Text NOT Like "[&0-9a-fA-F]" End ' txbFarbwert_KeyPress()
Example
IF expression_1 is true OR IF expression_2 is true, THEN execute this statement(s) END of the selection
Private Sub ResultSave() Dim sMessage1, sMessage2 As String Dialog.Path = sScriptFilePath Dialog.Title = ("Save the result matrix!") Dialog.Filter = ["*.fit", ("GnuPlot-Skript-Datei"), "*", ("Alle Dateien")] If Dialog.SaveFile() Then Message.Warning("Saving has been cancelled!") ' Cancel button pressed! Return Else If (File.Ext(Dialog.Path)) OR IF (File.Ext(Dialog.Path) <> "fit") Then Dialog.Path = File.SetExt(Dialog.Path, "fit") Endif File.Save(Dialog.Path, txaErrorAndFit.Text) Finally btnSaveScriptFile.Enabled = False Catch sMessage1 = ("The result file ") sMessage2 = (" can NOT be saved!") Message.Error("FEHLER!" & Chr(10) & sMessage1 & File.Name(Dialog.Path) & sMessage2) Endif ' Dialog.SaveFile() = True ? End ' ResultSave()
Hints:
The following examples - but also some of the examples mentioned above - can only be understood if you know the content of the term expression in Gambas. In the documentation for' Expression' you will find, among other things, the following:
An expression is a value (a constant, a predefined constant, a variable or the result of a function), which may optionally be preceded by certain operators depending on the type of value, followed by an operator and another value, and so on.
Translated and provided with examples it reads like this:
An expression is a value: a constant (*1), a predefined constant (*2), a variable (*3) or the result of a function call (*4), which can be preceded or followed by certain optional operators (*5) - depending on the type of value - and so on (*6).
Examples of the cases marked (*1) to (*6):
(*1) → 5 or “Test”
(*2) → gb. Integer
(*3) → iIndex
(*4) → Pi(2)
(*5) → NOT bIsActive
(*6) → NOT bIsActive OR IF (iLevel < iMinLevel)
The following applies to expressions associated with the IF control structure:
The IF control structure checks the truth value of an expression. For objects, zero is also the characteristic value for determining the truth value. In all cases, 0 means false and everything else is true.
Examples
Public Sub btnTest_Click() Dim iInteger As Integer Print iInteger IF iInteger THEN Print "JA" ELSE Print "NEIN" ENDIF '-------------------------------------------------------- IF txbPingNumber.Text THEN Print "TEXTBOX ENTHÄLT TEXT." ELSE Print "TEXTBOX ENTHÄLT KEINEN TEXT." ENDIF '-------------------------------------------------------- IF txbPingNumber THEN Print "DAS OBJEKT 'txbPingCount' EXISTIERT" ELSE Print "DAS OBJEKT 'txbPingCount' EXISTIERT NICHT" ENDIF '-------------------------------------------------------- IF $hPing THEN Print "DER PING-PROZESS LEBT..." ELSE Print "VOM PING-PROZESS IST NICHTS ZU SEHEN..." ENDIF '-------------------------------------------------------- TRY File.Save("/usr/local/backup.bak", txaOutput.Text) IF ERROR THEN Print "Fehler: "; Error.Text; " - "; Error.Where Return ENDIF End ' btnTest_Click()
ERROR alone/ is a keyword of the language Gambas. True is returned if the last TRY statement triggered an error. Minisini advises using ERROR only in this context.
These outputs were displayed in the console of the Gambas IDE:
0 NO THE TEXTBOX CONTAINS TEXT. THE OBJECT' txbPingCount' EXIST OF THE PING PROCESS IS NOT VISIBLE.... ERROR: Access forbidden - FMain. btnTest_Click.135
In diesem Kapitel werden die folgenden Varianten der IF-Kontroll-Struktur beschrieben:
Die Syntax für die IF-Kontroll-Struktur im zweiten Teil steht für die Fälle, in denen jeweils nur eine (bedingte) Auswahl in einer Zeile formuliert wird:
IF Expression [ { AND IF | OR IF } Expression ... ] [ THEN ] ... [ ELSE IF Expression [ { AND IF | OR IF } Expression ... ] [ THEN ] ... ] [ ELSE ... ] ENDIF
IF Expression [ { AND IF | OR IF } Expression ... ] THEN ... IF Expression [ { AND IF | OR IF } Expression ... ] THEN ... ELSE …
Die folgenden Beispiele zeigen vorwiegend Gambas-Quelltext-Ausschnitte und werden kurz kommentiert. Den Beispielen wird zum Teil Pseudo-Code vorangestellt, der als gut lesbare Interpretation der Syntax der IF-Kontroll-Struktur (→ 10.2.1.1 Syntax) gedacht ist.
Bei der einseitigen Auswahl wird die Anweisung oder der Anweisungsblock nur ausgeführt, wenn der Ausdruck wahr ist. Eine Alternative existiert nicht.
WENN Ausdruck wahr ist, DANN diese Anweisung(en) ausführen ENDE der Auswahl
IF Len(txbFarbwert.Text) = 0 THEN txbFarbwert.MaxLength = 6 Return ENDIF
WENN Ausdruck wahr ist, DANN diese Anweisung(en) ausführen IF Key.Code = Key.F1 THEN btnHelp_Click()
WENN Ausdruck NICHT wahr ist, DANN diese Anweisung(en) ausführen IF NOT txbFarbwert.Text Then Message.Warning("Geben Sie einen Farbwert ein!")
Wenn Variante 1 über den RadioButton ausgewählt wurde, dann wird nach dieser Variante gerechnet, sonst nach der 2. Variante:
WENN Ausdruck wahr ist, DANN diese Anweisung(en) ausführen (und Kontroll-Struktur verlassen) SONST jene Anweisung(en) ausführen ENDE der Auswahl
IF optV1.Value = True THEN Calculate_V1(iAZahl, iEZahl) ELSE Calculate_V2(iAZahl, iEZahl) ENDIF
Die alternative Schreibweise der IF-Kontroll-Struktur in einer Zeile löst in der zweiten Zeile einen Syntaxfehler aus, weil in diesem Fall am Zeilen-Ende kein ENDIF stehen darf:
(1) IF optV1.Value = True THEN Calc_V1(iAZahl, iEZahl) ELSE Calc_V2(iAZahl, iEZahl) (2) IF optV1.Value = True THEN Calc_V1(iAZahl, iEZahl) ELSE Calc_V2(iAZahl, iEZahl) ENDIF ' FEHLER!
Hier eine IF-Kontroll-Struktur für drei (→ k=3) unvereinbare Fälle bei denen Sie sicher sind, dass genau einer der drei Fälle zutrifft:
WENN Ausdruck_1 wahr ist, DANN diese Anweisung(en)_1 ausführen (und Kontroll-Struktur verlassen) SONST WENN Ausdruck_2 wahr ist, DANN diese Anweisung(en)_2 ausführen (und Kontroll-Struktur verlassen) ... SONST WENN Ausdruck_k wahr ist, DANN jene Anweisung(en)_k ausführen ENDE der Auswahl
Public Function Calculate(fP As Float, fQ As Float) As Variant[] Dim fDiskriminante As Float = 0 Dim fX1, fX2 As Float Dim fXC1, fXC2 As Complex fDiskriminante = (fP * fP) / 4 - fQ IF Sgn(fDiskriminante) = 1 THEN ' D>0 fX1 = - fP / 2 - Sqr(fDiskriminante) fX2 = - fP / 2 + Sqr(fDiskriminante) Return [fX1, fX2] ELSE IF Sgn(fDiskriminante) = 0 Then ' D=0 fX1 = - fP / 2 fX2 = fX1 Return [fX1, fX2] ELSE IF Sgn(fDiskriminante) = -1 Then ' D<0 fXC1 = Complex(- fP / 2, - Sqr(- fDiskriminante)) fXC2 = fXC1.Conj() Return [fX1, fX2] ENDIF End ' Calculate(fP As Float, fQ As Float) As Variant[]
Beispiel
WENN Ausdruck_1 wahr ist, DANN diese Anweisung(en)_1 ausführen (und Kontroll-Struktur verlassen) SONST WENN Ausdruck_2 wahr ist, DANN diese Anweisung(en)_2 ausführen (und Kontroll-Struktur verlassen) ... SONST bedingungslos jene Anweisung(en) ausführen! ENDE der Auswahl
Public Sub GetStatus(sStatus As String) IF sStatus Like "[+Pp]*" THEN Message.Info(IIf(sStatus Begins "+", "Status: positiv", "Status: " & sStatus)) ELSE IF sStatus Like "[-Nn]*" THEN If sStatus Begins "-" Then sStatus = "negativ" Message.Info("Status: " & sStatus) ELSE Message.Error("Der Status konnte NICHT ermittelt werden!") ENDIF End ' GetStatus(sStatus As String)
Die bedingungslose Verwendung von ELSE wird oft für Fehler-Meldungen verwendet.
Beispiel
Mehrere über 'AND IF' oder 'OR IF' verknüpfte Ausdrücke werden in den nächsten Beispielen jeweils in einer Prozedur eingesetzt:
WENN Ausdruck_1 wahr ist UND WENN auch Ausdruck_2 wahr ist, DANN diese Anweisung(en) ausführen ENDE der Auswahl
Public Sub txbFarbwert_KeyPress() IF (Key.Control AND Key.Code = Key.F1) THEN btnHelp_Click() IF (Key.Code = Key.Return OR Key.Code = Key.Enter) AND IF (txbFarbwert.Text) THEN Message.Info("Die eingegebenen Zeichen sind:\n\n" & Upper(txbFarbwert.Text)) IF Left(txbFarbwert.Text, 1) = "&" THEN txbFarbwert.MaxLength = 7 ELSE txbFarbwert.MaxLength = 6 ENDIF ' Left(txbFarbwert.Text, 1) = "&" ? ENDIF ' Key.Code = Key.Return OR Key.Code = Key.Enter AND ...? IF (Key.Code = Key.BackSpace) AND IF (Len(txbFarbwert.Text) > 0) THEN txbFarbwert.Text = Left(txbFarbwert.Text, Len(txbFarbwert.Text) - 1) ENDIF ' Key.Code = Key.BackSpace AND Len(txbFarbwert.Text) > 0 ? ' Zulässige Zeichen für einen Farbwert in hexadezimaler Darstellung IF Key.Text NOT Like "[&0-9a-fA-F]" THEN Stop Event ENDIF ' Key.Text NOT Like "[&0-9a-fA-F]" End ' txbFarbwert_KeyPress()
Beispiel
WENN Ausdruck_1 wahr ist ODER WENN Ausdruck_2 wahr ist, DANN diese Anweisung(en) ausführen ENDE der Auswahl
Private Sub ResultSave() Dim sMessage1, sMessage2 As String Dialog.Path = sScriptFilePath Dialog.Title = ("Speichern Sie die Ergebnis-Matrix!") Dialog.Filter = ["*.fit", ("GnuPlot-Skript-Datei"), "*", ("Alle Dateien")] If Dialog.SaveFile() Then Message.Warning("Das Speichern wurde abgebrochen!") ' Abbrechen-Button wurde gedrückt! Return Else If (File.Ext(Dialog.Path)) OR IF (File.Ext(Dialog.Path) <> "fit") Then Dialog.Path = File.SetExt(Dialog.Path, "fit") Endif File.Save(Dialog.Path, txaErrorAndFit.Text) Finally btnSaveScriptFile.Enabled = False Catch sMessage1 = ("Die Ergebnis-Datei ") sMessage2 = (" kann NICHT gespeichert werden!") Message.Error("FEHLER!" & Chr(10) & sMessage1 & File.Name(Dialog.Path) & sMessage2) Endif ' Dialog.SaveFile() = True ? End ' ResultSave()
Hinweise:
Die folgenden Beispiele – aber auch einige der o.a. Beispiele – sind nur dann zu verstehen, wenn man den Inhalt des Begriffs Expression in Gambas genau kennt. In der Dokumentation zu 'Ausdruck' steht u.a.:
An expression is a value (a constant, a predefined constant, a variable or the result of a function), which may optionally be preceded by certain operators depending on the type of value, followed by an operator and another value, and so on.
Übersetzt und mit Beispielen versehen liest sich das so:
Ein Ausdruck ist ein Wert: Eine Konstante (*1), eine vordefinierte Konstante (*2), eine Variable (*3) oder das Ergebnis eines Funktionsaufrufs (*4), dem optional bestimmte Operatoren nach- oder vorangestellt werden (*5) – je nach Typ des Wertes – und so weiter (*6).
Beispiele für die markierten Fälle (*1) bis (*6):
(*1) → 5 oder “Test”
(*2) → gb.Integer
(*3) → iIndex
(*4) → Pi(2)
(*5) → NOT bIsActive
(*6) → NOT bIsActive OR IF (iLevel < iMinLevel)
In Bezug auf Ausdruck im Zusammenhang mit der IF-Kontroll-Struktur gilt Folgendes:
Die IF-Kontroll-Struktur prüft den Wahrheitswert eines Ausdrucks. Schreibt man zum Beispiel als Ausdruck eine Integer-Variable, ist das nach der o.a. Definition immer noch ein Ausdruck und der Wahrheitswert eines Integers ist definiert als der Wahrheitswert der Relation iInteger <> 0. Analog gilt für einen String: sString <> Null, wobei auch die leere Zeichenkette als Null gilt. Bei Objekten ist ebenfalls Null der charakteristische Wert für die Wahrheitswertbestimmung. In allen Fällen bedeutet 0 → False und alles andere ist True.
Beispiele
Public Sub btnTest_Click() Dim iInteger As Integer Print iInteger IF iInteger THEN Print "JA" ELSE Print "NEIN" ENDIF '-------------------------------------------------------- IF txbPingNumber.Text THEN Print "TEXTBOX ENTHÄLT TEXT." ELSE Print "TEXTBOX ENTHÄLT KEINEN TEXT." ENDIF '-------------------------------------------------------- IF txbPingNumber THEN Print "DAS OBJEKT 'txbPingCount' EXISTIERT" ELSE Print "DAS OBJEKT 'txbPingCount' EXISTIERT NICHT" ENDIF '-------------------------------------------------------- IF $hPing THEN Print "DER PING-PROZESS LEBT..." ELSE Print "VOM PING-PROZESS IST NICHTS ZU SEHEN..." ENDIF '-------------------------------------------------------- TRY File.Save("/usr/local/backup.bak", txaOutput.Text) IF ERROR THEN Print "Fehler: "; Error.Text; " - "; Error.Where Return ENDIF End ' btnTest_Click()
ERROR allein ist ein Schlüsselwort der Sprache Gambas. Es wird True zurückgegeben, wenn die letzte TRY-Anweisung einen Fehler auslöste. Minisini rät dazu, ERROR nur in diesem Kontext zu verwenden.
Diese Ausgaben wurden in der Konsole der Gambas-IDE angezeigt:
0 NEIN DIE TEXTBOX ENTHÄLT TEXT. DAS OBJEKT 'txbPingCount' EXISTIERT VOM PING-PROZESS IST NICHTS ZU SEHEN... FEHLER: Access forbidden - FMain.btnTest_Click.135