Wednesday, January 17, 2024

Organize and Share Your Code Effortlessly: Exploring the Liberty BASIC Lesson Browser

 The Liberty BASIC Lesson Browser is a super helpful tool for anyone using Liberty BASIC, a really user-friendly programming language. This browser isn't just for learning; it's amazing for keeping all your coding projects neat and organized.

When you use the Lesson Browser, you can easily find your way around lots of programming lessons. But the best part is how it lets you keep all your own codes and programs in one place. Whether you’re working on a small project or something big, this browser makes it easy to save your work, put it into categories, and find it again whenever you need it. This is super handy because it helps you see how much you’ve learned and find old projects quickly.

If you like sharing what you make with others, the Lesson Browser is great for that too. You can show your codes and programs to other people who use Liberty BASIC. This is not only fun but also a great way to get new ideas and make your work even better.

For educators this tool is super useful because it makes it really easy to build educational materials, and for students it provides a great way to keep all your work organized.

So, in short, the Liberty BASIC Lesson Browser is more than just a way to learn programming. It’s a really useful tool for keeping your own coding projects organized and sharing them with friends and other coders. It's a must-have for anyone using Liberty BASIC.

Watch a demo of the Lesson Browser!

Tuesday, January 16, 2024

The Heart Behind Liberty BASIC

 As the creator of Liberty BASIC, I want to share the story behind this programming language, a project born out of my passion for making programming accessible, fun, and wondrous for everyone.  My journey in the realm of coding began with the magical experience of BASIC, a language that opened the doors to the world of software creation for me. I want to bring that same sense of excitement and possibility to others through Liberty BASIC.

What makes this especially inspiring I think is that Liberty BASIC was originally meant to be a programming game, where the player programmed robots in BASIC.

Bringing Back the Magic of BASIC

When I realized that the BASIC I was writing for the robot game would become a real programming tool, I decided to go for it!  My idea for Liberty BASIC was to recapture the spirit of the early days of BASIC. BASIC was the gateway for many into programming. It was simple, inviting, and allowed immediate interaction and results. My vision was to reignite that spark of wonder, making programming as much fun as it was for me when I first started.

Simplicity and Approachability

At the heart of Liberty BASIC lies its simplicity and approachability. The language is designed to be easy to learn and use, especially for those who are new to programming. It’s like giving someone a set of simple, intuitive tools to start building their dream projects right away.

Fun and Immediate Results

One of the unique features of Liberty BASIC is how it makes programming fun. I believe in the power of seeing your work come to life quickly. Beginners should be able to write a few lines of code and immediately see a window pop up, a graphic drawn, or a simple game come to life. This immediate feedback is not just rewarding; it's crucial in maintaining enthusiasm and interest in learning.

Liberty BASIC vs. Other Languages

While other languages like Python and JavaScript are powerful and versatile, they can be daunting for beginners.  I've always tried very hard to balance simplicity with capability. 

My Vision and Journey

My personal journey with programming has always been about the joy of creating and of learning new ways to think. With Liberty BASIC, I wanted to offer a tool that makes programming feel like an adventure, not a chore. It's been heartwarming to see people of all ages take their first steps in programming with Liberty BASIC, discovering the same joy and wonder that I found years ago.

In essence, Liberty BASIC is more than just a programming language; it's a celebration of the simplicity, fun, and wonder that programming can bring. It's been a wonderful journey that I am eager to invite others to join.

Links

        Liberty BASIC website 

        Liberty BASIC community forum  

        Liberty BASIC video playlist  

Saturday, October 08, 2022

The Enduring Appeal of BASIC

 Back in 2018 I started the BASIC Programming Language group on Facebook.  Since then it has grown to more than 7000 members, and the posting has only accelerated.  What I find really interesting about it is that the membership suddenly began to grow very rapidly in the last few months, more than doubling.

When a member wants to post for the first time there are a couple of questions that they need to answer, and I approve or deny the right to post based on the answers, the other groups the person belongs to and I also factor any pending comments.  The overwhelming majority of the requests to post are approved.

One of the questions is, what is your first BASIC or your preferred version of BASIC?

It becomes clear that there are so many different versions of BASIC that people use and have used.  I find this to be very impressive.  Additionally there are a bunch of people in the group who have written their own versions of BASIC, including myself (Liberty BASIC).  This sort of thing is continually ongoing.  BASIC is not a dead language at all!

Another important thing is that there are people of all ages all over the world who are still using and learning BASIC.

