Yabasic


Table of Contents

Chapter 1. Introduction

About this document

This document describes yabasic. You will find information about the yabasic interpreter (the program yabasic under Unix or yabasic.exe under Windows) as well as the language (which is, of course, a sort of basic) itself.

This document applies to version 2.91 of yabasic

However, it does not contain the latest news about yabasic or a FAQ. As such information tends to change rapidly, it is presented online only at www.yabasic.de.

Although basic has its reputation as a language for beginning programmers, this is not an introduction to programming at large. Rather this text assumes, that the reader has some (moderate) experience with writing and starting computer programs.

About yabasic

yabasic is a traditional basic interpreter. It understands most of the typical basic-constructs, like goto, gosub, line numbers, read, data or string-variables with a trailing '$'. But on the other hand, yabasic implements some more advanced programming-constructs like subroutines or libraries (but not objects). yabasic works much the same under Unix and Windows.

yabasic puts emphasis on giving results quickly and easily; therefore simple commands are provided to open a graphic window, print the graphics or control the console screen and get keyboard or mouse information. The example below opens a window, draws a circle and prints the graphic:

open window 100,100
open printer
circle 50,50,40
text 10,50,"Press any key to get a printout"
clear screen
inkey$
close printer
close window

This example has fewer lines, than it would have in many other programming languages. In the end however yabasic lacks behind more advanced and modern programming languages like C++ or Java. But as far as it goes it tends to give you results more quickly and easily.

Chapter 2. The yabasic-program under Windows

Starting yabasic

Once, yabasic has been set up correctly, there are three ways to start it:

  1. Right click on your desktop: The desktop menu appears with a submenu named new. From this submenu choose yabasic. This will create a new icon on your desktop. If you right click on this icon, its context menu will appear; choose Execute to execute the program.

  2. As a variant of the way described above, you may simply create a file with the ending .yab (e.g. with your favorite editor). Everything else then works as described above.

  3. From the start-menu: Choose yabasic from your start-menu. A console-window will open and you will be asked to type in your program. Once you are finished, you need to type return twice, and yabasic will parse and execute your program.

    Note

    This is not the preferred way of starting yabasic ! Simply because the program, that you have typed, can not be saved and will be lost inevitably ! There is no such thing as a save-command and therefore no way to conserve the program, that you have typed. This mode is only intended for quick hacks, and short programs.

Options

Under Windows yabasic will mostly be invoked by double-clicking on an appropriate icon; this way you do not have a chance to specify any of the command line options below. However, advanced users may change the librarypath in the registry, which has the same effect as specifying it as an option on the command line.

See the chapter on options for a complete list of all options, either on Unix or Windows.

The context Menu

Like every other icon under Windows, the icon of every yabasic-program has a context menu offering the most frequent operations, that may be applied to a yabasic-program.

Execute

This will invoke yabasic to execute your program. The same happens, if you double click on the icon.

Edit

notepad will be invoked, allowing you to edit your program.

View docu

This will present the embedded documentation of your program. Embedded documentation is created with the special comment doc.

Chapter 3. The yabasic-program under Unix

Starting yabasic

If your system administrator (vulgo root) has installed yabasic correctly, there are three ways to start it:

  1. You may use your favorite editor (emacs, vi ?) to put your program into a file (e.g. foo). Make sure that the very first line starts with the characters '#!' followed by the full pathname of yabasic (e.g. '#!/usr/local/bin/yabasic'). This she-bang-line ensures, that your Unix will invoke yabasic to execute your program (see also the entry for the hash-character). Moreover, you will need to change the permissions of your yabasic-program foo, e.g. chmod u+x foo. After that you may invoke yabasic to invoke your program by simply typing foo (without even mentioning yabasic). However, if your PATH-variable does not contain a single dot ('.') you will have to type the full pathname of your program: e.g. /home/ihm/foo (or at least ./foo).

  2. Save your program into a file (e.g. foo) and type yabasic foo. This assumes, that the directory, where yabasic resides, is contained within your PATH-variable.

  3. Finally your may simply type yabasic (maybe it will be necessary to include its full pathname). This will make yabasic come up and you will be asked to type in your program. Once you are finished, you need to type return twice, and yabasic will parse and execute your program.

    Note

    This is not the preferred way of starting yabasic ! Simply because the program, that you have typed, can not be saved and will be lost inevitably ! There is no such thing as a save-command and therefore no way to conserve the program, that you have typed. This mode is only intended for quick hacks, and short programs, i.e. for using yabasic as some sort of fancy desktop calculator.

Options

yabasic accepts a number of options on the command line.

See chapter on options for a complete list of all options, either on Unix or Windows.

Setting defaults

If you want to set some options once for all, you may put them into your X-Windows resource file. This is usually the file .Xresources or some such within your home directory (type man X for details).

Here is a sample section, which may appear within this file:

yabasic*foreground: blue
yabasic*background: gold
yabasic*geometry: +10+10
yabasic*font: 9x15

This will set the foreground color of the graphic-window to blue and the background color to gold. The window will appear at position 10,10 and the text font will be 9x15.

Chapter 4. Command line options of yabasic

Here are the options, that yabasic accepts on the command line (both under Unix and Windows).

All the options below may be abbreviated (and one hyphen may be dropped), as long as the abbreviation does not become ambiguous. For example, you may write -e instead of --execute.

--help or -?

Prints a short help message, which itself describes two further help-options.

--version

Prints the version of yabasic.

--infolevel INFOLEVEL

Change the infolevel of yabasic, where INFOLEVEL can be one of debug, note, warning, error, fatal and bison (the default is warning). This option changes the amount of debugging-information yabasic produces. However, normally only the author of yabasic would want to change this.

--execute A-PROGRAM-AS-A-SINGLE-STRING

With this option you may specify some yabasic-code to be executed right away. This is useful for very short programs, which you do not want to save to a file. If this option is given, yabasic will not read any code from a file. E.g.

yabasic -e 'for a=1 to 10:print a*a:next a'

prints the square numbers from 1 to 10.

--bind NAME-OF-STANDALONE-PROGRAM

Create a standalone program (whose name is specified by NAME-OF-STANDALONE-PROGRAM) from the yabasic-program, that is specified on the command line. Please note, that the file NAME-OF-STANDALONE-PROGRAM will be overwritten; therefore you should not give the name of your yabasic-program here. See the section about creating a standalone-program for a complete example.

--geometry +X-POSITION+Y-POSITION

Sets the position of the graphic window, that is opened by open window (the size of this window, of course, is specified within the open window-command). An example would be -geometry +20+10, which would place the graphic window 10 pixels below the upper border and 20 pixels right of the left border of the screen. This value cannot be changed, once yabasic has been started.

-fg FOREGROUND-COLOR or --foreground FOREGROUND-COLOR

Unix only. Define the foreground color for the graphics-window (that will be opened with open window). The usual X11 color names, like red, green, … are accepted. This value cannot be changed, once yabasic has been started.

-bg BACKGROUND-COLOR or --background BACKGROUND-COLOR

Unix only. Define the background color for the graphics-window. The usual X11 color names are accepted. This value cannot be changed, once yabasic has been started.

--display X11-DISPLAY-SPECIFICATION

Unix only. Specify the display, where the graphics window of yabasic should appear. Normally this value will be already present within the environment variable DISPLAY.

--font NAME-OF-FONT

Under Unix. Name of the font, which will be used for text within the graphics window.

--font NAME-OF-FONT

Under Windows. Name of the font, which will be used for graphic-text; can be any of decorative, dontcare, modern, roman, script, swiss. You may append a fontsize (measured in pixels) to any of those fontnames; for example -font swiss30 chooses a swiss-type font with a size of 30 pixels.

--docu NAME-OF-A-PROGRAM

Print the embedded documentation of the named program. The embedded documentation of a program consists of all the comments within the program, which start with the special keyword doc. This documentation can also be seen by choosing the corresponding entry from the context-menu of any yabasic-program.

--check

Check for possible compatibility problems within your yabasic-program. E.g. this option reports, if you are using a function, that has recently changed.

--librarypath DIRECTORY-WITH-LIBRARIES

Change the directory, wherein libraries will be searched and imported (with the import-command). See also import for more information about the way, libraries are searched.

--

Do not try to parse any further options; rather pass the subsequent words from the commandline to yabasic.

Chapter 5. All commands and functions of yabasic listed by topic

Numbers with base 2 or 16

In addition to the usual decimal notation (e.g. 1234), yabasic also supports numeric literals with base 2 or 16; examples are 0b10011 (the number 19, written with base 2) or 0x34AF (the number 13487, written with base 16) respectively. Please note that these numbers (apart from the way you write them into your program) are no different from ordinary numbers and can be used in any place, where a normal number with base 10 would fit. E.g. you may compute the sine sin(0b110); so the base 2 (or 16) is just a different way of representation.

See bin$, hex$ or dec for related functions.

Number processing and conversion

abs()
returns the absolute value of its numeric argument
acos()
returns the arcus cosine of its numeric argument
and()
the bitwise arithmetic and
asin()
returns the arcus sine of its numeric argument
atan()
returns the arctangent of its numeric argument
bin$()
converts a number into a sequence of binary digits
cos()
return the cosine of its single argument
dec()
convert a base 2 or base 16 number into decimal form
eor()
compute the bitwise exclusive or of its two arguments
euler
another name for the constant 2.71828182864
exp()
compute the exponential function of its single argument
frac()
return the fractional part of its numeric argument
int()
return the integer part of its single numeric argument
ceil()
compute the ceiling for its (float) argument
floor()
compute the floor for its (float) argument
round()
round its argument to the nearest integer
log()
compute the natural logarithm
max()
return the larger of its two arguments
min()
return the smaller of its two arguments
mod
compute the remainder of a division
bitnot()
the bitwise arithmetic not
or()
arithmetic or, used for bit-operations
pi
a constant with the value 3.14159
ran()
return a random number
shl()
shift its argument bitwise to the left
shr()
shift its argument bitwise to the right
sig()
return the sign of its argument
sin()
return the sine of its single argument
sqr()
compute the square of its argument
sqrt()
compute the square root of its argument
tan()
return the tangent of its argument
xor()
compute the exclusive or
** or ^
raise its first argument to the power of its second
< <= > >= = == <> !=
Compare numbers or strings

Conditions and control structures

and
logical and, used in conditions
break
breaks out of one or more loops or switch statements
case
mark the different cases within a switch-statement
continue
start the next iteration of a for-, do-, repeat- or while-loop
default
mark the default-branch within a switch-statement
do
start a (conditionless) do-loop
else
mark an alternative within an if-statement
elsif
starts an alternate condition within an if-statement
end
terminate your program
endif
ends an if-statement
false
a constant with the value of 0
fi
another name for endif
for
starts a for-loop
gosub
continue execution at another point within your program (and return later)
goto
continue execution at another point within your program (and never come back)
if
evaluate a condition and execute statements or not, depending on the result
label
mark a specific location within your program for goto, gosub or restore
loop
marks the end of an infinite loop
next
mark the end of a for loop
not
negate a logical expression; can be written as !
on gosub
jump to one of multiple gosub-targets
on goto
jump to one of many goto-targets
on interrupt
change reaction on keyboard interrupts
logical or
logical or, used in conditions
bitwise or
arithmetic or, used for bit-operations
pause
pause, sleep, wait for the specified number of seconds
repeat
start a repeat-loop
return
return from a subroutine or a gosub
sleep
pause, sleep, wait for the specified number of seconds
step
specifies the increment step in a for-loop
switch
select one of many alternatives depending on a value
then
tell the long from the short form of the if-statement
true
a constant with the value of 1
until
end a repeat-loop
wait
pause, sleep, wait for the specified number of seconds
wend
end a while-loop
while
start a while-loop
:
separate commands from each other

