KBasic

From Bauman National Library
This page was last modified on 1 June 2016, at 16:52.
KBasic
Paradigm Multi-paradigm: reflective-oriented, Object-oriented, imperative, scripting
Designed by KBasic Software
First appeared 2000
Typing discipline Static
License LGPL
Website http://www.kbasic.org/
Influenced by
VB6

KBasic is an open source project backed by years of continual development. It comes with Java™-like object orientation and backward support for VB6 and QBasic®, as it is 100% syntax compatible, but it is not a VB6 or VB.NET™ clone! Though it comes with support for VB.NET™ syntax, functions and similar objects and classes as well. KBasic combines the expressive power of Object-Oriented languages like C++ with the familiarity and ease of use of VB6. It allows developers with an installed base of VB6 applications to start developing for a mixed Windows®, Mac® OS X and Linux® environment without having to face a steep learning curve: KBasic uses the familiar visual design paradigm and has a full implementation of the BASIC language.

KBasic programs

KBasic is made up of the following programs:

  • a development environment with visual form designer (IDE)
  • a compiler (KBC)
  • an interpreter (VM)
  • a graphical user interface component. (VM)

It’s about 15 MB source codes (C++)

It is really easy to develop multi-platform GUI applications with well known BASIC syntax in a modern fashion, because KBasic uses the familiar visual design paradigm and has a full implementation of the BASIC language. KBasic uses Qt® to provide cross-platform functionality (Qt® is the leading cross-platform technology available worldwide).

Feature Overview

On the following sections you will get know KBasic. Though I cannot describe everything in detail like in a programming book, I will describe some of KBasic’s nature and features at an expert level. Nevertheless if you know C++, VB6 or similar BASICs or Java™ you will not have difficulties to get along with KBasic. It shares many concepts of those programming languages.

  • Write once and deploy native applications for Windows®, Mac® OS X and Linux®
  • OOP RAD features deliver high productivity
  • Much cheaper than other BASIC’s
  • “backward” support for VB6 and “forward” support for inheritance and other OOP features
  • do it on multiple platforms
  • Porting existing VB6 projects is easy, because KBasic is 100% syntax compatible
  • Familiar development process, environment
  • Same syntax as VB6
  • Easy to learn: built-in Tips and language reference
  • Be more productive with OOP RAD features
  • Built-in memory management via reference counting
  • True cross-platform deployment
  • Familiar language features: OOP, single inheritance, exceptions, etc.
  • Drag & drop GUI development
  • Rich UI widgets set
  • Familiar editing features: easy and fast browsing of your source code
  • Familiar editing features II: Auto-Completion of builtin-functions and datatypes, even user defined functions and types
  • Auto-Completion (Professional version only)
  • Familiar debugging features: single step, showing variables’ values, local and global scope
  • Familiar Install/Uninstall features: for Linux® (KDE), Mac® OS X and Windows®

Feature Details

KBasic is object oriented with objects and classes, single inheritance and polymorphism and private, public, protected scope of objects’ elements

KBasic is syntax compatible to old BASICs like QBasic® or VB6

  • optional parameter
  • paramarray
  • named arguments [mySub(param1 := 23, param2 := 100)]
  • on error goto
  • label and goto
  • variable naming (with shortcuts like name$ or n%)
  • property handling
  • primitive variables also arrays and user defined types can be passed to functions by reference
  • KBasic contains a virtual machine
  • automatic garbage collection
  • protected data and arrays
  • modern error management through exception handling

KBasic is not only one programming language but is also three languages. Through one of the following command you can switch KBasic into one mode.

  • If you want to use KBasic newest features (Default) use OPTION KBASIC
  • If you want to use old VB6 code use OPTION OLDBASIC
  • For very old BASIC code like QBasic you should use: OPTION VERYOLDBASIC

It is possible to use all three modes in one of your program, e.g. one module uses one mode and the other module of your program use another mode. Just place one of these lines in top of your module. Default is OPTION KBASIC.

Of course like other programming languages, KBasic comes with commands for control flow, conversion/casts, error handling, events and library functions like for gui, input or output, maths and so on.

KBasic is stable

KBasic was designed to facilitate the writing of very reliable and durable software. Of course, KBasic does not eliminate the need for quality control. It is still possible to write unreliable software by using bad coding practices. However, by eliminating certain kinds of programming errors, KBasic makes it easier to write reliable software.

KBasic is a typed language. This means that KBasic can do very detailed examinations of your program for potential type inconsistencies. KBasic is more strictly typed than standard BASIC. One of the most important characteristics regarding reliability is correct memory management. By not supporting pointers, KBasic excludes the danger of accidently overwriting data in memory while a program is running. Similarly, KBasic’s garbage collector prevents memory leaks and other malicious errors with dynamic memory allocation and deallocation. In addition, the KBasic interpreter examines different things at run time, e.g. whether arrays and strings are still within their bounds. Exception handling is another new feature. An exception is a signal for a exceptional program condition, which occurs like an error. By using the try/catch/finally statements, you can place all your error processing routines in one place, making it easier to catch and fix errors.