Wednesday, September 22, 2021

End User Programming - Real Computer Literacy

Most people will agree that it is good to understand the mechanical working of cars if you are going to drive one. It helps you to drive more safely, and if you break down somewhere you stand a chance of helping yourself out of a tough spot. When you go to the mechanic you will be able to avoid being ripped off by unscrupulous people.

It is no different with computers. If you learn to program computers it helps you to take advantage of them, and not the other way around. This is the real computer literacy; not the ability to operate a tablet or cell phone, or to know your way around the preferences or control panel of Windows or Mac OS. Many times I see people praising this kind of feature knowledge by young people. "Oh, young people are so smart. When I have a problem with my phone I ask my kids for help." We need to give them more than that, or else they may think more highly of themselves than they ought to.

So, what vehicle can we use to give computer literacy to the people? Computer programming is the critical thing because it gives the user a real understanding of computers. For the average person to attain programming skills we don't need a complicated enterprise grade programming language, which would frustrate more than enlighten people. BASIC was the engine for people to learn programming in the early days, and still could be if Windows, Mac and Linux would just include it.  Easy programming languages are missing or hidden from the user, and this causes a very real harm.

Why don't people create their own software anymore? They don't feel the need for it. They can just buy what they need.  While this is true, there are so many times when packaged software doesn't do exactly what is needed. There are also so many kinds of useful software that could be written that will not make it onto store shelves.

In fact they may even wonder why they should bother. They aren't encouraged to learn programming anymore like they once were. They don't know what they're missing if you ask me. Programming is a much better way to spend brain cells than watching TV or surfing the web. Personal computing was envisioned as a way to bring the power of the computer to the individual, a very empowering idea. Being limited to using prewritten applications is like being told that as an artist you're only allowed to paint by numbers.

So we need an easy way to start programming. It can be really hard to create software with the programming languages endorsed by the mainstream.  We have gotten away from simpler languages like BASIC, perhaps under the assumption that more complexity is better, but good computing avoids needless complexity.  Even with a language like Python there is too much to learn before you get results.  The Raspberry Pi computer, a device popular in schools, is a strong device for many purposes but it is too complicated to be a foundation for teaching computing to K-12 or as a first programming tool for most adult beginners.

Computers don't come with an easy to use programming language anymore.  This is SOOOO important. It used to be that when you turned the average computer on, the first thing it did was start BASIC. You could start programming immediately, and it was very easy to pick up. Nothing bad happened if you made a mistake, and it was fun!

People like to say that BASIC is a bad language for teaching programming.  The early versions of BASIC do have their weak points, but newer versions of BASIC are very strong for students and end users.  An entire industry of computer software came out of young people using computers that started up in BASIC programming mode.

Saturday, November 16, 2019

Have The Courage to Declutter - Best Practices Series


The things in our homes each have their own purpose, and they have their proper place.  In the course of time there is the inevitable accumulation of things, and this can become clutter which is a problem.  This is a way to think about programming.  It is not a perfect metaphor of course but I think it is useful.

Clean Your Room and Take Out the Trash

Living is a messy affair.  We do all kinds of things in our rooms.  Things like eating, opening and reading mail, getting dressed and undressed, play video games, etc.  If we don't stop and put things away and throw out the trash our rooms will unlivable.  How can we apply this when programming? First all if you find that you are commenting out code (in some languages comments are called remarks) then after a while your code will become harder to read and maintain.  Similarly if you notice you never use some part of your code any more it might be a good idea to delete that code.

Be brave and delete the old code.  If you want to keep the code then save the file in a different name so that you won't lose that version of it.  If you are using some kind of source code control (also known as version control) then you will never lose old code.

Don't Be a Hoarder

Hoarders are afraid to get rid of things and they often have many of the same kinds of things until their house fills up with so much stuff that they can't find anything and there is no room to live in their house anymore.

How to implement this idea in programming?  Each idea should only be expressed in one place. Do you notice sometimes when you're writing code that you are doing the same thing again and again so that when you change something then it needs to be changed everywhere you have that similar code?  You need to create a subroutine or a function that does that one thing in only one place, and then call that routine from all those places where the code was duplicated.  This is a kind of code refactoring.

Live In a Tiny House

Imagine your program must fit in a constrained memory.  What is the purpose of this, you might ask?  Today we have what is essentially unlimited memory in our computers.  If you just sat down and wrote code every day for the rest of your life you would never be able to fill up all that memory.  You might not be able to resist the temptation to add every single feature that you can to your software.  People who live in a tiny house often ask themselves what are the essential things, and what can be disposed of?  The more features you have, the more code you have, and the more complicated it is, and this makes it harder to extend and maintain.

    -"Everything should be as simple as possible, but not simpler." -- Albert Einstein

