Using Command Line Arguments - Updated

In this blog, Vijaye Raji wrote about arguments in Small Basic v0.1 (to v0.5).  But from v0.6, the interface has been changed.  So I will rewrite his article for current version of Small Basic.


The Program object in the standard library allows you to work with Command Line Arguments from inside a Small Basic program.  The Program object includes a ArgumentCount property that gives the total number of arguments passed to the program, and a GetArgument(index)  operation that allows you to access each of these arguments using their index.

The following program prints out all the prime numbers less than the number passed at the command line.

If ``(``Program``.`` ArgumentCount `` = ``1`` ) ``Then

  `` maxNumber `` = ``Program``.``GetArgument``(``1``)

  

  `` If ``(`` maxNumber `` < ``2`` ) ``Then

    ``TextWindow``.``WriteLine``(``"No Primes less than 2."``)

  ``EndIf

  

  `` For `` i `` = `` 2 `` To ``maxNumber

    ``CheckPrime``(``)

    `` If ``(`` isPrime `` = ``"True"`` ) ``Then

      ``TextWindow``.``WriteLine``(``i``)

    ``EndIf

  ``EndFor

Else

  ``TextWindow``.``WriteLine``(``"Usage: prime count"``)

EndIf

 

Sub ``CheckPrime

  `` isPrime `` = ``"True"

  `` For `` j `` = `` 2 `` To ``Math``.``SquareRoot``(``i``)

    `` If ``(``Math``.``Remainder``(``i`` , ``j`` ) `` = ``0`` ) ``Then

      `` isPrime `` = ``"False"

    ``EndIf

  ``EndFor

EndSub

In this program, Small Basic tries to coerce any passed argument as a number.  If you try passing a non-number, the program ends up with “0” and will print out “No Primes less than 2.”

For example:

 C:\Users\Nonki\Documents>prime 5
 2
3
5
Press any key to continue...

See Also