iOS Question Dim Within A Loop - Why?

RichardN

Well-Known Member
Licensed User
Longtime User
I have noticed this happens occasionally and maybe I should have asked the question earlier. This example applies to B4i but I have also noticed it happening in B4A.

This code does not work:
Dim ThisPosition As LatLng                                       'Before the loop

Do While Locations.NextRow
       
        ThisLat = Locations.GetDouble("Lat")
        ThisLong = Locations.GetDouble("Long")
        ThisPosition.Initialize(ThisLat,ThisLong)            'The values assigned are correct
        PointList.Add(ThisPosition)                               'When checked after the loop is not correct

        gMap.AddMarker3(ThisLat,ThisLong, Locations.GetString("Name"),Bm)
       
Loop

Despite the variable 'ThisPosition' being correctly dimensioned before the loop... (it may even be a global variable), the list 'PointsList' is incorrectly populated. A log reveals that 'ThisPosition' receives the correct value within the loop. However after the loop I find from the log that the list is the correct size but is entirely populated with the last value added.

This works as expected:
Do While Locations.NextRow

        ThisLat = Locations.GetDouble("Lat")
        ThisLong = Locations.GetDouble("Long")
        Dim ThisPosition As LatLng                               'Dim moved inside the loop
        ThisPosition.Initialize(ThisLat,ThisLong)
        PointList.Add(ThisPosition)

        gMap.AddMarker3(ThisLat,ThisLong, Locations.GetString("Name"),Bm)

Loop

Why does this happen? How do you know when you should put a Dim statement inside a loop so that it assigns a value correctly?
 

RichardN

Well-Known Member
Licensed User
Longtime User
Are you suggesting that this applies ONLY to variables that require initialisation?

Is that the rule to follow?
 
Upvote 0
Top