B4J Question itterate with For Each over global variables or custom type

Chris2

Active Member
Licensed User
I think I may be missing something obvious here, but I can't find the solution either in my head or the forums.
I'm trying to avoid Code Smell #7 - https://www.b4x.com/android/forum/threads/b4x-code-smells-common-mistakes-and-other-tips.116651/

Can I use a For Each loop to assign a value to multiple global variables, or elements of a custom type?

E.g. In the following, the For Each loop does not set the global variables to zero
B4X:
Sub Process_Globals
    Private a, b, c As Double
End Sub

Sub AppStart (Args() As String)
    a=5
    b=5
    c=5
    Log(a)
    Log(b)
    Log(c)
    
    For Each v As Double In Array(a, b, c)
        v=0
    Next
    
    Log(a)
    Log(b)
    Log(c)
End Sub

Logs..:
Waiting for debugger to connect...
Program started.
5
5
5
5
5
5
Program terminated (StartMessageLoop was not called).

Similarly, can I set multiple elements of a custom type to the same value?
B4X:
Sub Process_Globals
    Type DataRow (val1 As Double, val2 As Double, val3 As Double)
End Sub

Sub AppStart (Args() As String)
    Dim row As DataRow
    row.Initialize
    row.val1=6
    row.val2=6
    row.val3=6
    Log(row.val1)
    Log(row.val2)
    Log(row.val3)
    
    For Each v As Double In Array(row.val1, row.val2, row.val3)
        v=0
    Next
    
    Log(row.val1)
    Log(row.val2)
    Log(row.val3)
End Sub

Logs..:
Waiting for debugger to connect...
Program started.
6
6
6
6
6
6
Program terminated (StartMessageLoop was not called).

I *think* I understand why each of the above doesn't work - because I'm creating a new variable with the For Each loops, and setting that to zero rather than the global variables or custom type values themselves.
But I can't figure out how to make it work.

Thanks in advance.
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
Can I use a For Each loop to assign a value to multiple global variables, or elements of a custom type?
No.

Maybe you need to use a List or Map instead of these variables, however remember that design patterns and best practices are just tools in the hand of the developer. If you have three fields and it makes sense to have three separate fields then don't work too hard to make the code "more elegant".
A simple solution such as:
B4X:
Sub SetSameValue(v As Double)
 a = v
 b = v
 c = b
End Sub
is good enough.
 
Upvote 0
Top