B4R Question String declaration Error or "With B4R I always feel like a noob!"

Cableguy

Expert
Licensed User
Longtime User
Hi Guys...

Why does this code give an error?

B4X:
'in Globals:
Private XDirection as string

'In AppStart:
Dim x = Rnd(0,2) As Int
    If x = 0 Then
         XDirection = "Up"
    Else
         XDirection = "Down"
    End If

I get this warning:
 

rwblinn

Well-Known Member
Licensed User
Longtime User
Hi,

understood that strings needs to be converted to bytes, like:
B4X:
XDirection.GetBytes("Up")
XDirection.GetBytes("Down")
 
Upvote 0

Cableguy

Expert
Licensed User
Longtime User
B4R behaves in such a different way that sometimes we forget about it...
I was trying to define an empty string and then after define its value... But that is NOT possible in B4R...
So I searched a bit, and found out that I could use a string array instead, and since the values I need are known, It works like a charm!

B4X:
    Private XDirection() As String = Array As String("Left","Right")
    Private YDirection() As String = Array As String("Up","Down")
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
Make sure to go over this tutorial: https://www.b4x.com/android/forum/threads/memory-variables-and-objects.65672/

Objects created inside regular subs are created on the stack. You cannot assign a stack object to a global variable as the stack object will be invalid when the sub completes.

One solution is to declare a global array with the possible values and then have an index variable (Int) that points to the correct value.
Another option is to use ByteConverter.ObjectCopy to copy the object from the stack to the global variable. However for this to work properly the global variable should point to an object that is large enough to hold the new data.
 
Upvote 0
Top