I hope this article is helpful to you and will give you something to incorporate into your work.

Thursday, November 07, 2019

One Role Per Subroutine/Function - Best Practices Series


If I write the following code:

  call openFile "myFilename.dat"
  call writeDataToFile
  call closeFile

I have three different subroutines that I am calling.  The first call should open a file name named myFilename.dat.  It should not do anything unrelated to opening that file.  The writeData call should only write data to the file.  The closeFile call should only close the file.  These subroutines might have some related code that makes sense for dealing with files specific to the application, or some debug logging code or the like and that would probably be fine.

But if sub openFile also opens a graphics window, or if it reinitializes a bunch of variables, or anything else that is not directly related to opening the file, that code is probably in the wrong place.  Such code should be moved to its own subroutine.

Why is this important?

One important idea in software development is called the principle of least astonishment.  As much as possible when I read code I expect that it should do precisely what it appears to be doing.  Nothing more, and nothing less.  Trying to avoid "What the ..!?" moments is an important goal in programming.  It saves time and money and makes people's lives easier.  :-)

Sometimes code is initially written very clean and in a way that is compatible with this idea of one role per subroutine or function but over time it gets polluted and things get into the code which violate this principle.  This is especially common when debugging because it's easy to write code during a heavy debugging session that you would not normally be willing to write when you're not debugging.  Then once the bug seems to be gone we are less willing to move that 'debug quality code' to the place where it belongs, or we are not sure how to do it.

