### Basic Syntax Samples

Just a few reminders of Basic syntax usage.
If-Then-Else
There are two options on how to use If-Then-Else:
If Value = -1 Then Result = 0
If Value = -1 Then
Result = 0
End If
While
Do While condition
...
Loop
For
For variable = value1 To value2 [Step interval]
...
Next
Example For i
For i = 1 To 5
Log("Nr " & i)
Next
Example For i Step -1
Dim s() As String = Regex.Split(CRLF, "1 2 3")
For i = s.Length - 1 To 0 Step -1
Log(s(i)
Next
Hint:
Consider using Smart Strings to Log, like Log($"Nr ${i}"$)
For Each variable As type In collection
...
Next
Like...
For Each Item As String In MyList
...
Next
Hint:
Consider using For Each as default because much faster the For i, but also easier to use.
Example For Each: Sum
Dim Numbers() As Int
Numbers = Array As Int(1,2,3,4,5)
Dim Sum As Int
For Each n As Int In Numbers
Sum = Sum + n
Next
Log("Sum of 1 to 5 = " & Sum)
Output: Sum of 1 To 5 = 15
Example For Each: using a Custom Type
'List the content of the ContactType
'Define the Contact Type
Type ContactType (Id As Int, Name As String, EMail As String)
'Define the contact map. Each entry is ID = ContactType
Private ContactMap As Map
'Each Mapentry has as Key an Int and as Value a ContactType
'In the for each loop use the map values to get the contacts as contacttype
`Sub ListMap
For Each m As ContactType In ContactMap.Values
Log($"${m.Name} ${m.EMail} "$)
Next
End Sub`
Example For Each: customized TableView with CheckBoxes (see also Category TableView)
'A button with lists the CheckBoxes selected
'Note that the table has only one column which is assigned to a CheckBox
`Sub btnListSelected_Action
For Each tvo() As Object In TableView1.Items
Dim cb As CheckBox = tvo(0)
If cb.checked Then Log($"Selected ${cb.Text}"$)
Next
End Sub`
Select
Select value
Case 1
...
Case 2
...
Case Else
...
End Select
Array
Define a String Array like
Private Const Status() As String = Array As String("OFF", "ON")
Use
Status(0) resulting in OFF
Status(1) resulting in ON
Function
Returns a result, i.e.
`Sub Add(a As Int, b As Int) As Int
Return a + b
End Sub`
Log(Add(5,4)) outputs 9
Subroutine
Repeats lines of code, i.e.
`Sub ToLog(s As String)
Log(s)
End Sub`
ToLog("Hello World!") outputs Hello World! in the B4J IDE Logs Tab

Changed: , Category: Basic Syntax, File: T6C165M1212.htm, ID: 1212