Post by matty47 on May 6, 2023 1:57:33 GMT -6
A little code that I have translated allowing associative arrays or key/value pairs. May be of some interest.
'Set up two arrays
dim values$[1]
dim keys$[1]
Function findKey(k$)
'return index or -1 if key not found
dim n
for n = 0 to ArraySize(keys$,1)-1
if keys$[n] = k$ Then
Return n
end if
Next
Return -1
End Function
function freeKey()
'find the index of a free element in the array
dim n
for n = 0 to ArraySize(keys$,1)-1
if keys$[n] = "" Then
Return n
end if
next
ReDim keys$[ArraySize(keys$,1)+1]
ReDim values$[ArraySize(keys$,1)+1]
Return n+1
end Function
Sub updateKey(k$,value$)
'update or add an item
dim i
i = findKey(k$)
if i = -1 Then
i=freeKey()
end if
keys$[i]=k$
values$[i]=value$
End Sub
sub deleteKey(k$)
'delete by clearing the key - does not reduce array Size
dim i
i= findKey(k$)
if i<> -1 Then
keys$[i]=""
values$[i] = ""
end if
end Sub
function getValue$(k$)
'return a value by key or "" if not existing
dim i
i=findKey(k$)
if i= -1 Then
Return ""
End if
Return values$[i]
end Function
function countKeys()
'return the number of items
'need to skip empty keys - the deleted ones
dim k,n
k=0
for n=0 to ArraySize(keys$,1)-1
if keys$[n] <> "" Then
k = k+1
end if
Next
return k
end Function
function getValueByIndex$(i)
'get a value by the index
'need to skip empty keys - the deleted ones
dim k,n
k=0
for n=0 to ArraySize(keys$,1)-1
if keys$[n] <> "" Then
if k = i then
return values$[k]
end if
k=k+1
end if
Next
return ""
end Function
function getKeyByIndex$(i)
'get a key by the index number
'skip the empty keys - the deleted ones
dim k,n
k=0
for n = 0 to ArraySize(keys$,1)-1
if keys$[n] <> "" Then
if k=i Then
Return keys$[k]
end if
k=k+1
end if
Next
Return ""
end Function
Function listKeys$()
dim n
dim list$
list$ = ""
for n=0 to ArraySize(keys$,1)-1
if keys$[n] <> "" Then
list$ = list$ + keys$[n] + " " + values$[n] + "\n"
end if
Next
Return list$
end Function
'Now to test whether this works
updateKey("a","Apple")
updateKey("b","Banana")
updateKey("c","Cucumber")
updateKey("d","Dagwood")
updateKey("e","Evelyn")
Print (listKeys$)
Print("Now delete key c")
deleteKey("c")
Print (listKeys$)