Loose Variable Typing

RichardN

Well-Known Member
Licensed User
Longtime User
I'm having a little difficulty getting variable typing straight in my mind, for instance the expression:

varInt = txtEditText.Text .....works fine when txtEditText.Text ="123"

But where txtEditText.Text = Null

varInt = txtEditText.Text ....throws an exception instead of returning zero.

So I have to write:

If txtEditText.Text = Null Then
varInt = 0
Else
varInt = txtEditText.Text
End If

...Surely there is a simpler way of writing this ???
 

Jim Brown

Active Member
Licensed User
Longtime User
In my application I am checking for a valid number first. Like this:
B4X:
If Not(IsNumber(txtEditText.Text)) Then
   txtEditText.Text="0.0"
End If

However, If your text field only requires numbers you can set the Input Type to NUMBERS or DECIMAL_NUMBERS
(See options in designer or the txtEditText.InputType settings)

That will block any unwanted characters
 
Last edited:
Upvote 0

RichardN

Well-Known Member
Licensed User
Longtime User
Jim,

Appreciate what you say about typing the data entry field....that's easy but what I am really after is economy of code. In traditional BASIC:

Where varString = "abc" ..... VAL(varString) returns 0
Where varString = "" ..... VAL(varString) returns 0
Where varString = "123" ..... VAL(varString) returns 123


Is there a one-liner in B4A that will convert a varString to varNumeric without having to check that the string is not a Null first?
 
Upvote 0

Jim Brown

Active Member
Licensed User
Longtime User
There appears to be no function. I tried Abs() but that errors out when the string is Null. How about write your own Val() function?
B4X:
' string to int casting

Sub Globals
   Dim t As String
End Sub

Sub Activity_Create(FirstTime As Boolean)
   '
   t=Null
   Log(Val(t))
   '
   t="abc"
   Log(Val(t))
   '
   t=123
   Log(Val(t))
   '
End Sub

Sub Val(s As String) As Int
   If Not(IsNumber(s)) Then Return 0
   Return s
End Sub
 
Upvote 0

agraham

Expert
Licensed User
Longtime User
Basic4android supports strong typing better than Basic4ppc where everything used to be a String until the later versions. So unlike Basic4ppc, Basic4android for efficiency reasons does not go out of it's way checking when coercing types, if it doesn't work it throws an exception.

Erel would have to speak for himself but I don't think he intended Basic4android to be a loosely typed language except in as far as it could do with without adding too much code overhead.
 
Upvote 0
Top