KBasic is fast

KBasic is an interpreted programming language. Therefore, it will never be as fast as a compiled machine code language, like C. Actually, KBasic is roughly 20 times slower than C. Now, before you run away, bear in mind that this speed is fast enough for nearly all kinds of GUI applications, which often wait for the user to input something.

When analyzing the power of KBasic, you need to take into account the placement of KBasic with respect to other programming languages. On the one end are high-level, fully-interpreted languages like PHP and the UNIX-shell. These languages are very useful for creating a draft, but they are executed slowly. On the other end are the fully compiled machine code programming languages. These languages provide extremely fast programs but are not very portable or reliable.

KBasic falls between these languages. The performance of KBasic is much better than high-level programming languages, but has the ease and portability of those languages. Although KBasic is not as fast as a compiled C program, it is platform-independent, providing the ability to write stable programs for Windows, Mac OS X, and Linux.

A Simple Example

Now that you have an insight into what KBasic is all about, let us stop discussing abstract phrases and instead study a simple KBasic program. Here is the much loved and favourite “Hello World” example:

' program beginning

CLS
Print "Hello World!"
Print
Print                                  
Print "                / `._     .       .      _.' \"
Print "              '.@ = `.     \     /     .' = @.'"
Print "               \ @`.@ `.    \   /    .' @.'@ / "
Print "                \;`@`.@ `.   \ /   .' @.'@`;/  "
Print "                 \`.@ `.@ `'.(*).'` @.' @.'/   "
Print "                  \ '=._`. @ :=: @ .'_.=' /    "
Print "                   \ @  '.'..'='..'.'  @ /     "
Print "                    \_@_.==.: = :.==._@_/      "
Print "                    /  @ @_.: = :._@ @  \      "
Print "                   /@ _.-'  : = :  '-._ @\     "
Print "                  /`'@ @ .-': = :'-.@ @`'`\    "
Print "                  \.@_.=` .-: = :-. `=._@./    "
Print "                    \._.-'   '.'   '-._./      "
Print
Print "... you just ran your first KBasic program!"

Input these lines into a new KBasic code window. After running it in KBasic you will see a nice butterfly on your screen. Now let's go on to the next chapter.

What is the difference between KBasic and Visual Basic 6?

KBasic is very similar to VB6 thereby making it easy for VB6 developers to learn this new language. KBasic contains all the syntax elements of VB6 and implements controls and other components in a similar fashion to VB6. There are also some important differences between KBasic and VB6, such as the pre-processor and exception handling. Furthermore, KBasic provides additional object-oriented features and extensions, making it a true object-oriented programming language. This is one of the major differences between KBasic and VB6.

