Table of Contents

5.4.1 Gambas scripts (local)

All language elements of gambas can be used in the Gambas scripts. The structure of a Gambas script as a text file is not formalized except for the header. You can freely assign the file extension. You should follow the suggestion to use gbs3 as extension. The following script shows a proven format:

#!/usr/bin/env gbs3

PUBLIC SUB Main()
  PRINT
  PRINT " Current date: " & SetDateToGerman(Now) & "."
  PRINT " It was precisely " & Format$(Now, "hh:nn:ss") & " Clock!"
  PRINT
END ' Main()

PRIVATE FUNCTION SetDateToGerman(dDatum AS Date) AS String

  DIM aMonatMatrix, aWochenTagMatrix AS NEW String[]
  DIM sWochenTag, sTag, sMonat, sJahr AS String

  aMonatMatrix.Clear
  aMonatMatrix = ["January", "February", "March", "April", "May", "June", "July", "August",
              "September", "October", "November", "December"]
  aWochenTagMatrix.Clear
  aWochenTagMatrix = Split("Sunday Monday Tuesday Wednesday Thursday Friday Saturday"., " ")

  sWochenTag = aWochenTagMatrix[WeekDay(dDatum)]
  sTag = Str(Day(dDatum))
  sMonat = aMonatMatrix[Month(dDatum) - 1]
  sJahr = Str(Year(dDatum))

  RETURN sWochenTag & " - " & sTag & ". " & sMonat & " " & sJahr ' Formatierter String

END

Comments:

The above-mentioned content is stored in the file date_time2. gbs3 in the home directory. The file is then made executable:

hans@linux:~$ chmod u+x ./date_time2.gbs3
 
hans@linux:~$ ls -l # Kontrolle
-rwxr-xr-x   1 hans hans    1041 Dez 30 15:24 date_time2.gbs3

The Gambas script file date_time2. gbs3 is called in a console. The current date and the (system) time are displayed:

hans@linux:~$ gbs3 ./date_time2.gbs3
 
 Current date: Tuesday - 1 January 2013.
 It was exactly 15:26:25!
 
hans@linux:~$

The function SetDateToGerman (..) could also have been replaced by this line:

PRINT " Current date: " & Format(Now, "dddd - dd. mmmm yyyy" ) & "."

Using the function SetDateToGerman (..) should only show you how to use different language elements of Gambas in the script source code. This is an advantage compared to conventional scripting languages, which you will only recognize with extensive scripts - a language for different tasks!

5.4.1.1.1 Example 1

The following script reads and displays the environment variables:

#!/usr/bin/env gbs3

PUBLIC SUB Main()
  Print
  Print "Display environment variables"
  Print "--------------------------------"
  Print
  GetEnviroment()
END ' Main()

Public Sub GetEnviroment()
  DIM sElement as String

  FOR EACH sElement IN Application.Env
      Print sElement & " ---> " & Application.Env[sElement]
  NEXT ' sElement

End

The call in the console is made with

hans@linux:~$ gbs3 ./enviroment.gbs3

and returns the environment variables as name-value pairs, each separated by the symbol' —→':

LC_PAPER ---> de_DE.UTF-8
LC_ADDRESS ---> de_DE.UTF-8
SSH_AGENT_PID ---> 1856
LC_MONETARY ---> de_DE.UTF-8
GPG_AGENT_INFO ---> /tmp/keyring-XpXASO/gpg:0:1
TERM ---> xterm
SHELL ---> /bin/bash
..
XAUTHORITY ---> /home/hans/.Xauthority
LC_NAME ---> de_DE.UTF-8
_ ---> /usr/local/bin/gbs3

5.4.1.2 Example 2

This Gambas script outputs the currently used memory, ignoring some memory segments:

#!/usr/bin/env gbs3

Public Sub Main()
  Print "--> The currently used memory is " & CStr(GetUsedMemory()) & " Byte."
End ' Main()

Private Function GetUsedMemory() As Integer
  Dim sExecResult, sValue As String
  Dim aResult As String[]
  Dim cValue As New Collection

  Exec ["cat", "/proc/meminfo"] To sExecResult
  For Each sValue In Split(sExecResult, "\n", "", True)
      aResult = Split(sValue, " ", "", True)
      cValue[Left$(aResult[0], -1)] = aResult[1]
  Next ' sValue

  Return cValue!MemTotal - cValue!MemFree - cValue!Buffers - cValue!Cached +
         cValue!SwapTotal - cValue!SwapFree - cValue!SwapCached