Data keeping and processing

arraydim()
returns the dimension of the array, which is passed as an array reference
arraysize()
returns the size of a dimension of an array
data
introduces a list of data-items
dim
create an array prior to its first use
read
read data from data-statements
redim
create an array prior to its first use. A synonym for dim
restore
reposition the data-pointer

String processing

asc()
accepts a string and returns the position of its first character within the ascii charset
chomp$()
remove a single trailing newline from its string-argument; if the string does not end in a newline, the string is returned unchanged
chr$()
accepts a number and returns the character at this position within the ascii charset
glob()
check if a string matches a simple pattern
hex$()
convert a number into hexadecimal
instr()
searches its second argument within the first; returns its position if found
rinstr()
find the rightmost occurrence of one string within the other
left$()
return (or change) left end of a string
len()
return the length of a string
lower$()
convert a string to lower case
ltrim$()
trim spaces at the left end of a string
mid$()
return (or change) characters from within a string
right$()
return (or change) the right end of a string
split()
split a string into many strings
str$()
convert a number into a string
string$()
create a new string by repeating the given one a certain number of times
token()
split a string into multiple strings
trim$()
remove leading and trailing spaces from its argument
rtrim$()
trim spaces at the right end of a string
upper$()
convert a string to upper case
val()
converts a string to a number

File operations and printing

at()
can be used in the commands print and input to place the output at a specified position
beep
ring the bell within your computer; a synonym for bell
bell
ring the bell within your computer (just as beep)
clear screen
erases the text window
close
close a file, which has been opened before
close printer
stops printing of graphics
print color
print or input-prompt with color
print colour
see print color
eof
check, if an open file contains data
getscreen$()
returns a string representing a rectangular section of the text terminal
inkey$
wait, until a key is pressed
input
read input from user or file and assign it to a variable
line input
read in a whole line of text and assign it to a variable
open
open a file
open printer
open printer for printing graphics
print
Write to terminal or file
putscreen
draw a rectangle of characters into the text terminal
reverse
print reverse (background and foreground colors exchanged)
screen
as clear screen clears the text window
seek()
change the position within an open file
tell
get the current position within an open file
using
Specify the format for printing a number
#
either a comment or a marker for a file-number
at
can be used in the commands print and input to place the output at a specified position
@
synonymous to at
;
suppress the implicit newline after a print-statement

Subroutines

end sub
ends a subroutine definition
local
mark a variable as local to a subroutine
numparams
return the number of parameters, that have been passed to a subroutine
return
return from a subroutine or a gosub
static
preserves the value of a variable between calls to a subroutine
sub
declare a user defined subroutine

Libraries

export
mark a function as globally visible
import
import a library

Invoking other program from within yabasic

system()
hand the name of an external command over to your operating system and return its exitcode
system$()
hand the name of an external command over to your operating system and return its output

Adding new code to a running program

See also adding code during execution.

compile
compile a string with yabasic-code on the fly
eval()
compile and execute a single numeric expression
eval$()
compile and execute a single string-expression
execute()
execute a user defined subroutine, which must return a number
execute$()
execute a user defined subroutine, which must return a string

Commands and functions related with time

date$
returns a string with various components of the current date
pause
pause, sleep, wait for the specified number of seconds
sleep
pause, sleep, wait for the specified number of seconds
time$
return a string containing the current time

Other commands

bind()
binds a yabasic-program and the yabasic-interpreter together into a standalone program
doc
special comment, which might be retrieved by the program itself
docu$
special array, containing the contents of all docu-statement within the program
error
raise an error and terminate your program
exit
terminate your program
peek
retrieve various internal informations (numeric)
peek$
retrieve various internal informations (strings)
poke
change selected internals of yabasic
rem
start a comment
to
this keyword appears as part of other statements
wait
pause, sleep, wait for the specified number of seconds
//
starts a comment
:
separate commands from each other

Graphics and printing

backcolor
change color for background of graphic window
box
draw a rectangle. A synonym for rectangle
circle
draws a circle in the graphic-window
clear
erase circles, rectangles or triangles
clear window
clear the graphic window and begin a new page, if printing is under way
close curve
close a curve, that has been drawn by the line-command
close window
close the graphics-window
color
change color for any subsequent drawing-command
dot
draw a dot in the graphic-window
fill
draw a filled circles, rectangles or triangles
getbit$()
return a string representing the bit pattern of a rectangle within the graphic window
line
draw a line
mouseb
extract the state of the mousebuttons from a string returned by inkey$
mousemod
return the state of the modifier keys during a mouseclick
mousex
return the x-position of a mouseclick
mousey
return the y-position of a mouseclick
new curve
start a new curve, that will be drawn with the line-command
open window
open a graphic window
putbit
draw a rectangle of pixels encoded within a string into the graphics window
rectangle
draw a rectangle
triangle
draw a triangle
text
write text into your graphic-window
window origin
move the origin of a window

The foreign function interface

foreign_buffer_alloc$()
Create a new buffer for use in a foreign function call
foreign_buffer_dump$()
return the content of a buffer as a hex-encoded string
foreign_buffer_free()
free a foreign buffer
foreign_buffer_get()
extract a number from a foreign buffer
foreign_buffer_get$()
extract a string from a foreign buffer
foreign_buffer_get_buffer$()
take a buffer and construct a handle to a second buffer from its content
foreign_buffer_set
store a given value within a buffer
foreign_buffer_set_buffer
store a pointer to one buffer within another buffer
foreign_buffer_size()
return the size of the foreign buffer
foreign_function_call()
call a function (returning a number) from a non-yabasic library or dll
foreign_function_call$()
call a function (returning a string or a buffer) from a non-yabasic library or dll
foreign_function_size()
Abbreviations for foreign_buffer_ and foreign_function_
frnbf_ and frnfn_
return the size of one of the types available for foreign function calls

Chapter 6. Some features and general concepts of yabasic

This chapter presents some general concepts and terms, which deserve a description on their own, but are not associated with a single command or function in yabasic. Most of these topics do not lend themselves to be read alone, rather they might be read (or skimmed) as background material if an entry from the alphabetical list of commands refers to them.

Logical shortcuts

Logical shortcuts are no special language construct and there is no keyword for them; they are just a way to evaluate logical expressions. Logical expressions (i.e. a series of conditions or comparisons joined by and or or) are only evaluated until the final result of the expression can be determined. An example:

if (a<>0 and b/a>2) print "b is at least twice as big as a"

The logical expression a<>0 and b/a>2 consists of two comparisons, both of which must be true, if the print statement should be executed. Now, if the first comparison (a<>0) is false, the whole logical expression can never be true and the second comparison (b/a>2) need not be evaluated.

This is exactly, how yabasic behaves: The evaluation of a composed logical expressions is terminated immediately, as soon as the final result can be deduced from the already evaluated parts.

In practice, this has the following consequences:

  • If two or more comparisons are joined with and and one comparison results in false, the logical expression is evaluated no further and the overall result is false.

  • If two or more comparisons are joined with or and one comparison results in true, the logical expression is evaluated no further and the result is true.

Nice, but whats this good for ?, I hear you say. Well, just have another look at the example, especially the second comparison (b/a>2); dividing b by a is potentially hazardous: If a equals zero, the expression will cause an error and your program will terminate. To avoid this, the first part of the comparison (a<>0) checks, if the second one can be evaluated without risk. This pre-checking is the most common usage and primary motivation for logical shortcuts (and the reason why most programming languages implement them).

Conditions and expressions

Well, bottomline there is no difference or distinction between conditions and expressions, at least as yabasic is concerned. So you may assign the result of comparisons to variables or use an arithmetic expression or a simple variable within a condition (e.g. within an if-statement). So the constructs shown in the example below are all totally valid:

input "Please enter a number between 1 and 10: " a

rem   Assigning the result of a comparison to a variable
okay=a>=1 and a<=10

rem   Use a variable within an if-statement
if (not okay) error "Wrong, wrong !"

So conditions and expressions are really the same thing (at least as long as yabasic is concerned). Therefore the terms conditions and expression can really be used interchangeably, at least in theory. In reality the term condition is used in connection with if or while whereas the term expression tends to be used more often within arithmetic context.

Comparing strings or numbers

Yabasic, of course, allows to compare strings with strings and numbers with numbers; <, <=, > and >= compare their left-hand side to their right-hand side as usual; nothing new here and examples can be found throughout this manual.

More interesting, the equality-operator (for numbers as well as for strings) can be written in two different ways: either as = (traditional) or as == (more modern). The second form has the advantage of beeing visually distinct from the assignment-operator, which is the single =. One may argue therefore, that using == results in code, that is easier to understand and read; This manual however sticks to tradition and mostly uses the single = for equality-check.

Finally, inequality can be checked with <> or !=; both operators behave identically and so it is only a matter of taste, which one to use.

References on arrays

References on arrays are the only way to refer to an array as a whole and to pass it to subroutines or functions like arraydim or arraysize.

While (for example) a(2) designates the second element of the array a, a() (with empty braces) refers to the array a itself. a() is called an array reference. A nice example is the bultin function split, that accepts an array-reference and modifies the content of this array.

You may also pass to and use array reference within your own subroutines; these subroutines will then be able to modify the array you have passed in often this is intended.

Passing an array reference does not create a copy of the array; this has some interesting consequences:

  • Speed and space: Creating a copy of an array would be a time and memory consuming operation; passing just a reference is cheap and fast.

  • Returning many values: A subroutine, that wants to give back more than one value, may require an array reference among its arguments and then store its many return values within this array. This is the only way to return more than one value from a subroutine.

An example

The following program creates two subroutines (print_words and upcase_words), that operate on an array of words (words$() below):

dim words$(4)
for i=1 to 4
  read words$(i)
next i

print_words(words$())
upcase_words(words$())
print_words(words$())

sub print_words(w$())
  local i
  for i=1 to arraysize(w$(),1)
    print w$(i)," ";
  next i
  print    
end sub

sub upcase_words(w$())
  local i
  for i=1 to arraysize(w$(),1)
    w$(i) = upper$(w$(i))
  next i
end sub

data "case","does","not","matter"
            

If you run this program, you will get this output:

	      
case does not matter
CASE DOES NOT MATTER		
	      
	    

Specifying Filenames under Windows

As you probably know, windows uses the character '\' to separate the directories within a pathname; an example would be C:\programs\yabasic\yabasic.exe (a possible location of the yabasic executable). However, the very same character '\' is used to construct escape sequences, not only in yabasic but in most other programming languages.

Therefore e.g. the string "C:\t.dat" does not specify the file t.dat within the directory C:; this is because the sequence '\t' is translated into the tab-character (and thus giving a rather unusal filename containing a tab). To specify this filename, you need to use the string "C:\\t.dat" (note the double slash '\\').

Escape-sequences

Escape-sequences are the preferred way of specifying 'special' characters. They are introduced by the '\'-character and followed by one of a few regular letters, e.g. '\n' or '\r' (see the table below).

Escape-sequences may occur within any string at any position; they are replaced at parsetime (opposed to runtime), i.e. as soon as yabasic discovers the string, with their corresponding special character. As a consequence of this len("\a") returns 1, because yabasic replaces "\a" with the matching special character just before the program executes.