A KBasic program may consists of one or more classes, modules, forms, functions, or subroutines. As with VB6, it is possible to have global namespaces, functions, subroutines, and variables. KBasic does not support pre-processor commands (e.g. #ifdef, #if, etc.), but this feature is planned for the future. However, in theory, pre-processor commands like this are not needed because KBasic is a platform-independent programming language and, therefore, does not have platform-related dependencies. Furthermore, the simple data types are the same except that their size might change. Changed sizes might be:

  • Boolean 1 byte
  • Integer 32 bits
  • Long 64 bits

KBasic Syntax

Declaration of Variables

Before using variables, you must declare them. You must define the name and the data type of a variable. The 'Dim'-statement declares a variable. 'Dim'-statements are one of many variable declaration statements, which slightly differs from the others. Other declaration statements are 'Redim,' 'Static,' 'Public,' 'Private,' 'Protected,' and 'Const'.

Dim myName As String

Variables can be declared everywhere in procedures, functions, and subs, not only at the top of procedures, functions, and subs. However, most or the time they are at the top.

Use the following rules to name procedures, functions, subs, constants, variables, or arguments in KBasic:

  • Use a letter (A-Z, a- z) or underscore (_) as your first character
  • Never use whitespace ( ), period (.), exclamation mark (!), or the following characters : @, &, $, #, „ in your names.
  • The name may contain numbers but must not start with a number
  • Do not use names already in use by predefined elements of the KBasic language, such as keywords (e.g. 'If'), built-in functions (e.g. 'Print'), classes etc. This would lead to a name collision in which the original language element would be expected. Your program will not compile.
  • You cannot use variables with the same name in the same scope. e.g. you cannot declare variable 'age' two times in a procedure, but you can declare 'age' in a procedure and in a module at the same time because they are declared in different scopes (at different places).

Lifetime of variables

The lifetime of variables is the time in which the variable exists or has a value. The value of a variable can be changed during its lifetime. If a variable is outside its scope, it has no value. If a procedure is executed, a variable exists after its 'Dim'-statement. Local variables exists until the procedure is completed; after reentering the procedure all variables are created again after their respective 'Dim'-statements.

If you do not change the value of a variable during its lifetime in a program, it contains the initialized value at program start. A variable declared in a sub contains an assigned value until the sub is left. If the same sub is called again, the value is reset to the initialized value.

When using static-declared variables in procedures, the variables only exist once in memory, unless the procedure is called multiple times using recursion. If you use global-declared module variables or class-variables, it is the same. The variables exist once in memory at runtime. If you use instance-variables you must consider that they only exist together with the instance (object) to which they belong.

Functions

Functions are very similar to subs in that both are procedures, but functions return a value and can be used in expressions.

Syntax:

Function Name([Arguments])[As Type]
  [Statements]
End Function

Function Name([Arguments])[As Type] [Throws Name, ...]
  [Statements]
End Function

The arguments of a function-procedure are used as the arguments of a sub-procedure. Define a function-procedure by using the keyword 'Function.'

Classes

A simple application can contain a form, while all source code is inside the form module of that form. But if the application grows bigger and bigger it might be useful, to write source codes from different forms at one place, so you need a place to write the source codes down outside the forms. Here comes the classes. Create a class, which contains a methods, which is useful for your forms. You KBasic code is stored in classes or modules. You can archive your code within classes. Every class consists of the declaration part and the methods you have inserted. A class can contain:

  • Declarations - for variables, types, enumerations and constants
  • Methods (also called procedures) - which are not assigned to a special event or object. You can create as many procedures as you want, e.g. sub-procedures without return value or function-procedures.
  • Signal/Slots-Methods - These are special methods, which are only useful together with the bindings. See the documentation of the bindings in the KBasic IDE for more information.
  • Properties - Are variables, which are accessed through two special methods (get and set method). Properties are accessable without the need to write braces, when you use them.

Syntax:

[Abstract] Class Name Inherits ParentClassName

  [Static] Dim Name As Type
  [Static] Public Name As Type
  [Static] Protected Name As Type
  [Static] Private Name As Type
  Const Name As Type
  Public Const Name As Type
  Protected Const Name As Type
  Private Const Name As Type
  ...

  [Public | Protected | Private] 
  Enum Name
    Name As Type
    ...
  End Enum
  ...

  [Public | Protected | Private] 
  Type Name
    Name As Type
    ...
  End Type
  ...

  [Public | Protected | Private]  
  Property Name As Type 

    Get
      [Statements]
    End Get 

    Set(Argument) 
      [Statements]
    End Set 

  End Property 
  ...

  [Public | Protected | Private] 
  Constructor Name([Arguments])
    [Statements]
  End Constructor
  ...

  [Public | Protected | Private] 
  Destructor Name( ) 
    [Statements]
  End Destructor

  [Static] [Public | Protected | Private] 
  Function Name([Arguments]) [As Type] [Throws Name, ...]
    [Statements]
  End Function
  ...

  [Static] [Public | Protected | Private] 
  Sub Name([Arguments]) [Throws Name, ...]
    [Statements]
  End Sub
  ...

  [Public | Protected | Private] 
  Slot Name([Arguments])
    [Statements]
  End Slot
  ...

  [Public | Protected | Private] 
  Signal Name([Arguments])
    [Statements]
  End Signal
  ...

End Class
Bigger example:

Class Salsa Inherits Waltz

  Public Enum class_enum
     Entry
     Entry2
     Security = Entry
  End Enum 

  Public Type class_type
    element As Integer
  End Type 

  Const classConst = 4

  Public publicInstanceVar As Integer
  Private privateInstanceVar As Integer 
  Protected protectedInstanceVar As Integer 

  Static Public publicClassVar As Integer
  Dim publicModuleType As module1.module_type
  Dim publicModuleType2 As module_type

  ' parent constructor call inside constructor

  Sub meExplicit()
    Dim localVar = Me.publicInstanceVar ' it is the same with parent
    Dim localVar2 = Me.publicClassVar  
    Dim localVar3 = Salsa.publicClassVar 
    Dim localVar4 = Salsa.classConst 
    Dim localVar5 = Me.classConst 
'    
    Dim localVar6 As class_enum 
    localVar6 = Salsa.class_enum.Entry 
'    Dim localVar7 As Me.class_enum   '  full type name not allowed 
    Dim localVar8 As class_type 
  End Sub 

  Sub meImplicit()
    Dim localVar = publicInstanceVar
    Dim localVar2 = publicClassVar 
    Dim localVar3 = classConst 
    Dim localVar4 As class_enum 
    Dim localVar5 As class_type

  End Sub   Sub classSub()
    Const localConst = 6
    Dim n = localConst
  End Sub 

  Sub classSubWithArgument(i As Integer)
    Dim localVar = i
  End Sub   Function classFunction() As String
    Return "hello"
  End Function 
  Static Public Sub test() Throws Waltz   
    Throw New Waltz     
  End Sub   Private pvtFname As String   Public Property Nickname As String 

    Get
      Print "Hi"
    End Get 

    Set ( ByVal Value As String ) 
      Print "Hi"
    End Set 

  End Property End Class

References

  1. KBasic

The article is written by Makarov D. V.