Friday, July 08, 2016

Keyed dictionary lookup in Liberty BASIC

Liberty BASIC has a way to manage collections of data by using arrays and you look up the information by numeric position.  You can do a lot with this but it doesn't let you look up information by name.

We can provide an easy to use way to do this in Liberty BASIC by using the string functions of Liberty BASIC.  By using a single string we can have easy lookup of values by name and also have the ability to store the collection of values in a file and retrieve it simply.  In some versions of BASIC this is only useful for small lists of information because of string size limitations of 255.  Liberty BASIC permits strings of millions of characters so this is not a problem.

Here is a very simple demo of the concept just to get us started.  In future postings we will explain and enhance the way this works.

global dictionary$

call setValueByName "first", "Tom"
call setValueByName "last", "Thumb"
call setValueByName "phone", "555-555-1234"

print getValue$("last")
print getValue$("blah")
print getValue$("phone")
print getValue$("first")

sub setValueByName key$, value$
  dictionary$ = "~key~"+key$+"~value~"+value$+dictionary$
end sub

function getValue$(key$)
  getValue$ = chr$(0)
  keyPosition = instr(dictionary$, "~key~"+key$)
  if keyPosition > 0 then
    keyPosition = keyPosition + 5  'skip over key tag
    valuePosition = instr(dictionary$, "~value~",  keyPosition)
    if valuePosition > 0 then
      valuePosition = valuePosition + 7   'skip over value tag
      endPosition = instr(dictionary$, "~key~", valuePosition)
      if endPosition > 0 then
        getValue$ = mid$(dictionary$, valuePosition, endPosition - valuePosition)
      else
        getValue$ = mid$(dictionary$, valuePosition)
      end if
    end if
  end if
end function