Наши официальные канал и чат в telegram, группа в ВКонтакте

Документация

Yabasic


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.90 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 (me !) 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. See the section about creating a standalone-program for details.

--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
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 print-command 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 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 the user (or from a 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 print-command 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 information
peek$
retrieve various internal string-information
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:\yabasic\yabasic.exe (the usual 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 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. 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.

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