Of course if you write a program such that there are no named subroutines or functions then your program is in danger of being a Big ball of mud (see https://en.wikipedia.org/wiki/Big_ball_of_mud).  If you discover that this is the state of your work, your code can be greatly improved by beginning to identify sections of code that can be moved into named subroutines or functions.

As a counterpoint this idea if you find that all the programs that you write are small one page long games or utilities that you bang out in a few minutes, then your programs might only be a small ball of mud.  In this case you might not really benefit very much from trying to break everything down into small named subroutines.

Tuesday, November 05, 2019

Naming Things Well - Best Practices Series


Some BASIC programmers come from the experience of needing to fit their programs in 4K of RAM or less, so it feels natural to give variable names single letters such as a, b, c or I, j, k. Of course most classic BASIC interpreters don't have support more for than 2 characters for variables. Some BASICs will let you call your variable 'count' but only the c and o will be recognized as the variable name.

To be fair, I've seen more than a few C programmers also choose single character variable names. Bad habits are language agnostic. ;)

In programming languages today including Liberty BASIC, you can give your variable names and other things such as subroutines and functions longer names. What's more, computers have so much memory that we can dispense with trying to save memory with short variable names. And if you're used to using line numbers I strongly encourage you to discard them in favor of named labels. Once you are used to this it will make your programming better.

Why does it matter?

Programming is an exercise in thinking and so it is really important to pick the best possible names for the parts of your programming ideas. When you or somebody else reads your code it will help to understand the code if the variables and function/sub names are chosen well.

What if you are about to go to the store to buy some milk and you told your friend "I'm g to the s to b some m." How well would you be understood?

So, when you write code ask yourself (or the coder next to you) what is the best name for this variable or routine? Later on you may even realize there is a better name and so don't hesitate to act on that impulse and update your code with the new better name.

Think of your coding as a journey to discover the truth of the code, and naming things is an important part of the discovery.

Friday, October 26, 2018

No Software Degree? Don't Let It Stop You!

I saw a an article over on freecodecamp.org where the author tells his story about getting a development job without a degree.  I think it is so inspiring when people share their stories.

I also am an un-degreed software engineer and I’ve been working in the industry for more than 30 years.

I assume that if you are ready to jump in to software development without doing a 4 year program, that you are passionate about writing code! If that describes you, read on!

Here are some tips.
  • Don’t let anyone tell you that you NEED a degree. You can go and get one, sure and if that’s what you want, great. Go do it, but it will take you years and a lot of money.
  • Read a lot. Consume as much programming literature as you can. Read conference proceedings. Read code. Read the History of Programming Languages, read archives of Dr. Dobbs Journal. 
  • Learn several programming languages in different paradigms. I’m familiar with BASIC, 6502 assembly, Forth, C, Objective-C, Java and Smalltalk. Don’t be a one trick pony.
  • Make your own software. Participate in open source projects so you can learn team programming skills. Code with friends. Create your own applications. Write some video games. Try your hand at programming tools. I wrote Liberty BASIC (a popular programming language) in my spare time and now I sell it. If you have a dossier of interesting stuff that you’ve done, it will be easier to get hired. Haven’t done anything interesting? The degree may not be enough.
  • Network like crazy. Almost every job I’ve landed I landed because of people I met at the store, at church, at conferences (that I paid to attend myself), etc.  Join some programming groups on Facebook and meet local people using meetup.com.  This can be really important.
  • Be ready to explain what you know. When you do get that interview, who will hire you if you can’t show on the whiteboard what you learned from your work. Give them a post mortem on your own code. Be ready to say what you could have done better.
Good luck and please check out my Liberty BASIC product!  http://www.libertybasic.com
See you around!

Friday, September 07, 2018

Win a free Liberty BASIC software!

We are having a referral contest until the end of October!  You can win a copy of the Liberty BASIC programming software.  All you need to do is tell five friends who you think will enjoy Liberty BASIC to email us saying they learned about Liberty BASIC from you!

    Read more about it here!

Thursday, September 06, 2018

New Liberty BASIC Projects Area

I've created a new area on the Liberty BASIC Community Forum over at Proboards here:

    http://libertybasiccom.proboards.com/board/20/community-projects

Here is copy from a post I made there about the purpose of the board:
I created this area of the board for a specific reason.  I want to create libraries free code for specific purposes and also some programs for the specific purpose of promoting Liberty BASIC.

So, for example:
  • A game framework and some examples. Side scrolling games, platform games, etc., with sprites, sound effects, background music that can use the keyboard, mouse, or joystick. etc.
  • A business application including forms, an ODBC database, printed output (tables, forms, bar charts, histograms)
  • A graphical editor - a mini CAD program or similar
  • Hardware interfacing - a monitor program for experimenting with serial devices

Suggestions welcome.  Is there any particular thing you know how to do well, or that you would like to be able to do in Liberty BASIC?  Let's make these things into actual reusable code  that people can use, and that can be included with Liberty BASIC.
I will also blog here about these projects as they progress.

Tuesday, September 04, 2018

New blog - The 6502 Shack

I'm a big fan of the 8-bit computers based on the 6502.

I've created a new blog dedicated to the MOS 6502 microprocessor and the computers that are built on it, and also a new Facebook group for it.  Read more about it here.

Wednesday, August 02, 2017

Raspberry Pi Deluxe Starter Kit Giveaway!



We are giving away a deluxe Raspberry Pi kit, and this includes all kinds of nice accessories including an electronics learning lab.  No purchase is required, so enter by Aug 31, 2017 to be included in the raffle.

Check out the video here for details about the kit!  https://youtu.be/toln-Z_z4RY

To enter the drawing, send an email to carlg@justbasic.com with the subject Raspberry Pi Contest, and we will send you a confirmation email. The winner will be announced at the end of August 2017.

Please share this information with your friends.




Monday, August 22, 2016

Book - Programming for the Absolute Beginner 2nd Edition

Programming for the Absolute Beginner 2nd Edition by Jerry Ford

I was excited to see that a second edition of Jerry Ford's programming book was recently released.  It uses Just BASIC (all examples also compatible with Liberty BASIC) to teach the fundamentals of programming.

Jump to Amazon's link

Here is the table of contents.  :-)

1 Introduction to Programming
2 Creating Programs with Just BASIC
3 Creating Graphical User Interfaces
4 Working with Variables and Arrays
5 Making Decisions with Conditional Logic
6 Using Loops to Process Data
7 Improving Program Organization with Functions and Subroutines
8 Working with Text Files
9 Working with Sound and Graphics
10 Arcade-Style Computer Game Development
11 Debugging Your Applications

Friday, August 19, 2016

Graphing Data - Setting the stage

If I have a set of data for sales, or temperature, or mosquito populations, or anything at all and I want to plot it on an X/Y graph, what are my choices for layout?

Should our graphing library figure out what the ranges are and set its own scaling?  Should it require that we tell it up front what the X and Y scales are?  Maybe it can even be designed to allow for changing the scale on the fly?

It would be great if our data plotting graphics library could handle plotting to screen, saving that to a file as a bitmap, and also plotting to a printer.