Table 6.1. Escape sequences
Escape SequenceMatching special character
\nnewline
\ttabulator
\vvertical tabulator
\bbackspace
\rcarriage return
\fformfeed
\aalert (i.e. a beeping sound)
\\backslash
\'single quote
\"double quote
\xHEXchr$(HEX) (see below)

Note, that an escape sequences of the form \xHEX allows one to encode arbitrary characters as long as you know their position (as a hex-number) within the ascii-charset: For example \x012 is transformed into the character chr$(18) (or chr$(dec("12",16)). Note that \x requires a hexa-decimal number (and the hexadecimal string "12" corresponds to the decimal number 18).

Subroutines: Sharing code within one program

Purpose

Nobody wants to repeat oneself and therefore yabasic allows to collect arbitrary code into subroutines, so that you may call it from multiple locations within you program. To this end, two conditions must be fulfilled:

  1. The subroutine neeeds to know details about what to do; that's why subroutines have parameters. E.g. in the overly simple subroutine sub add(a,b) (see the example below) the parameters would be a and b, specifying, which numbers to add.

    Remark: In certain cases a subroutine may want to find out, how many parameters it has been called with, by querying the special variable numparams.

  2. The subroutine needs to run without messing up the state of the program, at the point where it has been called. That's why many subroutines use local variables, which are different and isolated from all other variables in your program, even if they happen to have the same name. parameters (as described above) are, in addition to their primary function, also local variables.

    Remark: If a subroutine wants to remember some information between invocations, it may declare some of its variables as static instead of local function

To see these concepts explained in more detail (complete with examples), follow the links at the end of this section.

Remark: You may notice, that other programming language may use other terms than subroutine for the same concept: function or procedure have been popular for pieces of code, that either return a value or not, and in other languages def is used to name both. And the term method is used in object-oriented languages. However yabasic is not object oriented, and regardless, if a piece of code produces a value or not, it can be encapsulated in a subroutine, so yabasic uses the function sub throughout.

A simple example

The short program below does nothing more than to add two numbers; for this purpose, it even defines a subroutine. This admittedly is more overhead, than you would normally take.

print "About to add two numbers."
input "Please enter first number: " x
input "Please enter second number: " y
print "Their sum is: ", add(x,y)

sub add(a,b)
  return a+b
end sub
	

If you run it, you would see:

	  
About to add two numbers.
Please enter first number: 2
Please enter second number: 3
Their sum is: 5
	
	

Again, see the link at the end of this section for more explanations and examples (e.g. on local or static, which have only been mentioned but not shown at work so far).

See also

All commands for subroutines, where you will find links to the individual keywords related.

Libraries: Sharing code between many programs

Purpose

Libraries build upon subroutines and take the concept of code-reuse one step further: They allow code to be shared between different programs (as compared to subroutines, which on their own allow code-reuse within a single program only). Moreover, it is possible and in fact common, that the author of a library and the author of a program using that library, are different persons, each writing their respective code on their own.

A simple example

Here is a program, that asks the user for two numbers and then uses a library adder to add those:

import adder
	  
print "About to add two numbers."
input "Please enter first number: " x
input "Please enter second number: " y
print "Their sum is: ", adder.add(x,y)
	

The statement import adder pulls in code from a very simple library adder.yab:

sub add(a,b)
  return a+b
end sub
	

If you run it, you might see:

	  
About to add two numbers.
Please enter first number: 3
Please enter second number: 4
Their sum is: 7
	  
	

Compared with the very similar example for subroutines, there are two differences:

  1. The code of the subroutine add has been moved to its own file adder.yab.

  2. The subroutine add needs to be called as adder.add, which consists of filename (adder.yab but without the ending .yab) and the name of the subroutine (add) within that file.

This is an example of namespaces.

Namespaces

When the executable code is devided between a main program file and (multiple) libraries it is important to keep their subroutines and variables seperate. To this end yabasic internally prefixes the subroutines and variables defined in a library with the shortened name of the library. E.g. in the example above, the subroutine add from the library adder.yab is prefixed by this library-name and ends up as beeing defined as adder.add.

Subroutines and variables defined within the main program are prefixed with main; this prefix is fixed and not related to the actual filename of the main-program. Normally, however, there is no need to use this prefix explicitly; it only helps yabasic to keep everything apart.

See also

import, export, subroutines

Adding code to a running program

Purpose

Normally, you write programs in yabasic and specify all the necessary logic and calculations within your program. Once you are done, you invoke it, probably multiple times; and while it is running, it does not change.

However, there are some commands within yabasic, that allow to blur the line between writing and execution. Namely eval, eval$, compile, execute and execute$ allow to create and execute new yabasic-code while your program is running. This comes in handy, if the code to be used comes from the user of your program and will only be known after your program has started. A simple example is the yabasic-code to calculate the maximum of a user-supplied expression within a given range; find it as an example for eval. In the same way, one may write a program to plot an arithmetic function, whose definition is entered by the user.

Note: Even if the commands listed above allow to change the yabasic-program, that is currently running, the file where the program is stored, does not change. Therefore, the changes to the running program are not permanent.

How the various functions and commands differ

The most simple functions are eval and eval$; they compile an expression (with a numeric or string result), e.g. and execute it right away. The compiled code is remembered, so that it need not be compiled again, when the sames expression is executed again; this caters efficiency. However these functions only accept a single expression and nothing else.

If you need more complex computation and logic, the process needs to be split: First create a new subroutine with the compile-command, then execute this subroutine (maybe multiple times) via execute or execute$. This allows to use the broad logic available in subroutines (e.g. conditions, loops, local variables or even other subroutines) and therefore much more complex calculations than with eval. If you want to use compile multiple times within your program (e.g. in a loop), you may want to enumerate the functions you create to avoid name-clashes (as shown in the examples of compile).

To invoke the subroutines created, you need to execute them with execute or execute$, which require the name of the function (a string) as their first argument.

Creating a standalone program from your yabasic-program

Sometimes you may want to give one of your yabasic-programs to other people. However, what if those other people do not have yabasic installed ? In that case you may create a standalone-program from your yabasic-program, i.e. an executable, that may be executed on its own, standalone, even (and especially !) on computers, that do not have yabasic installed. Having created a standalone program, you may pass it around like any other program (e.g. one written in C) and you can be sure that your program will execute right away.

Such a standalone-program is simply created by copying the full yabasic-interpreter and your yabasic-program (plus all the libraries that it may import) together into a single, new program, whose name might be chosen at will (under windows of course it should have the ending .exe). If you decide to create a standalone-program, there are three facilities in yabasic, that you may use:

  • The bind-command, which does the actual job of creating the standalone program from the yabasic-interpreter and your program.

  • The command-line Option --bind (see options), which does the same from the command-line.

  • The special peek("isbound"), which may be used to check, if the yabasic-program containing this peek is bound to the interpreter as part of a standalone program.

With these bits you know enough to create a standalone-program. Actually there are two ways to do this: on the command line and from within your program.

Creating a standalone-program from the command line

Let's say you have the following very simple program within the file foo.yab:

print "Hello World !"

Normally you would start this yabasic-program by typing yabasic foo.yab and as a result the string Hello World ! would appear on your screen. However, to create a standalone-program from foo.yab you would type:

yabasic -bind foo.exe foo.yab

This command does not execute your program foo.yab but rather create a standalone-program foo.exe. Note: under Unix you would probably name the standalone program foo or such, omitting the windows-specific ending .exe.

Yabasic will confirm by printing something like: ---Info: Successfully bound 'yabasic' and 'foo.yab' into 'foo.exe'.

After that you will find a program foo.exe (which must be made executable with the chmod-command under Unix first). Now, executing this program foo.exe (or foo under Unix) will produce the output Hello World !.

This newly created program foo.exe might be passed around to anyone, even if he does not have yabasic installed.

Creating a standalone-program from within your program

It is possible to write a yabasic-program, that binds itself to the yabasic-interpreter. Here is an example:

if (!peek("isbound")) then
  bind "foo"
  print "Successfully created the standalone executable 'foo' !"
  exit
endif

print "Hello World !"

If you run this program (which may be saved in the file foo.yab) via yabasic foo.yab, the peek("isbound") in the first line will check, if the program is already part of a standalone-program. If not (i.e. if the yabasic-interpreter and the yabasic-program are separate files) the bind-command will create a standalone program foo containing both. As a result you would see the output Successfully created the standalone executable 'foo' !. Note: Under Windows you would probably choose the filename foo.exe.

Now, if you run this standalone executable foo (or foo.exe), the very same yabasic-program that is shown above will be executed again. However, this time the peek("isbound") will return TRUE and therefore the condition of the if-statement is false and the three lines after then are not executed. Rather the last print-statement will run, and you will see the output Hello World !.

That way a yabasic-program may turn itself into a standalone-program.

Points to consider before creating a standalone program

  • The new standalone program will be at least as big as the interpreter itself, which is typically a few hundred kilobytes.

  • There is no easy way to extract your yabasic-program from within the standalone program: If you ever want to change it, you should keep it around as a separate file.

  • If a new version of yabasic becomes available, you might want to recreate your standalone program to take advantage of bugfixes and improvements.

See also

The bind-command, the peek-function and the command line options.

Interaction with functions from a non-yabasic library or dll

Note

Under Unix, depending on the way yabasic has been built, this feature might have been disabled; the error message in this case will read like this build of yabasic does not support calling foreign libraries. To resolve this issue, you are invited to contact the maintainer.

Note

This is interesting, but somewhat advanced stuff. You will need a good understanding of various concepts of the C-language, especially pointers and structures as well as allocating and freeing blocks of memory. Please be aware, that mistakes or errors during calls to foreign functions or buffers may easily crash yabasic.

Yabasic allows to employ functionality from an external library; i.e. from a library, which is not written in yabasic, but rather in C; such a library is called a foreign library, as opposed to a library written in yabasic itself. Calling out to a foreign library can be useful, if such a library provides functionality, that can not be replicated in yabasic itself and for which a commandline-interface (which could be used via system) does not exist or is too cumbersome or slow. Examples would be libraries libVLC or libcurl which offer the functionality of vlc or curl to other programs, especially programs written in yabasic.

The foreign function interface of yabasic relies on the great libffi-library, a library making it easy to call other libraries dynamicaaly and the established standard for this task.

Some Background

Libraries

Libraries (e.g. libcurl) are meant to provide functionality to other programs (here: yabasic and your yabasic-program). Libraries and programs must be linked together; this can happen either statically at compile-time or dynamically during the excution of the program. For yabasic as the program, static linking happens at the time, yabasic itself is build, whereas dynamic linking happen during the execution and under control of your yabasic-program. So the foreign function interface deals with dynamic (or runtime) linking to external libraries. This linking is done by yabasic behind the scene, when you invoke foreign_function_call; this function, after loading the library, directly calls the specified function therein.

Which functions are available differs from library to library and you should already have this information before you try the library with yabasic.

Types

If you want to use a function from a foreign library, you will need to deal with the fact, that each function requires several parameters and returns exactly one. These parameters have a wide variety of types which need to be mapped to the two types (numbers and strings) known by yabasic. Here are the types available for foreign functions, grouped by the way, they are handled in yabasic:

uint8,int8,uint16,int16,uint32,int32,uint64,int64,float,double,char,short,int,long

In C all these types are used to represent numbers (integer or floating point) with various degrees of precision. When invoking foreign_function_call you need to pass strings, which specify the right type as well as the actual yabasic-value, which will then be converted accordingly. Which types a foreign function expects can be looked up e.g. from its manpage.

string

Strings for foreign functions directly map to strings of yabasic. So if you specify this type for a parameter of a foreign function, the matching value is simply a yabasic string. If you specify string as the return value of a foreign function you should use the variant of calling it, which returns a string, i.e. foreign_function_call$.

buffer

You should specify a buffer as the type of a parameter or the return type, if the foreign function expects a structure or a pointer to a memory area; see structures and buffers for details.

Three simple examples

Computing the cosine

This first example prints the cosine of 2, not by using yabasics own cos-function but by calling out to the standard C-library:

if peek$("os")="windows" then
  lib$ = "msvcrt.dll"
else
  lib$ = "libm.so.6"
endif

print "cos(2): ",foreign_function_call(lib$,"double","cos","double",2)

The first lines determine the name of the library, which is different under Unix and Windows. The call to foreign_function_call than just states the name of the library, the return type ("double") of the function and then its name ("cos"), as well as type and value (2) of its argument. The final result -0.416147 then is the same as from the the internal cos-function, which is no surprise, because yabasic is already statically linked to the standard C-library and uses its function to compute the cosine.

Searching a string within another string

A second example:

if peek$("os")="windows" then
  lib$ = "msvcrt.dll"
else
  lib$ = "libm.so.6"
endif

print foreign_function_call$(lib$,"string","strstr","string","foobar","string","ob","options","copy_string_result")

This example calls the strstr-function from the standard C-library; this function accepts two string arguments and returns a string, which is the first (if any) appearance of the second string within the first one (remark: this function makes more sense in C than in yabasic). Please note the option "copy_string_result", which advices yabasic to return a copy of the result of strstr; otherwise your program might crash, because strstr simply returns a pointer to a part of its first argument, a string that will later be freed by yabasic.

Showing a message box under Windows

This example is windows only; it shows a standard Windows message box with the given title and message:

message_box("Hello World !","Message from yabasic")

sub message_box(message$, title$)
  msgptr$ = foreign_buffer_alloc$(len(message$)+1)
  foreign_buffer_set msgptr$, 0, message$
  titleptr$ = foreign_buffer_alloc$(len(title$)+1)
  foreign_buffer_set titleptr$, 0, title$
  hwnd$ = foreign_function_call$("user32.dll", "buffer", "GetActiveWindow")
  ret = foreign_function_call("user32.dll", "int32", "MessageBoxA", "buffer", hwnd$, "buffer", msgptr$, "buffer", titleptr$, "uint32", 0)
  foreign_buffer_free msgptr$
  foreign_buffer_free titleptr$
  return ret
end sub

The relevant Windows-function MessageBoxA is found within the library user32.dll; most of the example deals with properly allocating, handling and freeing buffers to hold the supplied text-snippets. Thanx to Jean-Marc Duro for this example.

Internal steps during a call to a foreign function

A remark on libffi: this is the library which allows yabasic to call functions from other libraries libffi is used by many other programming-languages for the same purpose; in yabasic it is linked statically (rather than dynamically) so that its functionality is available right from the start. Summing up: libffi itself need not be loaded but helps to call functions from other loaded libraries.

Here is the sequence of events during a foreign function call (e.g. foreign_function_call):

  • Yabasic parses the type specifications and argument values provided and collects the necessary information for libffi.

  • The named library is loaded with the appropriate call (which is different under Windows and Unix). This step might easily fail, e.g. if you misspelled the name of the library or your system cannot find the library.

  • With the help of libffi the named function is invoked.

  • If you specified the option unload_library, the library that has been loaded is unloaded again.

  • The return value of the function is converted to a form suitable for yabasic and your program continues.

Errors are reported during every step.

Abbreviations for long names

Yabasics functions for dealing with foreign libraries start with foreign_function or foreign_buffer (e.g. foreign_buffer_alloc). To help in typing, these names can all be abbreviated by contracting foreign_function into frnfn and foreign_buffer into frnbf. In the examples below, both forms appear.

Structurs and buffers

The C-language provides a wide variety of simple datatypes (like numbers an strings) and allows to aggregate simple datatypes to structures such a structure contains a set of simple types arranged without overlap (but sometimes with gaps). Yabasic on itself does not know the internals of a structure but rather treats it as a uniform buffer. Structure and buffer are just flipsides of the same memory area viewed either from C or yabasic. For your yabasic-program a buffer is represented by a handle, which is just a simple printable string (containing the size and the memory adress).

The detailed knowledge about the simple types within a structure must be coded into your program, which uses the command (or function) foreign_buffer_set and foreign_buffer_get. Both functions require type and offset (which needs to be looked up in documentation of the foreign library) of the simple type within the structure and a handle to the buffer, which contains the structure.

Beeing essentially a memory area, a buffer is created with foreign_buffer_alloc and destroyed with foreign_buffer_free if needed no more.

Besides representing a structure, a buffer can also provide room to store raw areas of memory for use by the foreign library; example might be image- or sound-content.

Two more complex examples

Dealing with time

The example below deals with the time functions from the standard C-library; some of them deal with the tm structure for keeping the segmented time; to understand the example it is good to have the tm-structure at hand; see below. In addition it might be helpful to consult the manpages of the various C-functions (e.g. localtime)involved.

struct tm {
    int tm_sec;    /* Seconds (0-60) */
    int tm_min;    /* Minutes (0-59) */
    int tm_hour;   /* Hours (0-23) */
    int tm_mday;   /* Day of the month (1-31) */
    int tm_mon;    /* Month (0-11) */
    int tm_year;   /* Year - 1900 */
    int tm_wday;   /* Day of the week (0-6, Sunday = 0) */
    int tm_yday;   /* Day in the year (0-365, 1 Jan = 0) */
    int tm_isdst;  /* Daylight saving time */
};
    

The example plays with the two forms of keeping the time, either as unix-time (number of seconds since epoch) or as a segmented time (sec, min, etc.). The six steps are each introduced by comments, please see below.

# First: Determine the correct library depending on OS
#
if peek$("os")="windows" then
  lib$ = "msvcrt.dll"
else
  lib$ = "libm.so.6"
endif

# Second: Get the unix-time
#
# time() has a pointer argument to store the result (in addition to returning it)
# we pass NULL, so only the return value is relevant
#
null$ = foreign_buffer_alloc$(-1)
now = foreign_function_call(lib$,"int","time","buffer",null$)
print "Seconds since the epoch: ",now

# Third: Convert the unix-time to a segmented time
#
# localtime() does not accept the time-value as an argument, but rather requires a pointer
# to the time-value, so we construct a buffer for one int and put in our value
now$ = foreign_buffer_alloc$(foreign_function_size("int"))
foreign_buffer_set now$,0,"int",now
# Dump the buffer for educational purpose
print "Dump of buffer:          ",foreign_buffer_dump$(now$)
# localtime() returns a structure with the componentes (year, day, sec, etc.) as elements
local$ = foreign_function_call$(lib$,"buffer","localtime","buffer",now$)

# Fourth: Get the current year from the resulting buffer
#
# assuming, that year is the sixth element of the structure
# so offset is 5
offset = 5 * foreign_function_size("int")
year = foreign_buffer_get(local$,offset,"int")
print "Current year:            ", year + 1900


# Fifth: manipulate the segmented time
#
# set year to something else
foreign_buffer_set local$,offset,"int",year-50


# Sixth: convert time-structure from localtime into ascii
#
print "50 years back:           ", foreign_function_call$(lib$,"string","asctime","buffer",local$)

On my computer this program produces the following output:

Seconds since the epoch: 1559014899
Dump of buffer:          F3ADEC5C
Current year:            2019
50 years back:           Tue May 28 05:41:39 1969

Getting the version of libcurl

This final example just invokes libcurl to report its version. This is somewhat involved, because the matching function curl_version_info (see its man-page) returns a structure, which contains a pointer to a string, as can be seen from the structures definition:

typedef struct {
  CURLversion age;          /* see description below */
  const char *version;      /* human readable string */
  unsigned int version_num; /* numeric representation */
  const char *host;         /* human readable string */
  int features;             /* bitmask, see below */
  char *ssl_version;        /* human readable string */
  long ssl_version_num;     /* not used, always zero */
  const char *libz_version; /* human readable string */
  const char * const *protocols; /* protocols */

  ...                       /* more lines omitted */
  
} curl_version_info_data;
    

Please note, that the yabasic-code below uses abbreviations (e.g. frnfn_call instead of foreign_function_call.

# Get structure with version info
info$ = frnfn_call$("libcurl.so.4","buffer","curl_version_info","int",1)
# dump it for reference
print frnbf_dump$(info$,32)
# assume, that the pointer to version string is at offset 8
sinfo$ = frnbf_get_buffer$(info$,8)
# print readable version
print frnbf_get$(sinfo$,0,10)

The printing of frnbf_dump gives a hint on the internal offsets within the structure and helps to determine that offset of 8 for the next call.

On my system this program produces 7.61.1 for the version of curl.

See also

foreign_function_call, foreign_function_call2, foreign_function_size, foreign_buffer_alloc, foreign_buffer_free, foreign_buffer_size, foreign_buffer_dump, foreign_buffer_set, foreign_buffer_set_buffer, foreign_buffer_get, foreign_buffer_get2, foreign_buffer_get_buffer, system

Chapter 7. All commands and functions of yabasic grouped alphabetically

  • A
    • abs() — returns the absolute value of its numeric argument
    • acos() — returns the arcus cosine of its numeric argument
    • and — logical and, used in conditions
    • and() — the bitwise arithmetic and
    • arraydim() — returns the dimension of the array, which is passed as an array reference
    • arraysize() — returns the size of a dimension of an array
    • asc() — accepts a string and returns the position of its first character within the ascii charset
    • asin() — returns the arcus sine of its numeric argument
    • at() — can be used in the commands print and input to place the output at a specified position
    • atan() — returns the arctangent of its numeric argument
  • B
    • backcolor — change color for background of graphic window
    • beep — ring the bell within your computer; a synonym for bell
    • bell — ring the bell within your computer (just as beep)
    • bin$() — converts a number into a sequence of binary digits
    • bind() — binds a yabasic-program and the yabasic-interpreter together into a standalone program
    • bitnot() — the bitwise arithmetic not
    • box — draw a rectangle. A synonym for rectangle
    • break — breaks out of one or more loops or switch statements
  • C
    • case — mark the different cases within a switch-statement
    • ceil() — compute the ceiling for its (float) argument
    • chomp$() — remove a single trailing newline from its string-argument; if the string does not end in a newline, the string is returned unchanged
    • chr$() — accepts a number and returns the character at this position within the ascii charset
    • circle — draws a circle in the graphic-window
    • clear — erase circles, rectangles or triangles
    • clear screen — erases the text window
    • clear window — clear the graphic window and begin a new page, if printing is under way
    • close — close a file, which has been opened before
    • close curve — close a curve, that has been drawn by the line-command
    • close printer — stops printing of graphics
    • close window — close the graphics-window
    • color — change color for any subsequent drawing-command
    • compile — compile a string with yabasic-code on the fly
    • continue — start the next iteration of a for-, do-, repeat- or while-loop
    • cos() — return the cosine of its single argument
  • D
    • data — introduces a list of data-items
    • date$ — returns a string with various components of the current date
    • dec() — convert a base 2 or base 16 number into decimal form
    • default — mark the default-branch within a switch-statement
    • dim — create an array prior to its first use
    • do — start a (conditionless) do-loop
    • doc — special comment, which might be retrieved by the program itself
    • docu$ — special array, containing the contents of all docu-statement within the program
    • dot — draw a dot in the graphic-window
  • E
    • else — mark an alternative within an if-statement
    • elsif — starts an alternate condition within an if-statement
    • end — terminate your program
    • endif — ends an if-statement
    • end sub — ends a subroutine definition
    • eof — check, if an open file contains data
    • eor() — compute the bitwise exclusive or of its two arguments
    • error — raise an error and terminate your program
    • euler — another name for the constant 2.71828182864
    • eval() — compile and execute a single numeric expression
    • eval$() — compile and execute a single string-expression
    • execute() — execute a user defined subroutine, which must return a number
    • execute$() — execute a user defined subroutine, which must return a string
    • exit — terminate your program
    • exp() — compute the exponential function of its single argument
    • export — mark a function as globally visible
  • F
  • G
    • getbit$() — return a string representing the bit pattern of a rectangle within the graphic window
    • getscreen$() — returns a string representing a rectangular section of the text terminal
    • glob() — check if a string matches a simple pattern
    • gosub — continue execution at another point within your program (and return later)
    • goto — continue execution at another point within your program (and never come back)
  • H
    • hex$() — convert a number into hexadecimal
  • I
    • if — evaluate a condition and execute statements or not, depending on the result
    • import — import a library
    • inkey$ — wait, until a key is pressed
    • input — read input from user or file and assign it to a variable
    • instr() — searches its second argument within the first; returns its position if found
    • int() — return the integer part of its single numeric argument
  • L
    • label — mark a specific location within your program for goto, gosub or restore
    • left$() — return (or change) left end of a string
    • len() — return the length of a string
    • line — draw a line
    • line input — read in a whole line of text and assign it to a variable
    • local — mark a variable as local to a subroutine
    • log() — compute the natural logarithm
    • loop — marks the end of an infinite loop
    • lower$() — convert a string to lower case
    • ltrim$() — trim spaces at the left end of a string
  • M
    • max() — return the larger of its two arguments
    • mid$() — return (or change) characters from within a string
    • min() — return the smaller of its two arguments
    • mod — compute the remainder of a division
    • mouseb — extract the state of the mousebuttons from a string returned by inkey$
    • mousemod — return the state of the modifier keys during a mouseclick
    • mousex — return the x-position of a mouseclick
    • mousey — return the y-position of a mouseclick
  • N
    • new curve — start a new curve, that will be drawn with the line-command
    • next — mark the end of a for loop
    • not — negate a logical expression; can be written as !
    • numparams — return the number of parameters, that have been passed to a subroutine
  • O
    • on gosub — jump to one of multiple gosub-targets
    • on goto — jump to one of many goto-targets
    • on interrupt — change reaction on keyboard interrupts
    • open — open a file
    • open printer — open printer for printing graphics
    • open window — open a graphic window
    • logical or — logical or, used in conditions
    • or() — arithmetic or, used for bit-operations
  • P
    • pause — pause, sleep, wait for the specified number of seconds
    • peek — retrieve various internal informations (numeric)
    • peek$ — retrieve various internal informations (strings)
    • pi — a constant with the value 3.14159
    • poke — change selected internals of yabasic
    • print — Write to terminal or file
    • print or input with color — print or input-prompt with color
    • print colour — see print color
    • putbit — draw a rectangle of pixels encoded within a string into the graphics window
    • putscreen — draw a rectangle of characters into the text terminal
  • R
    • ran() — return a random number
    • read — read data from data-statements
    • rectangle — draw a rectangle
    • redim — create an array prior to its first use. A synonym for dim
    • rem — start a comment
    • repeat — start a repeat-loop
    • restore — reposition the data-pointer
    • return — return from a subroutine or a gosub
    • reverse — print reverse (background and foreground colors exchanged)
    • right$() — return (or change) the right end of a string
    • rinstr() — find the rightmost occurrence of one string within the other
    • round() — round its argument to the nearest integer
    • rtrim$() — trim spaces at the right end of a string
  • S
    • screen — as clear screen clears the text window
    • seek() — change the position within an open file
    • sig() — return the sign of its argument
    • sin() — return the sine of its single argument
    • shl() — shift its argument bitwise to the left
    • shr() — shift its argument bitwise to the right
    • sleep — pause, sleep, wait for the specified number of seconds
    • split() — split a string into many strings
    • sqr() — compute the square of its argument
    • sqrt() — compute the square root of its argument
    • static — preserves the value of a variable between calls to a subroutine
    • step — specifies the increment step in a for-loop
    • str$() — convert a number into a string
    • string$() — create a new string by repeating the given one a certain number of times
    • sub — declare a user defined subroutine
    • switch — select one of many alternatives depending on a value
    • system() — hand the name of an external command over to your operating system and return its exitcode
    • system$() — hand the name of an external command over to your operating system and return its output
  • T
    • tan() — return the tangent of its argument
    • tell — get the current position within an open file
    • text — write text into your graphic-window
    • then — tell the long from the short form of the if-statement
    • time$ — return a string containing the current time
    • to — this keyword appears as part of other statements
    • token() — split a string into multiple strings
    • triangle — draw a triangle
    • trim$() — remove leading and trailing spaces from its argument
    • true — a constant with the value of 1
  • U
    • until — end a repeat-loop
    • upper$() — convert a string to upper case
    • using — Specify the format for printing a number
  • V
    • val() — converts a string to a number
  • W
    • wait — pause, sleep, wait for the specified number of seconds
    • wend — end a while-loop
    • while — start a while-loop
    • window origin — move the origin of a window
  • X
    • xor() — compute the exclusive or
  • Symbols and Special characters
    • # — either a comment or a marker for a file-number
    • // — starts a comment
    • @ — synonymous to at
    • : — separate commands from each other
    • ; — suppress the implicit newline after a print-statement
    • ** or ^ — raise its first argument to the power of its second
    • < <= > >= = == <> != — Compare numbers or strings

A

Name

abs() — returns the absolute value of its numeric argument

Synopsis

y=abs(x)

Description

If the argument of the abs-function is positive (e.g. 2) it is returned unchanged, if the argument is negative (e.g. -1) it is returned as a positive value (e.g. 1).

Example

print abs(-2),abs(2)
          

This example will print 2 2

See also

sig


Name

acos() — returns the arcus cosine of its numeric argument

Synopsis

x=acos(angle)

Description

acos is the arcus cosine-function, i.e. the inverse of the cos-function. Or, more elaborate: It Returns the angle (in radians, not degrees !), which, fed to the cosine-function will produce the argument passed to the acos-function.

Example

print acos(0.5),acos(cos(pi))
          

This example will print 1.0472 3.14159 which are π/3 and π respectively.

See also

cos, asin


Name

and — logical and, used in conditions

Synopsis

if a and b …
while a and b …

Description

Used in conditions (e.g within if, while or until) to join two expressions. Returns true, if and only if its left and right argument are both true and false otherwise.

Note, that logical shortcuts may take place.

Example

input "Please enter a number" a
if (a>=1 and a<=9) print "your input is between 1 and 9"
          

See also

or,not


Name

and() — the bitwise arithmetic and

Synopsis

x=and(a,b)

Description

Used to compute the bitwise and of both its argument. Both arguments are treated as binary numbers (i.e. a sequence of digits 0 and 1); a bit of the resulting value will then be 1, if both arguments have a 1 at this position in their binary representation.

Note, that both arguments are silently converted to integer values and that negative numbers have their own binary representation and may lead to unexpected results when passed to and.

Example

print and(6,3)
          

This will print 2. This result is clear, if you note, that the binary representation of 6 and 3 are 110 and 011 respectively; this will yield 010 in binary representation or 2 as decimal.

See also

or, eor and bitnot


Name

arraydim() — returns the dimension of the array, which is passed as an array reference

Synopsis

a=arraydim(b())

Description

If you apply the arraydim()-function on a one-dimensional array (i.e. a vector) it will return 1, on a two-dimensional array (i.e. a matrix) it will return 2, and so on.

This is mostly used within subroutines, which expect an array among their parameters. Such subroutines tend to use the arraydim-function to check, if the array which has been passed, has the right dimension. E.g. a subroutine to multiply two matrices may want to check, if it really is invoked with two 2-dimensional arrays.

Example

dim a(10,10),b(10)
print arraydim(a()),arraydim(b())
          

This will print 2 1, which are the dimension of the arrays a() and b(). You may check out the function arraysize for a full example.

See also

arraysize and dim.


Name

arraysize() — returns the size of a dimension of an array

Synopsis

x=arraysize(a(),b)

Description

The arraysize-function computes the size of the specified dimension of a given array. Here, size stands for the maximum number, that may be used as an index for this array. The first argument to this function must be an reference to an array, the second one specifies, which of the multiple dimensions of the array should be taken to calculate the size. Please note, that arraysize returns the value that has been used in the actual dim-statement, the real (internal) size of the array is allocated one larger in each dimension to have a first element at index 0; however this is not reflected by the output of arraysize.

An Example involving subroutines: Let's say, an array has been declared as dim a(10,20) (that is a two-dimensional array or a matrix). If this array is passed as an array reference to a subroutine, this sub will not know, what sort of array has been passed. With the arraydim-function the sub will be able to find the dimension of the array, with the arraysize-function it will be able to find out the size of this array in its two dimensions, which will be 10 and 20 respectively.

Our sample array is two dimensional; if you envision it as a matrix this matrix has 10 lines and 20 columns (see the dim-statement above. To state it more formally: The first dimension (lines) has a size of 10, the second dimension (columns) has a size of 20; these numbers are those returned by arraysize(a(),1) and arraysize(a(),2) respectively. Refer to the example below for a typical usage.

Example


rem
rem  This program adds two matrices elementwise.
rem

dim a(10,20),b(10,20),c(10,20)

rem  initialization of the arrays a() and b() 
for y=1 to 10:for x=1 to 20
   a(y,x)=int(ran(4)):b(y,x)=int(ran(4))
next x:next y

matadd(a(),b(),c())

print "Result:"
for x=1 to 20
   for y=10 to 1 step -1
      print c(y,x)," ";
   next y
   print
next x

sub matadd(m1(),m2(),r())

   rem  This sub will add the matrices m1() and m2()
   rem  elementwise and store the result within r()
   rem  This is not very useful but easy to implement.
   rem  However, this sub excels in checking its arguments
   rem  with arraydim() and arraysize()

   local x:local y
   
   if (arraydim(m1())<>2 or arraydim(m2())<>2 or arraydim(r())<>2) then
      error "Need two dimensional arrays as input"
   endif

   y=arraysize(m1(),1):x=arraysize(m1(),2)
   if (arraysize(m2(),1)<>y or arraysize(m2(),2)<>x) then
      error "The two matrices cannot be added elementwise"
   endif

   if (arraysize(r(),1)<>y or arraysize(r(),2)<>x) then
      error "The result cannot be stored in the third argument"
   endif

   local xx:local yy
   for xx=1 to x
      for yy=1 to y
         r(yy,xx)=m1(yy,xx)+m2(yy,xx)
      next yy
   next xx

 end sub

          

See also

arraydim and dim.


Name

asc() — accepts a string and returns the position of its first character within the ascii charset

Synopsis

a=asc(char$)

Description

The asc-function accepts a string, takes its first character and looks it up within the ascii-charset; this position will be returned. The asc-function is the opposite of the chr$-function. There are valid uses for asc, however, comparing strings (i.e. to bring them into alphabetical sequence) is not among them; in such many cases you might consider to compare strings directly with <, = and > (rather than converting a string to a number and comparing this number).

Example

input "Please enter a letter between 'a' and 'y': " a$
if (a$<"a" or a$>"y") print a$," is not in the proper range":end
print "The letter after ",a$," is ",chr$(asc(a$)+1)
          

See also

chr$


Name

asin() — returns the arcus sine of its numeric argument

Synopsis

angle=asin(x)

Description

acos is the arcus sine-function, i.e. the inverse of the sin-function. Or, more elaborate: It Returns the angle (in radians, not degrees !), which, fed to the sine-function will produce the argument passed to the asin-function.

Example

print asin(0.5),asin(sin(pi))
          

This will print 0.523599 -2.06823e-13 which is π/6 and almost 0 respectively.

See also

sin, acos


Name

at() — can be used in the commands print and input to place the output at a specified position

Synopsis

clear screen
…
print at(a,b)
input at(a,b) "Your input: " a$
print @(a,b)

Description

The at-clause takes two numeric arguments (e.g. at(2,3)) and can be inserted after the print-keyword. at() can be used only if clear screen has been executed at least once within the program (otherwise you will get an error).

The two numeric arguments of the at-function may range from 0 to the width of your terminal minus 1, and from 0 to the height of your terminal minus 1; if any argument exceeds these values, it will be truncated accordingly. However, yabasic has no influence on the size of your terminal (80x25 is a common, but not mandatory), the size of your terminal and the maximum values acceptable within the at-clause may vary. To get the size of your terminal you may use the peek-function: peek("screenwidth") returns the width of your terminal and peek("screenheight") its height.

Example

clear screen
maxx=peek("screenwidth")-1:maxy=peek("screenheight")-1
for x=0 to maxx
  print at(x,maxy*(0.5+sin(2*pi*x/maxx)/2)) "*"
next x
          

This example plots a full period of the sine-function across the screen.


Name

atan() — returns the arctangent of its numeric argument

Synopsis

angle=atan(a,b)
angle=atan(a)

Description

atan is the arctangent-function, i.e. the inverse of the tan-function. Or, more elaborate: It Returns the angle (in radians, not degrees !), which, fed to the tan-function will produce the argument passed to the atan-function.

The atan-function has a second form, which accepts two arguments: atan(a,b) which is (mostly) equivalent to atan(a/b) except for the fact, that the two-argument-form returns an angle in the range -π to π, whereas the one-argument-form returns an angle in the range -π/2 to π/2. To understand this you have to be good at math.

Example

print atan(1),atan(tan(pi)),atan(-0,-1),atan(-0,1)
          

This will print 0.463648 2.06823e-13 -3.14159 3.14159 which is π/4, almost 0, -π and π respectively.

See also

tan, sin

B

Name

color — change color for background of graphic window

Synopsis

backcolour red,green,blue
backcolour "red,green,blue"
	  

Description

Change the color, that becomes visible, if any portion of the window is erased, e.g. after clear window or clear line. Note however, that parts of the window, that show the old background color will not change.

As with the color-command, the new background color can either be specified as a triple of three numbers or as a single string, that contains those three numbers separated by commas.

Note, that the command backcolor can be written as backcolour too and vice versa.

Example

open window 255,255
for x=10 to 235 step 10:for y=10 to 235 step 10
  	backcolour x,y,0
	clear window
	sleep 1
next y:next x
            

This changes the background colour of the graphic window repeatedly and clears it every time, so that it is filled with the new background colour.


Name

beep — ring the bell within your computer; a synonym for bell

Synopsis

beep

Description

The bell-command rings the bell within your computer once. This command is not a sound-interface, so you can neither vary the length or the height of the sound (technically, it just prints \a). bell is exactly the same as beep.

Example

beep:print "This is a problem ..."
          

See also

beep


Name

bell — ring the bell within your computer (just as beep)

Synopsis

bell

Description

The beep-command rings the bell within your computer once. beep is a synonym for bell.

Example

print "This is a problem ...":beep
          

See also

bell


Name

bin$() — converts a number into a sequence of binary digits

Synopsis

hexadecimal$=bin$(decimal)

Description

The bin$-function takes a single numeric argument an converts it into a string of binary digits (i.e. zeroes and ones). If you pass a negative number to bin$, the resulting string will be preceded by a '-'.

If you want to convert the other way around (i.e. from binary to decimal) you may use the dec-function.

Example

for a=1 to 100
  print bin$(a)
next a
          

This example prints the binary representation of all digits between 1 and 100.


Name

bind() — binds a yabasic-program and the yabasic-interpreter together into a standalone program

Synopsis

bind("foo.exe")

Description

The bind-command combines your own yabasic-program (plus all the libraries it does import) and the interpreter by copying them into a new file, whose name is passed as an argument. This new program may then be executed on any computer, even if it does not have yabasic installed.

Please see the section about creating a standalone-program for details.

Example

if (!peek("isbound")) then
  bind "foo"
  print "Successfully created the standalone executable 'foo' !"
  exit
endif

print "Hello World !"
          

This example creates a standalone program foo from itself.

See also

The section about creating a standalone-program, the peek-function and the command line options.


Name

bitnot() — the bitwise arithmetic not

Synopsis

x=bitnot(a)

Description

This function is used to compute the bitwise not of its single argument. The argument is treated as binary number (i.e. a sequence of digits 0 and 1); a bit of the resulting value will be 1, if the argument has a 0 at this position in its binary representation; if the bit in the argument is 1, the bit in the result will be 0.

Note, that its argument is silently converted to a positive integer value and that negative numbers have their own binary representation and may lead to unexpected results when passed to bitnot.

A note on naming: This one-argument-function is named bitnot to distinguish it from the one-argument-function not, which operates on logical expressions. For the similar functions and and or this distinction between logical and bitwise function is done implicitly through the number of arguments (1 and 2, respectively).

Example

print bin$(not(17))
          

This will print 11111111111111111111111111101110. This result is clear, if you note, that the binary representation of 17 is 10001, which inverted will give the long binary number given before.

See also

or, eor and and


Name

box — draw a rectangle. A synonym for rectangle

Synopsis

See the rectangle-command.

Description

The box-command does exactly the same as the rectangle-command; it is just a synonym. Therefore you should refer to the entry for the rectangle-command for further information.


Name

break — breaks out of one or more loops or switch statements

Synopsis

break
break 2

Description

break transfers control immediately outside the enclosing loop or switch statement. This is the preferred way of leaving a such a statement (rather than goto, which is still possible in most cases). An optional digit allows one to break out of multiple levels, e.g. to leave a loop from within a switch statement. Please note, that only a literal (e.g. 2) is allowed at this location.

Example

for a=1 to 10
  break
  print "Hi"
next a

while 1
  break
  print "Hi"
wend

repeat
  break
  print "Hi"
until 0

switch 1
case 1:break
case 2:case 3:print "Hi"
end switch
          

This example prints nothing at all, because each of the loops (and the switch-statement) does an immediate break (before it could print any "Hi").

See also

for, while, repeat and switch.

C

Name

case — mark the different cases within a switch-statement

Synopsis

switch a
  case 1
  case 2
  …
end switch

…

switch a$
  case "a"
  case "b"
  …
end switch

Description

Please see the switch-statement.

Example

input a
switch(a)
  case 1:print "one":break
  case 2:print "two":break
  default:print "more"
end switch
          

Depending on your input (a number is expected) this code will print one or two or otherwise more.

See also

switch


Name

ceil() — compute the ceiling for its (float) argument

Synopsis

print ceil(x)

Description

The ceil-function returns the smallest integer number, that is larger or equal than its argument.

Example

print ceil(1.5),floor(1.5)
print ceil(2),floor(2)
          

Comparing functions ceil and floor, gives a first line of output (1 2), showing that ceil is less or equal than floor; but as the second line of output (2 2) shows, the two functions give equal results for integer arguments.

See also

floor, int, frac, round


Name

chomp$() — remove a single trailing newline from its string-argument; if the string does not end in a newline, the string is returned unchanged

Synopsis

print chomp$("Hallo !\n")

Description

The chomp$-function checks, if its string-argument ends in a newline and removes it eventually; for this purpose chomp$ can replace an if-statement. This can be especially useful, when you deal with input from external sources like system$.

You may apply chomp$ freely, as it only acts, if there is a newline to remove; note however, that user-input, that comes from the normal input-statement, does not need such a treatment, because it already comes without a newline.

Example

The following yabasic-program uses the unix-command whoami to get the username of the current user in order to greet him personally. This is done twice: First with the chomp$-function and then again with with an equivalent if-statement:

print "Hello " + chomp$(system$("whoami")) + " !"

user$ = system$("whoami")
if (right$(user$,1)="\n") user$=left$(user$,len(user$)-1)
print "Hello again " + user$ + " !"
          

See also

system$


Name

chr$() — accepts a number and returns the character at this position within the ascii charset

Synopsis

character$=chr$(ascii)

Description

The chr$-function is the opposite of the asc-function. It looks up and returns the character at the given position within the ascii-charset. It's typical use is to construct nonprintable characters which do not occur on your keyboard.

Nevertheless you won't use chr$ as often as you might think, because the most important nonprintable characters can be constructed using escape-sequences using the \-character (e.g. you might use \n instead of chr$(10) wherever you want to use the newline-character).

Example

print "a",chr$(10),"b"
          

This will print the letters 'a' and 'b' in different lines because of the intervening newline-character, which is returned by chr$(10).

See also

asc


Name

circle — draws a circle in the graphic-window

Synopsis

circle x,y,r
clear circle x,y,r
fill circle x,y,r
clear fill circle x,y,r

Description

The circle-command accepts three parameters: The x- and y-coordinates of the center and the radius of the circle.

Some more observations related with the circle-command:

  • The graphic-window must have been opened already.

  • The circle may well extend over the boundaries of the window.

  • If you have issued open printer before, the circle will finally appear in the printed hard copy of the window.

  • fill circle will draw a filled (with black ink) circle.

  • clear circle will erase (or clear) the outline of the circle.

  • clear fill circle or fill clear circle will erase the full area of the circle.

Example

open window 200,200

for n=1 to 2000
  x=ran(200)
  y=ran(200)
  fill circle x,y,10
  clear fill circle x,y,8
next n
          

This code will open a window and draw 2000 overlapping circles within. Each circle is drawn in two steps: First it is filled with black ink (fill circle x,y,10), then most of this circle is erased again (clear fill circle x,y,8). As a result each circle is drawn with an opaque white interior and a 2-pixel outline (2-pixel, because the radii differ by two).


Name

clear — erase circles, rectangles or triangles

Synopsis

clear rectangle 10,10,90,90
clear fill circle 50,50,20
clear triangle 10,10,20,20,50,30

Description

May be used within the circle, rectangle or triangle command and causes these shapes to be erased (i.e. be drawn in the colour of the background).

fill can be used in conjunction with and wherever the fill-clause may appear. Used alone, clear will erase the outline (not the interior) of the shape (circle, rectangle or triangle); together with fill the whole shape (including its interior) is erased.

Example

open window 200,200
fill circle 100,100,50
clear fill rectangle 10,10,90,90
          

This opens a window and draws a pacman-like figure.


Name

clear screen — erases the text window

Synopsis

clear screen

Description

clear screen erases the text window (the window where the output of print appears).

It must be issued at least once, before some advanced screen-commands (e.g. print at or inkey$) may be called; this requirement is due to some limitations of the curses-library, which is used by yabasic under Unix for some commands.

Example

clear screen
print "Please press a key : ";
a$=inkey$
print a$
          

The clear screen command is essential here; if it would be omitted, yabasic would issue an error ("need to call 'clear screen' first") while trying to execute the inkey$-function.

See also

inkey$


Name

clear window — clear the graphic window and begin a new page, if printing is under way

Synopsis

clear window

Description

clear window clears the graphic window. If you have started printing the graphic via open printer, the clear window-command starts a new page as well.

Example

open window 200,200
open printer "t.ps"

for a=1 to 10
if (a>1) clear window
text 100,100,"Hallo "+str$(a)
next a

close printer
close window
          

This example prints 10 pages, with the text "Hello 1", "Hello 2", … and so on. The clear screen-command clears the graphics window and starts a new page.


Name

close — close a file, which has been opened before

Synopsis

close filenum
close # filenum

Description

The close-command closes an open file. You should issue this command as soon as you are done with reading from or writing to a file.

Example

open "my.data" for reading as 1
input #1 a
print a
close 1
          

This program opens the file "my.data", reads a number from it, prints this number and closes the file again.

See also

open


Name

close curve — close a curve, that has been drawn by the line-command

Synopsis

new curve
line to x1,y1
…
close curve

Description

The close curve-command closes a sequence of lines, that has been drawn by repeated line to-commands.

Example

open window 200,200
new curve
line to 100,50
line to 150,150
line to 50,150
close curve
          

This example draws a triangle: The three line to-commands draw two lines; the final line is however not drawn explicitly, but drawn by the close curve-command.

See also

line, new curve


Name

close printer — stops printing of graphics

Synopsis

close printer

Description

The close printer-command ends the printing graphics. Between open printer and close printer everything you draw (e.g. circles, lines …) is sent to your printer. close printer puts an end to printing and will make your printer eject the page.

Example

open window 200,200
open printer
circle 100,100,50
close printer
close window
          

As soon as close printer is executed, your printer will eject a page with a circle on it.

See also

open printer


Name

close window — close the graphics-window

Synopsis

close window

Description

The close window-command closes the graphics-window, i.e. it makes it disappear from your screen. It includes an implicit close printer, if a printer has been opened previously.

Example

open window 200,200
circle 100,100,50
close window
          

This example will open a window, draw a circle and close the window again; all this without any pause or delay, so the window will be closed before you may regard the circle..

See also

open window


Name

color — change color for any subsequent drawing-command

Synopsis

colour red,green,blue
colour "red,green,blue"

Description

Change the color, in which lines, dots, circles, rectangles or triangles are drawn. The color-command accepts three numbers in the range 0 … 255 (as in the first line of the synopsis above). Those numbers specify the intensity for the primary colors red, green and blue respectively. As an example 255,0,0 is red and 255,255,0 is yellow.

Alternatively you may specify the color with a single string (as in the second line of the synopsis above); this string should contain three numbers, separated by commas. As an example "255,0,255" would be violet. Using this variant of the colour-command, you may use symbolic names for colours:

open window 100,100
yellow$="255,255,0"
color yellow$
text 50,50,"Hallo"
	  

, which reads much clearer.

Example

open window 255,255
for x=10 to 235 step 10:for y=10 to 235 step 10
  	colour x,y,0
  	fill rectangle x,y,x+10,y+10
next y:next x
            

This fills the window with colored rectangles. However, none of the used colours contains any shade of blue, because the color-command has always 0 as a third argument.

Note, that the command color can be written as colour too and vice versa.


Name

compile — compile a string with yabasic-code on the fly

Synopsis

compile(code$)

Description

This is an advanced command (closely related with the execute-command). It allows you to compile a string of yabasic-code (which is the only argument). Afterwards the compiled code is a normal part of your program.

Note, that there is no way to remove the compiled code.

Examples

compile("sub mysub(a):print a:end sub")
mysub(2)
          

This example creates a function named mysub, which simply prints its single argument.

Another Example

This next example combines the functions compile and execute:

count = 1	      
subname$ = "foo" + str$(count)
compile("sub "+ subname$ + "(a):print a:end sub")
execute(subname$,2)
          

This example creates and executes a function, whose name (foo1) is stored within the variable subname$; the newly created function simply prints its single argument. This example could be executed multiple times within a single yabasic-program, simply by incrementing the variable count; by doing that, multiple subroutines (foo1, foo2, …) could be created and executed in succession.


Name

continue — start the next iteration of a for-, do-, repeat- or while-loop

Synopsis

continue

Description

You may use continue within any loop to start the next iteration immediately. Depending on the type of the loop, the loop-condition will or will not be checked. Especially: for- and while-loops will evaluate their respective conditions, do- and repeat-loops will not.

Remark: Another way to change the flow of execution within a loop, is the break-command.

Example

for a=1 to 100
  if mod(a,2)=0 continue
  print a
next a
          

This example will print all odd numbers between 1 and 100.

See also

for, do, repeat, while, break


Name

cos() — return the cosine of its single argument

Synopsis

x=cos(angle)

Description

The cos-function expects an angle (in radians) and returns its cosine.

Example

print cos(pi)
          

This example will print -1.

See also

acos, sin

D

Name

data — introduces a list of data-items

Synopsis

data 9,"world"
…
read b,a$

Description

The data-keyword introduces a list of comma-separated list of strings or numbers, which may be retrieved with the read-command.

The data-command itself does nothing; it just stores data. A single data-command may precede an arbitrarily long list of values, in which strings or numbers may be mixed at will.

yabasic internally uses a data-pointer to keep track of the current location within the data-list; this pointer may be reset with the restore-command.

Example

do
  restore
  for a=1 to 4
    read num$,num
    print num$,"=",num
  next a
loop
data "eleven",11,"twelve",12,"thirteen",13,"fourteen",14
          

This example just prints a series of lines eleven=11 up to fourteen=14 and so on without end.

The restore-command ensures that the list of data-items is read from the start with every iteration.

See also

read, restore


Name

date$ — returns a string with various components of the current date

Synopsis

a$=date$

Description

The date$-function (which must be called without parentheses; i.e. date$() would be an error) returns a string containing various components of a date; an example would be 4-05-27-2004-Thu-May. This string consists of various fields separated by hyphens ("-"):

  • The day within the week as a number in the range 0 (=Sunday) to 6 (=Saturday) (in the example above: 4, i.e. Thursday).

  • The month as a number in the range 1 (=January) to 12 (=December) (in the example: 5 which stands for May).

  • The day within the month as a number in the range 1 to 31 (in the example: 27).

  • The full, 4-digit year (in the example: 2004, which reminds me that I should adjust the clock within my computer …).

  • The abbreviated name of the day within the week (Mon to Sun).

  • The abbreviated name of the month (Jan to Dec).

Therefore the whole example above (4-05-27-2004-Thu-May) would read: day 4 in the week (counting from 0), May 27 in the year 2004, which is a Thursday in May.

Note, that all fields within the string returned by date$ have a fixed with (numbers are padded with zeroes); therefore it is easy to extract the various fields of a date format with mid$.

Example

rem   Two ways to print the same ...

print mid$(date$,3,10)

dim fields$(6)
a=split(date$,fields$(),"-")
print fields$(2),"-",fields$(3),"-",fields$(4)
          

This example shows two different techniques to extract components from the value returned by date$. The mid$-function is the preferred way, but you could just as well split the return-value of date$ at every "-" and store the result within an array of strings.

See also

time$


Name

dec() — convert a base 2 or base 16 number into decimal form

Synopsis

a=dec(number$)
a=dec(number$,base)

Description

The dec-function takes the string-representation of a base-2 or base-16 (which is the default) number and converts it into a decimal number. The optional second argument (base) might be used to specify a base other than 16. However, currently only base 2 or base 16 are supported. Please note, that for base 16 and 2 you may write literals in the usual way, by preceding them with 0x or 0b respectively, e.g. like

print 0xff + 0b11

; this may save you from applying the dec altogether.

Example

input "Please enter a binary number: " a$
print a$," is ",dec(a$)
          

Name

default — mark the default-branch within a switch-statement

Synopsis

switch a+3
case 1
  …
case 2
  …
default
  …
end switch

Description

The default-clause is an optional part of the switch-statement (see there for more information). It introduces a series of statements, that should be executed, if none of the cases matches, that have been specified before (each with its own case-clause).

So default specifies a default to be executed, if none of the explicitly named cases matches; hence its name.

Example

print "Please enter a number between 0 and 6,"
print "specifying a day in the week."
input d
switch d
case 0:print "Monday":break
case 1:print "Tuesday":break
case 2:print "Wednesday":break
case 3:print "Thursday":break
case 4:print "Friday":break
case 5:print "Saturday":break
case 6:print "Sunday":break
default:print "Hey you entered something invalid !"
end switch
          

This program translates a number between 0 and 6 into the name of a weekday; the default-case is used to detect (and complain about) invalid input.

See also

sub, case


Name

dim — create an array prior to its first use

Synopsis

dim array(x,y)
dim array$(x,y)

Description

The dim-command prepares one or more arrays (of either strings or numbers) for later use. This command can also be used to enlarges an existing array.

When an array is created with the dim-statement, memory is allocated and all elements are initialized with either 0 (for numerical arrays) or "" (for string arrays). Please be aware, that the dim reserves room for one element more than actually specified, e.g. dim(10) reserves memory for 11 elements. This makes it possible to access element 0 as well as element 10, which serves the conventions of C as well as basic.

If the array already existed, and the dim-statement specifies a larger size than the current size, the array is enlarged and any old content is preserved. But note, that dim cannot be used to shrink an array: If you specify a size, that is smaller than the current size, the dim-command does nothing.

Finally: To create an array, that is only known within a single subroutine, you should use the command local, which creates local variables as well as local arrays.

Example

dim a(5,5)

for x=1 to 5:for y=1 to 5
  a(x,y)=int(ran(100))
next y:next x

printmatrix(a())

dim a(7,7)

printmatrix(a())

sub printmatrix(ar())
  local x,y,p,q
  x=arraysize(ar(),1)
  y=arraysize(ar(),2)
  for q=1 to y
    for p=1 to y
      print ar(p,q),"\t";
    next p
    print
  next q
end sub
          

This example creates a 2-dimensional array (i.e. a matrix) with the dim-statement and fills it with random numbers. The second dim-statement enlarges the array, all new elements are filled with 0.

The subroutine printmatrix just does, what its name says.


Name

do — start a (conditionless) do-loop

Synopsis

do 
… 
loop

Description

Starts a loop, which is terminated by loop; everything between do and loop will be repeated forever. This loop has no condition, so it is an infinite loop; note however, that a break- or goto-statement might be used to leave this loop anytime.

Example

do
  a=a+1
  print a
  if (a>100) break
loop
          

This example prints the numbers between 1 and 101. The break-statement is used to leave the loop.

See also

loop, repeat, while, break


Name

doc — special comment, which might be retrieved by the program itself

Synopsis

doc   This is a comment
docu  This is another comment

Description

Introduces a comment, which spans up to the end of the line. But other than the rem-comment, any docu-comment is collected within the special docu$-array and might be retrieved later on. Moreover you might invoke yabasic -docu foo.yab on the command line to retrieve the embedded documentation within the program foo.yab.

Instead of doc you may just as well write docu or even documentation.

Example

rem   Hi, this has been written by me
rem
doc   This program asks for a number and
doc   prints this number multiplied with 2
rem
rem   Print out the above message
rem
for a=1 to arraysize(docu$(),1):print docu$(a):next a

rem   Read and print the number
input "Please input a number: " x
print x*2
          

This program uses the comments within its code to print out a help message for the user; if you run this program, you get this output:

  This program asks for a number and
  prints this number multiplied with 2
Please input a number: 2
4

The contents of the doc-lines are retrieved from the docu$-array; if you do not want a comment to be collected within this array, use the rem-statement instead.

See also

docu$, rem, option --docu


Name

docu$ — special array, containing the contents of all docu-statement within the program

Synopsis

a$=docu$(1)

Description

Before your program is executed, yabasic collects the content of all the doc-statements within your program within this 1-dimensional array (well only those within the main-program, libraries are skipped).

You may use the arraysize function to find out, how many lines it contains.

Example

docu
docu  This program reads two numbers 
docu  and adds them.
docu

rem retrieve and print the embedded documentation
for a=1 to arraysize(docu$(),1)
  print docu$(a)
next a

input "First number: " b
input "Second number: " c

print "The sum of ",b," and ",c," is ",b+c
          

This program uses the embedded documentation to issue a usage-message.


Name

dot — draw a dot in the graphic-window

Synopsis

dot x,y
clear dot x,y

Description

Draws a dot at the specified coordinates within your graphic-window. If printing is in effect, the dot appears on your printout too.

Use the functions peek("winheight") or peek("winwidth") to get the size of your window and hence the boundaries of the coordinates specified for the dot-command.

Example

open window 200,200
circle 100,100,100
do
  x=ran(200):y=ran(200)
  dot x,y
  total=total+1
  if (sqrt((x-100)^2+(y-100)^2)<100) in=in+1
  print 4*in/total
loop
          

This program uses a well known algorithm to compute π.

See also

line, open window

E

Name

else — mark an alternative within an if-statement

Synopsis

if (…) then 
  … 
else 
  … 
endif

Description

The else-statement introduces the alternate branch of an if-statement. I.e. it starts the sequence of statements, which is executed, if the condition of the if-statement is not true.

Example

input "Please enter a number: " a
if (mod(a,2)=1) then
  print a," is odd."
else
  print a," is even."
endif
          

This program detects, if the number you have entered is even or odd.

See also

if


Name

elsif — starts an alternate condition within an if-statement

Synopsis

if (…) then
  …
elseif (…) 
  …
elsif (…) then
  …
else
  …
endif

Description

The elsif-statement is used to select a single alternative among a series of choices.

With each elsif-statement you may specify a condition, which is tested, if the main condition (specified with the if-statement) has failed. Note that elsif might be just as well written as elseif.

Within the example below, two variables a and b are tested against a range of values. The variable a is tested with the elsif-statement. The very same tests are performed for the variable b too; but here an involved series of if-else-statements is employed, making the tests much more obscure.

Example

input "Please enter a number: " a
if (a<0) then
  print "less than 0"
elseif (a<=10) then
  print "between 0 and 10"
elsif (a<=20)
  print "between 11 and 20"
else
  print "over 20"
endif

input "Please enter another number: " b
if (b<0) then
  print "less than 0"
else
  if (b<=10) then
    print "between 0 and 10"
  else
    if (b<=20) then
      print "between 11 and 20"
    else
      print "over 20"
    endif
  endif
endif
          

Note, that the very same tests are performed for the variables a and b, but can be stated much more clearly with the elsif-statement.

Note, that elsif might be written as elseif too, and that the keyword then is optional.

See also

if, else


Name

end — terminate your program

Synopsis

end

Description

Terminate your program. Much (but not exactly) like the exit command.

Note, that end may not end your program immediately; if you have opened a window or called clear screen, yabasic assumes, that your user wants to study the output of your program after it has ended; therefore it issues the line ---Program done, press RETURN--- and waits for a key to be pressed. If you do not like this behaviour, consider using exit.

Example

print "Do you want to continue ?"
input "Please answer y(es) or n(o): " a$
if (lower$(left$(a$,1))="n") then
  print "bye"
  end
fi
          

See also

exit


Name

endif — ends an if-statement

Synopsis

if (…) then
  …
endif

Description

The endif-statement closes (or ends) an if-statement.

Note, that endif may be written in a variety of other ways: end if, end-if or even fi.

The endif-statement must be omitted, if the if-statement does not contain the keyword then (see the example below). Such an if-statement without endif extends only over a single line.

Example

input "A number please: " a
if (a<10) then
  print "Your number is less than 10."
endif

REM  and now without endif 

input "A number please: " a
if (a<10) print "Your number is less than 10."
          

See also

if


Name

end sub — ends a subroutine definition

Synopsis

sub foo(…) 
  …
end sub

Description

Marks the end of a subroutine-definition (which starts with the sub-keyword). The whole concept of subroutines is explained within the entry for sub.

Example

print foo(3)

sub foo(a)
  return a*2
end sub
          

This program prints out 6. The subroutine foo simply returns twice its argument.

See also

sub


Name

eof — check, if an open file contains data

Synopsis

open 1,"foo.bar"
if (eof(1)) then 
   …
end if

Description

The eof-function checks, if there is still data left within an open file. As an argument it expects the file-number as returned by (or used within) the open-function (or statement).

As a special case, if the argument is zero: test if input from stdin is available.

Example

a=open("foo.bar")
while not eof(a)
  input #a,a$
  print a$
end while
          

This example will print the contents of the file "foo.bar". The eof-function will terminate the loop, if there is no more data left within the file.

See also

open


Name

eor() — compute the bitwise exclusive or of its two arguments

Synopsis

print eor(a,b)

Description

The eor-function takes two arguments and computes their bitwise exclusive or. I.e. treat each arguments as a sequence of bits and compare theses two sequences bit by bit to produce the result. If the bits from the arguments are equal, the resulting bit will be 0, otherwise 1.

The xor-function is the same as the eor function; both are synonymous; however they have each their own description, so you may check out the entry of xor for a slightly different view.

Example

for a=0 to 3
  for b=0 to 3
    print fill$(bin$(a))," eor ",fill$(bin$(b))," = ",fill$(bin$(eor(a,b)))
  next b
next a

sub fill$(a$)
  return right$("0"+a$,2)
end sub
          

This example prints a table, from which you may figure, how the eor-function is computed.

See also

and, or


Name

error — raise an error and terminate your program

Synopsis

error "Wrong, wrong, wrong !!"

Description

Produces the same kind or error messages, that yabasic itself produces (e.g. in case of a syntax-error). The single argument is issued along with the current line-number.

Example

input "Please enter a number between 1 and 10: " a
if (a<1 or a>10) error "Oh no ..."
          

This program is very harsh in checking the users input; instead of just asking again, the program terminates with an error, if the user enters something wrong.

The error message would look like this:

---Error in t.yab, line 2: Oh no ...
---Error: Program stopped due to an error

See also

Well, there should be a corresponding called warning; unfortunately ther is none yet.


Name

euler — another name for the constant 2.71828182864

Synopsis

foo=euler

Description

euler is the well known constant named after Leonard Euler; its value is 2.71828182864. euler is not a function, so parens are not allowed (i.e. euler() will produce an error). Finally, you may not assign to euler; it wouldn't sense anyway, because it is a constant.

Example

print euler
          

See also

pi


Name

eval() — compile and execute a single numeric expression

Synopsis

print eval("1+2")

Description

eval accepts a string, which should be the text of a single numeric expression; it processes the expression and returns the result. All numeric functions and arithmetic operators of yabasic can be used as well as any variables known.

The string passed to eval is first compiled and then executed right away. The compilation happens just before the execution and may cause compilation errors, if you pass an invalid expression. eval might come handy, if you want to calculate an expression, that is not known at the start of your program, e.g. because it is read from the user; see the example below.

Example

input "Please enter an aritmetic expression involving the variable x: " expr$
first = true
for x=0 to 100 step 0.01
  result = eval(expr$)
  if (first or result > maximum) maximum = result: xmaximum = x
  first = false
next x
print "In the range 0 to 100, expression " + expr$ + " has its maximum of " + str$(maximum) + " at " + str$(xmaximum) + " (approximately)"
          

The example above reads an arithmetic expression from the user and steps through the range 0 … 100 to find its maximum. If the user types e.g. -(x-50)**2, the program would find a maximum of around zero (e.g. -1.90013e-24) at 50.


Name

eval$() — compile and execute a single string-expression

Synopsis

print eval$("a$ + b$")

Description

eval$ accepts a string, which should be the text of a single string-expression; it processes the expression and returns the result. All string-functions and string-operators of yabasic can be used as well as any variables known.

The string passed to eval$ is first compiled and then executed right away. The compilation happens right before the execution and may cause compilation errors, if you pass an invalid expression. See the example below for two interesting use-cases.

A short but useful Example

The example below allows to apply the quoting rules of yabasic to user-input:

input "Please enter a string with some excape-sequences (e.g. \\r,\\n,\\t): " a$
print eval$("\"" + a$ + "\"")
            

If the user types abc\ndef at the prompt, the text is echoed like this:

	      
		abc
		def
	      
	    

A longer Example

The next example shows the subroutine evemex$ (for eval embedded expression) that allows to embed expressions into a string, simply by enclosing them with {{ and }}:


input "Please enter your name: " name$
print evemex$("Hello {{name$}}, your name has {{len(name$)}} characters.")


sub evemex$(evemex_str$)

  local evemex_pos1, evemex_pos2, evemex_res$

  evemex_pos1 = 1 
  evemex_pos2 = 1 
  evemex_res$ = ""
  	
  while (evemex_pos1 < len(evemex_str$))
    if (mid$(evemex_str$, evemex_pos1, 2) = "{{") then
      evemex_res$ = evemex_res$ + mid$(evemex_str$, evemex_pos2, evemex_pos1 - evemex_pos2)
      evemex_pos1 = evemex_pos1 + 2
      evemex_pos2 = evemex_pos1
      while (evemex_pos2 < len(evemex_str$))
        if (mid$(evemex_str$, evemex_pos2, 2) = "}}") then
           rem 
           rem  See the use of eval in the next line
           rem
	   evemex_res$ = evemex_res$ + eval$("str$(" + mid$(evemex_str$, evemex_pos1, evemex_pos2 - evemex_pos1) + ")")
	   evemex_pos2 = evemex_pos2 + 2
	   evemex_pos1 = evemex_pos2
	   break
	else
	  evemex_pos2 = evemex_pos2 + 1
	endif
      wend
    else
      evemex_pos1 = evemex_pos1 + 1
    endif
  wend

  evemex_res$ = evemex_res$ + mid$(evemex_str$, evemex_pos2, evemex_pos1 - evemex_pos2 + 1)	
  return evemex_res$

end sub
            

If the user when prompted types Marc, he is greeted with Hello Marc, your name has 4 characters. The program uses eval$ only once, and it adds str$ around the embedded expression to ensure, that the result is always a string and can be concatenated with the other strings.

Please note, that the subroutine prefixes its local variables with evemex (for eval embedded expression) to avoid name clashes with any variable that might be used in expressions within the string passed.


Name

execute() — execute a user defined subroutine, which must return a number

Synopsis

print execute("bar","arg1","arg2")

Description

The execute-function is the counterpart of the execute$-function (please see there for some caveats). execute may be used to execute subroutines, which return a number.

Example

print execute("bar",2,3)
sub bar(a,b)
  return a+b
end sub
            

This example would print out 5.


Name

execute$() — execute a user defined subroutine, which must return a string

Synopsis

print execute$("foo$","arg1","arg2")

Description

execute$ can be used to execute a user defined subroutine, whose name is specified as a string expression.

This function allows to execute a subroutine, whose name is not known by the time you write your program. This might happen, if you want to execute a subroutine, which is compiled (using the compile command) as late as of execution of your program.

Note however, that the execute$-function is not the preferred method to execute a user defined subroutine; in almost all cases you should just execute a subroutine by writing down its name within your yabasic program (see the example below).

Example

print ex