End

The script can then be called in a terminal and outputs the used memory:

hans@linux:~$ gbs3 ./speicher.gbs3
--> The currently used memory is 649116 bytes.
hans@linux:~$

It is also possible to display the more than 40 memory segments directly in a terminal - but without the manipulations in the GetUsedMemory () function, which are only possible and used in one script:

hans@linux:~$ cat /proc/meminfo
MemTotal:        8093648 kB
MemFree:         6519468 kB
Buffers:          145764 kB
..
DirectMap4k:       63104 kB
DirectMap2M:     8241152 kB
hans@linux:~$

5.4.1.3 Example 3

Connecting to a database and reading and displaying selected database data is also no problem for a Gambas script. Here is the source code for the tb_sqlite3. gbs3 script:

#!/usr/bin/env gbs3

USE "gb.db"
USE "gb.db.sqlite3"

Public cDBVerbindung As New Connection

Public Sub Main()
  Dim iDatensatzNummer, iSpaltenNummer As Integer
  Dim sFehler, sFeldName, sSQL_Anweisung As String
  Dim rDBResult As Result

' Syntax:   goDBServer(  TYP,     HOST,               USER,PASS, DATENBANK,    PORT,TABELLE)
  sFehler = goDBServer("sqlite3", User.Home &/ "Liste", "", "", "liste.sqlite", "", "liste")
  If sFehler = "DBError" Then
     Print " A DB connection to the DB server could not be established!"
     Return
  Endif ' sFehler = "DBError" ?

  sSQL_Anweisung = "SELECT * FROM liste"
  rDBResult = cDBVerbindung.Exec(sSQL_Anweisung)

  If rDBResult.Count = 0 Then
     Print "The number of selected records is zero!"
     Return
  Endif

  Print
  Print "Report vom " & Format(Now, "dd. mmmm yyyy") & " - " & Format$(Now, "hh:nn") & " Clock"
  Print "-------------------------------------------------"
  Print

  IF rDBResult.Available THEN

  For iDatensatzNummer = 0 To rDBResult.Count - 1
   rDBResult.MoveTo(iDatensatzNummer)
   For iSpaltenNummer = 0 To rDBResult.Fields.Count - 1
    Print Upper(rDBResult.Fields[iSpaltenNummer].Name) & " ---> " & rDBResult[iSpaltenNummer]
   Next ' Spalte
    Print
  Next ' Dataset

  Endif ' MDataBase.rDBResult.Available

  Print "===== DB-Report-Ende ==========================="
  Print

End ' Main()

Private Function goDBServer(DBType As String, DBHost As String, DBUserName As String,
                 DBUserPassword As String, DBName As String, DBPort As String,
                 DBTabellenName As String) As String

  cDBVerbindung.Type = Lower(DBType)      ' The type must be written in lower case!
  cDBVerbindung.Host = DBHost
  cDBVerbindung.User = DBUserName         ' ---> Only for MySQL and PostgreSQL
  cDBVerbindung.Password = DBUserPassword ' ---> Only for MySQL and PostgreSQL
  cDBVerbindung.Name = DBName
  cDBVerbindung.Port = DBPort             ' ---> Only for MySQL and PostgreSQL

  Try cDBVerbindung.Open()
  If Error Then Return "DBFehler" ' ERROR

End

With the Gambas script mentioned above, the data records are only displayed in blocks and lines:

hans@linux:~$ gbs3 ./tb_sqlite3.gbs3

Database Report from 30 December 2012 - 16:22 hrs
-------------------------------------------------

ID ---> 1
SURNAME ---> Eagle
Forename ---> Anne
PLACE OF RESIDENCE ---> Osterburg
POSTCODE ---> 39606
STREET ---> Werbener Strasse 20
TELEPHONE LANDLINE ---> 03937864322
MOBILE PHONE ---> 01712323456
EMAIL ADDRESS ---> adler.anne@web.de
WEB ADDRESS --->
DATE OF BIRTH ---> 06/22/2005
NOTES ---> "Jugend forscht" - 2013

Error messages are also displayed in the console. In the first case, the error is caught and displayed by a separate error message, while in the second case, only the internal error routine is triggered:

hans@linux:~$ gbs3 ./tb_sqlite3.gbs3
 A DB connection to the DB server could not be established!
hans@linux:~$
hans@linux:~$ gbs3 ./tb_sqlite3.gbs3
MMain.Main.26: Query failed: SQL error or missing database
1: MMain.Main.26
hans@linux:~$