How about data sources and formats?  Should we design it to accept one or more strings of delimited values?  In the graphing example at runbasic.com it allows you to upload a CSV file with data to plot.  Maybe as an interesting example I should find a downloadable file from a scientific website and the project should be to plot a graph from that?

Feedback welcome.  More to come.

Monday, August 08, 2016

Graphing data

I get a lot of questions about how to draw graphs involving progressions of numbers, and comparisons of trends, etc.  Liberty BASIC doesn't have a built in graphing function, but it does support rich graphics drawing.

So if you're looking for a way to draw graphs of money, web traffic, rainfall, or whatever else stay tuned over the next couple of weeks.  We're going to blaze a trail!

There are at least a couple of options for solving this problem.

  • Export data out to a CSV file and use Excel to plot graphs
  • Use Liberty BASIC's graphics drawing features and draw the graphs ourselves
We are going to draw the graphs ourselves.

Impatient for the next post?  Check out this link!


Stay tuned!

Tuesday, August 02, 2016

Blast from the past - Whatever happened to PEEK and POKE?

I am reposting the following blog entry from ten years ago because it has been one of the most popular posts ever according to Blogger's statistics graph.  The link at the end of the post was broken, so I updated it.

Enjoy!


Sometimes I'm asked how to PEEK and POKE using Liberty BASIC. The short answer to this is, you can't. The long answer is more complicated.

The original home computers (like the classic Commodore 64, TRS-80, and Apple II models) were designed to be completely open to their owners. Most of the different parts of the computer like the sound, graphics, keyboard and joystick (there were no mice back then) were controlled by mapping them to different memory locations. So, the built-in commands didn't do everything you need? It was common to control the computer's equipment directly by sticking values into the memory locations that control that equipment, and reading the status back out. This was done with POKE and PEEK. This was a lot of fun, and usually useful too.

