Functies voor conversie (Apache OpenOffice runtime-bibliotheek)

From Apache OpenOffice Wiki
< NL‎ | Documentation‎ | BASIC Guide
Revision as of 15:56, 19 January 2013 by DiGro (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
Book.png

In veel situaties ontstaan omstandigheden waaronder een variabele van het ene type moet worden gewijzigd naar een variabele van een ander type.

Impliciete en expliciete conversies van typen

De eenvoudigste manier om een variabele te wijzigen van het ene type naar een ander is om een toewijzing te gebruiken.

Dim A As String
Dim B As Integer
 
B = 101 
A = B

In dit voorbeeld is variabele A een string (tekenreeks) en variabele B is een integer (geheel getal). Apache OpenOffice BASIC zorgt er voor dat variabele B naar een string wordt geconverteerd gedurende de toewijzing aan variabele A. Deze conversie is veel omvattender dan het lijkt: de integer B blijft in het werkgeheugen in de vorm van een twee-byte lang getal. Aan de andere kant is A een string en de computer bewaart een één- of twee-byte lange waarde voor elk teken (elk getal). Daarom moet, vóórdat de inhoud van B naar A wordt gekopieerd, B worden geconverteerd naar de interne indeling van A.

Anders dan in de meeste programmeertalen voert BASIC conversies van typen automatisch uit. Dit kan echter fatale consequenties hebben. Bij nadere beschouwing, blijkt de volgende reeks code

Dim A As String
Dim B As Integer
Dim C As Integer
 
B = 1 
C = 1
A = B + C

die op het eerste gezicht recht toe recht aan lijkt te zijn, uiteindelijk een soort valstrik te zijn. De interpreter van BASIC berekent eerst het resultaat van het proces om op te tellen en converteert dat dan naar een string, die, als het resultaat ervan, de string 2 produceert.

Als, aan de andere kant, de interpreter van BASIC eerst de beginwaarden B en C naar een string converteert en de operator plus toepast op het resultaat, produceert het de string 11.

Hetzelfde is van toepassing bij het gebruiken van variabelen van het type Variant:

Dim A 
Dim B 
Dim C 
 
B = 1 
C = "1"
A = B + C

Omdat variabelen van het type variant zowel getallen als tekenreeksen mogen bevatten, is het niet helder of de variabele A wordt toegewezen aan het getal 2 of de tekenreeks 11.

The error sources noted for implicit type conversions can only be avoided by careful programming; for example, by not using the variant data type.

To avoid other errors resulting from implicit type conversions, Apache OpenOffice Basic offers a range of conversion functions, which you can use to define when the data type of an operation should be converted:

CStr(Var)
converts any data type into a string.
CInt(Var)
converts any data types into an integer value.
CLng(Var)
converts any data types into a long value.
CSng(Var)
converts any data types into a single value.
CDbl(Var)
converts any data types into a double value.
CBool(Var)
converts any data types into a Boolean value.
CDate(Var)
converts any data types into a date value.

You can use these conversion functions to define how Apache OpenOffice Basic should perform these type conversion operations:

Dim A As String
Dim B As Integer
Dim C As Integer
 
B = 1 
C = 1
A = CStr(B + C)         ' B and C are added together first, then
                        ' converted to the string "2"
A = CStr(B) + CStr(C)   ' B and C are converted into a string,then
                        ' combined to produce the string "11"

During the first addition in the example, Apache OpenOffice Basic first adds the integer variables and then converts the result into a chain of characters. A is assigned the string 2. In the second instance, the integer variables are first converted into two strings and then linked with one another by means of the assignment. A is therefore assigned the string 11.

The numerical CSng and CDbl conversion functions also accept decimal numbers. The symbol defined in the corresponding country-specific settings must be used as the decimal point symbol. Conversely, the CStr methods use the currently selected country-specific settings when formatting numbers, dates and time details.

The Val function is different from the Csng, Cdbl and Cstr methods. It converts a string into a number; however it always expects a period to be used as the decimal point symbol.

Dim A As String
Dim B As Double
 
A = "2.22"
B = Val(A)      ' Is converted correctly regardless of the
                ' country-specific settings

Checking the Content of Variables

In some instances, the date cannot be converted:

Dim A As String
Dim B As Date
 
A = "test"
B = A            ' Creates error message

In the example shown, the assignment of the test string to a date variable makes no sense, so the Basic interpreter reports an error. The same applies when attempting to assign a string to a Boolean variable:

Dim A As String
Dim B As Boolean
 
A = "test"
B = A            ' Creates error message

Again, the basic interpreter reports an error.

These error messages can be avoided by checking the program before an assignment, in order to establish whether the content of the variable to be assigned matches the type of the target variable. Apache OpenOffice Basic provides the following test functions for this purpose:

IsNumeric(Value)
checks whether a value is a number.
IsDate(Value)
checks whether a value is a date.
IsArray(Value)
checks whether a value is an array.

These functions are especially useful when querying user input. For example, you can check whether a user has typed a valid number or date.

If IsNumeric(UserInput) Then
  ValidInput = UserInput
Else
  ValidInput = 0
  MsgBox "Error message."
End If

In the previous example, if the UserInput variable contains a valid numerical value, then this is assigned to the ValidInput variable. If UserInput does not contain a valid number, ValidInput is assigned the value 0 and an error message is returned.

While test functions exist for checking numbers, date details and arrays in Apache OpenOffice Basic, a corresponding function for checking Boolean values does not exist. The functionality can, however, be imitated by using the IsBoolean function:

Function IsBoolean(Value As Variant) As Boolean
  On Error Goto ErrorIsBoolean:
  Dim Dummy As Boolean
  Dummy = Value
  IsBoolean = True
  On Error Goto 0
  Exit Sub
 
  ErrorIsBoolean:
  IsBoolean = False
  On Error Goto 0
End Function

The IsBoolean function defines an internal Dummy help variable of the Boolean type and tries to assign this to the transferred value. If assignment is successful, the function returns True. If it fails, a runtime error is produced, the error handler intercepts the error, and the function returns False.

Documentation note.png VBA : If a string in Apache OpenOffice Basic contains a non-numerical value and if this is assigned to a number, Apache OpenOffice Basic does not produce an error message, but stops converting the string at the first invalid character. This procedure differs from VBA. There, an error is triggered and program implementation terminated if a corresponding assignment is executed.


Content on this page is licensed under the Public Documentation License (PDL).
Personal tools