Since these early machines didn't multitask it was pretty safe to steal control of things away from the BASIC interpreter (which was a much operating system as there was). Then computers started running Windows, the Mac OS, Linux, etc. and allowed more than one program to run at a time. PEEK and POKE became problematic because if one program decided to mess with the screen for example, it might interfere with what other programs need to do their thing. Not only that, but computers today all have different kinds of hardware in them, so even if you could PEEK and POKE the exact memory locations would be different from machine to machine. So that's the bad news. :-(

The good news is that we can still have a power trip. How? Your operating system manages all the hardware for you behind operating system functions. These functions make every computer look more or less the same to the programmer. You can use these functions to do a lot of powerful things and most languages have a way to use them. For example Liberty BASIC programmers can use the CALLDLL command to make Windows API calls, which are the operating system calls of the Windows operating system. These are more complicated in general (and you can fill a whole bookshelf with information about them) than the old fashioned PEEK and POKE, but at least we aren't left without some way to pull rank on our computers. ;-)

So if you're missing the power and coolness of PEEK and POKE, why not try your hand at API calls?

Here is a useful link to get you started:

http://www.libertybasicuniversity.com/lbnews/nl108/index.htm

High DPI Issues

These days we see the arrival of very high resolution displays such as Apple's retina screens and the 4K monitors.  These are very cool, but for programmers they can be a real pain in the side.

Any application designed for a normal monitor will be tiny when viewed on a very high resolution monitor.  Windows provides a way to make things larger on screen so that the user isn't left reaching for a magnifying glass, but the effect isn't consistently applied to all the widgets and fonts, so that the user is left with an unsatisfying and unsatisfactory result.

The programming is left with the job of cleaning this up.

Check out the ongoing thread about this in our forum.

http://libertybasic.conforums.com/index.cgi?board=general&action=display&num=1456442864&start=0

Dictionary lookup - bug fixes

One of our eagle-eyed forum members noticed a bug in our dictionary code (thanks to tsh!).  In a couple of places the code that dealt with keys was not looking for the end of the key name.  This caused problems when two keys started the same.  For example let's say we have a key "name" and another key "names of next of kin".  The second key starts with "name", and the code wasn't written to avoid a false detection of this sort.

The solution to this problem is to fully qualify the key names by adding the "~value~" tag into the detection code so that when we look for "name" we are actually looking for a match on "~key~name~value~" and not "~key~name", which would give us a false positive if we looking at any key that happened to start with "name"

Here is the fixed version of our dictionary inspector.  Enjoy!

    nomainwin
    WindowWidth = 555
    WindowHeight = 438
    dim keys$(1000)
    dim info$(10, 10)
    global dictionary$, keyCount, lastKey$
    call readDictionary

    texteditor #main.value, 175, 7, 360, 365
    listbox #main.keys, keys$(), [keySelected], 5, 7, 160, 365
    menu #main, "Key", "New", [newKey], "Delete", [deleteKey]
    menu #main, "Edit"
    open "Dictionary inspector" for window as #main
    #main "trapclose [quit]"
    #main.keys "singleclickselect"
    #main.value "!autoresize";
    call loadKeys

[main.inputLoop]   'wait here for input event
    wait

[newKey]   'ask the user for a new key
    call saveValue
    prompt "Enter a name for the key."; newKey$
    if newKey$ <> "" then
        call setValueByName newKey$, ""
        call loadKeys
        #main.keys "select "; newKey$
        #main.value "!cls";
        #main.value "!setfocus";
        call collectGarbage
        call writeDictionary
        lastKey$ = newKey$
    end if
    wait

[deleteKey]  'left for later
    notice "Delete not implemented yet."
    wait

[keySelected] 'a key in the list was selected
    call saveValue
    #main.keys "selection? selectedKey$"
    selectedValue$ = getValue$(selectedKey$)
    #main.value "!contents selectedValue$";
    lastKey$ = selectedKey$
    wait

[quit] 'End the program
    call saveValue
    close #main
    end

sub saveValue   'if the value is changed, save it
    if lastKey$ <> "" then
        #main.value "!modified? modified$";
        if modified$ = "true" then
            #main.value "!contents? saveThisValue$";
            call setValueByName lastKey$, saveThisValue$
            call collectGarbage
            call writeDictionary
        end if
    end if
end sub

function getKeys$(delimiter$)
  global keyCount
  pointer = 1
  while pointer <> 0
    'get the next key
    pointer = instr(dictionary$, "~key~", pointer)
    if pointer then
      keyPointer = pointer + 5
      pointer = instr(dictionary$, "~value~", pointer)
      key$ = mid$(dictionary$, keyPointer, pointer - keyPointer)
      if instr(keyList$, "~key~" + key$ + "~value~") = 0 then
        getKeys$ = getKeys$ + key$ + delimiter$
        keyList$ = keyList$ + "~key~" + key$
        keyCount = keyCount + 1
      end if
    end if
  wend
end function

sub writeDictionary
  open "dictionary.dat" for output as #writeDict
    print #writeDict, dictionary$
  close #writeDict
end sub

sub readDictionary
  if fileExists(DefaultDir$, "dictionary.dat") then
      open "dictionary.dat" for input as #readDict
    length = lof(#readDict)
    dictionary$ = input$(#readDict, length)
    close #readDict
  end if
end sub

sub collectGarbage
  pointer = 1
  while pointer > 0
    'get the next key
    pointer = instr(dictionary$, "~key~", pointer)
    if pointer then
      keyPointer = pointer + 5
      pointer = instr(dictionary$, "~value~", pointer)
      key$ = mid$(dictionary$, keyPointer, pointer - keyPointer)
      if instr(keyList$, "~key~" + key$ + "~value~") = 0 then
        value$ = getValue$(key$)
        newDictionary$ = "~key~" + key$ + "~value~" + value$ + newDictionary$
        keyList$ = keyList$ + "~key~" + key$ + "~value~"
      end if
    end if
  wend
  dictionary$ = newDictionary$
end sub

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

function getValue$(key$)
  getValue$ = chr$(0)
  keyPosition = instr(dictionary$, "~key~"+key$+"~value~")
  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

sub loadKeys
    keyList$ = getKeys$("~")
    redim keys$(keyCount)
    for item = 1 to keyCount
      keys$(item-1) = word$(keyList$, item, "~")
    next item
    #main.keys "reload"
end sub

function fileExists(path$, filename$) ' Does file exist?
    files path$, filename$, info$(
    fileExists = val(info$(0, 0)) > 0
end function


Wednesday, July 20, 2016

A dictionary lookup mini application

Here is a simple demo application for our keyed lookup library in development.  It opens a window with keys on the left, and a text editor on the right.  You can add new keys and edit the values for those keys by changing text on the right.  The values are saved to the file dictionary.dat.

We will enhance this code for a couple more blog entries before we move on to some other project.  :-)

Enjoy!

    nomainwin
    WindowWidth = 555
    WindowHeight = 438

    dim keys$(1000)
    dim info$(10, 10)
    global dictionary$, keyCount, lastKey$
    call readDictionary


    texteditor #main.value, 175, 7, 360, 365
    listbox #main.keys, keys$(), [keySelected], 5, 7, 160, 365

    menu #main, "Key", "New", [newKey], "Delete", [deleteKey]
    menu #main, "Edit"

    open "Dictionary inspector" for window as #main
    #main "trapclose [quit]"
    #main.keys "singleclickselect"
    #main.value "!autoresize";
    call loadKeys


[main.inputLoop]   'wait here for input event
    wait


[newKey]   'ask the user for a new key
    call saveValue
    prompt "Enter a name for the key."; newKey$
    if newKey$ <> "" then
        call setValueByName newKey$, ""
        call loadKeys
        #main.keys "select "; newKey$
        #main.value "!cls";
        #main.value "!setfocus";
        call writeDictionary
        lastKey$ = newKey$
    end if
    wait


[deleteKey]  'left for later
    notice "Delete not implemented yet."
    wait


[keySelected] 'a key in the list was selected
    call saveValue
    #main.keys "selection? selectedKey$"
    selectedValue$ = getValue$(selectedKey$)
    #main.value "!contents selectedValue$";
    lastKey$ = selectedKey$
    wait


[quit] 'End the program
    call saveValue
    close #main
    end


sub saveValue   'if the value is changed, save it
    if lastKey$ <> "" then
        #main.value "!modified? modified$";
        if modified$ = "true" then
            #main.value "!contents? saveThisValue$";
            call setValueByName lastKey$, saveThisValue$
            call collectGarbage
            call writeDictionary
        end if
    end if
end sub


function getKeys$(delimiter$)
  global keyCount
  pointer = 1
  while pointer > 0
    'get the next key
    pointer = instr(dictionary$, "~key~", pointer)
    if pointer then
      keyPointer = pointer + 5
      pointer = instr(dictionary$, "~value~", pointer)
      key$ = mid$(dictionary$, keyPointer, pointer - keyPointer)
      if instr(keyList$, "~key~" + key$) = 0 then
        getKeys$ = getKeys$ + key$ + delimiter$
        keyList$ = keyList$ + "~key~" + key$
        keyCount = keyCount + 1
      end if
    end if
  wend
end function


sub writeDictionary
  open "dictionary.dat" for output as #writeDict
    print #writeDict, dictionary$
  close #writeDict
end sub


sub readDictionary
  if fileExists(DefaultDir$, "dictionary.dat") then
      open "dictionary.dat" for input as #readDict
    length = lof(#readDict)
    dictionary$ = input$(#readDict, length)
    close #readDict
  end if
end sub


sub collectGarbage
  pointer = 1
  while pointer > 0
    'get the next key
    pointer = instr(dictionary$, "~key~", pointer)
    if pointer then
      keyPointer = pointer + 5
      pointer = instr(dictionary$, "~value~", pointer)
      key$ = mid$(dictionary$, keyPointer, pointer - keyPointer)
      if instr(keyList$, key$) = 0 then
        value$ = getValue$(key$)
        newDictionary$ = "~key~" + key$ + "~value~" + value$ + newDictionary$
        keyList$ = keyList$ + key$
      end if
    end if
  wend
  dictionary$ = newDictionary$
end sub


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


sub loadKeys
    keyList$ = getKeys$("~")
    redim keys$(keyCount)
    for item = 1 to keyCount
      keys$(item-1) = word$(keyList$, item, "~")
    next item
    #main.keys "reload"
end sub


function fileExists(path$, filename$) ' Does file exist?
    files path$, filename$, info$(
    fileExists = val(info$(0, 0)) > 0
end function


Friday, July 15, 2016

Dictionary lookup - getting the keys

When you have an array you can simply loop through the contents to examine what's there, but when you have a dictionary you need to have the list of keys so that you can look up each value in the dictionary.  For that, we need a getKeys$() function.  The following function returns a single string with the keys from our global dictionary$ variable, each separated by a delimiter that we can specify.

function getKeys$(delimiter$)
  pointer = 1
  while pointer > 0
    'get the next key
    pointer = instr(dictionary$, "~key~", pointer)
    if pointer then
      keyPointer = pointer + 5
      pointer = instr(dictionary$, "~value~", pointer)
      key$ = mid$(dictionary$, keyPointer, pointer - keyPointer)
      if instr(keyList$, "~key~" + key$) = 0 then
        getKeys$ = getKeys$ + key$ + delimiter$
        keyList$ = keyList$ + "~key~" + key$
      end if
    end if
  wend
end function

Once have this string we can tease out each key.  Here is an quick example that shows how to do this.  The variable allKeys$ will hold all the keys, each separated by "~".  Then we use the word$() function to get each key.

global dictionary$

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

allKeys$ = getKeys$("~")
print allKeys$

key = 1
while word$(allKeys$, key, "~") <> ""
  key$ = word$(allKeys$, key, "~")
  print "Key number "; key; " is "; key$
  print "    value = "; getValue$(key$)
  key = key + 1
wend


Here is what the resulting output looks.

phone~last~first~
Key number 1 is phone
    value = 555-555-1234
Key number 2 is last
    value = Thumb
Key number 3 is first
    value = Tom


Notice that the keys do not come out in the order that we put them in.  This is typical in dictionary style lookup mechanisms.  The ordering of keys is not guaranteed.

Wednesday, July 13, 2016

Dictionary lookup - saving to disk

One advantage of using our single string dictionary lookup technique is that saving to and reading from a disk file is amazingly simple.  Just open the file and write the string.

sub writeDictionary
  open "dictionary.dat" for output as #writeDict
    print #writeDict, dictionary$
  close #writeDict
end sub

Reading on the other hand requires a slightly more sophisticated technique.  For example, if any of the keys or values have return characters in them then we want to make sure we read the whole file all the way to the end.  For this we will use the input$() function.

sub readDictionary
  open "dictionary.dat" for input as #readDict
  length = lof(#readDict)
  dictionary$ = input$(#readDict, length)
  close #readDict
end sub

The ability to preserve return characters is useful more for the values than for the keys, which for most applications will probably just be short one or two word names.

Tuesday, July 12, 2016

Liberty BASIC on the Rosetta Code site

One of the members of our community forum posted about some graphics code that he wrote on the Rosetta Code site.

Here is his post.
http://libertybasic.conforums.com/index.cgi?board=LB3&action=display&num=1468265910

I'm glad he posted about it just as a reminder to what a great resource the Rosetta Code site is.  There are many, many code samples there to learn from.  Check out this link.

http://rosettacode.org/wiki/Category:Liberty_BASIC

And, if you'd like to get in on the action there are many Rosetta Code examples which have not yet been implemented in Liberty BASIC.  For a list try this link:

http://rosettacode.org/wiki/Reports:Tasks_not_implemented_in_Liberty_BASIC

These are implemented in other language on the Rosetta Code site so if you'd like to try your hand at writing one or more in Liberty BASIC there are examples to glean inspiration from.

Monday, July 11, 2016

Dictionary lookup - Garbage collection

If we need to use our keyed dictionary lookup functions for a purpose where we will change the values for any or all keys the string we save in dictionary$ will get larger each time we set a key and value.  This is because the setValueByName subroutine sets a key and value by adding onto the front of the dictionary$ variable but it does not remove any preexisting value for that key.  So if for example I set a key of "storeFolder" and a value of "c:\myStoreFolder" and then later I change the value to "c:\myOtherFolder" I will have two different entries for the key "storeFolder".  Only the latest value will be returned by the getValue$() function.

So, how do we fix this?  We implement a garbage collector.  We can create a subroutine that makes a copy of dictionary$ that only has the latest value for each key.

Here is a first stab at a garbage collector subroutine.

sub collectGarbage
  pointer = 1
  while pointer > 0
    'get the next key
    pointer = instr(dictionary$, "~key~", pointer)
    if pointer then
      keyPointer = pointer + 5
      pointer = instr(dictionary$, "~value~", pointer)
      key$ = mid$(dictionary$, keyPointer, pointer - keyPointer)
      if instr(keyList$, key$) = 0 then
        value$ = getValue$(key$)
        newDictionary$ = "~key~" + key$ + "~value~" + value$ + newDictionary$
        keyList$ = keyList$ + key$
      end if
    end if
  wend
  dictionary$ = newDictionary$
end sub

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

Friday, July 01, 2016

Leveraging the lesson browser

Liberty BASIC has a cool feature that many people don't take advantage of.  It's called the lesson browser.  It allows you to create a collection of different programs in a single file arranged in an outline fashion along with comments for each program.

This is great for:
  1. Creating lessons (yeah)
  2. Sharing ideas with others
  3. Grouping related programs in a project
  4. Tracking the evolution of a program (a kind of versioning)
Here is a screenshot of the lesson browser in action.  It is used to provide a tutorial and also example of new features of Liberty BASIC, but it can be used by users to create any collection of programs along with documentation.