1.1 First this
The Survival Guide is (in)frequently updated... whenever I feel like it :-) I will try to mark all major changes to the previous version of the Survival Guide in red. I'm bound to miss something, or make mistakes. These pages have been written over time, with different versions of PureBasic and Windows.
Some sections may no longer apply, or work differently with newer versions of PureBasic or Windows! Check!
Here's how to check how old code and examples are, and perhaps that might help you to see if if the examples and explanations still apply:
On October 5, 2003, the user BluezNL posted the following:
I put most of my stupid mistakes together on a page, a sort of survival guide... :wink:And it's been 14 years since!
Feel the Pure Power!
PureBasic exists in different flavours and versions (Windows, Linux, Mac OS-X, Amiga). In this guide I will limit myself to PureBasic for Windows. (The Windows version is perhaps the most mature, but the Linux and Mac versions are getting better every day.)
These pages help you getting started with the Windows version of PureBasic, which is a programming language. (Duh! I bet you didn't see that one coming!). These pages started as a form of self help, then turned into a sort of tutorial / reference / snippet collection, and now have become... euh... a mess I guess :-) And they have been a mess for the last decade...
note that this is not an official guide, and that I am in no way
part of the official PureBasic team. All mistakes are mine (except those
made by others, of course :-)) Consider this work a tribute to the great
work AlphaSound & Co did.
How this document is organized
These pages are spread over five seperate sections (with a bit of historic overlap and duplication):
0 - Table of Contents - search this space for specific keywordsIf you're an experienced user / programmer, read on. If things look confusing or complicated you may want to go to the Primer pages.
It's Basic, Jim. But not as we know it
No. I am not going to tell you how to program, or how to learn Basic (well, perhaps a little). I am only going to point out some things that caused me loads of problems due to misunderstandings. Some of it might be obvious to you, but not to me at the time... (Which was my prime motivation to write this guide.)
This thing called PureBasic is different... But that doesn't mean this is a bad programming language, or that basic itself is a bad programming language. It just depends what you are going to do with it. I switched over to PureBasic (or PB or Pure as it is lovingly called) when my previous language of choice GfaBasic disappeared...
PureBasic does have its own flavour though...
Don't listen to anybody who says any programming in Basic is bad, that any program in Basic resembles a plate of spaghetti, and that Basic is oh so slow. What counts is not the language a program is written in, but how well a program does what it is supposed to do. (And I would like to invite the sceptics to have a good look at the aspects of any modern 'Basic' language. They might be in for a surprise.)
One word of warning though: PureBasic is a procedural language, not an object oriented language.
are some user created pre-processors, and perhaps one day there will be
a little OOP (though I would not hold my breath as the developers have
said 'no' more than once). Fortunately, it is still very usable.
What it is
PureBasic? Well. A programming language. It's a kind of Basic (check WikiPedia) with it's own deviations from the standard syntax.
PureBasic costs 79 euro (in August 2008 it was 79 euro, and in April 2016 it was still 79 euro!) and can be bought here. You can use a credit card or euro cheque. Buying the official full version includes life time updates. So better be fast before the developer changes his mind regarding the license scheme!
There is also a demo version available so you can try before you buy. Go to purebasic.com for more information, download and try. The demo version has a number of limitations, of which the most obvious is the lack of WinApi support (that's any command ending on an underscore).
Don't worry. I don't get any money for this free plug. So let's hit the road and see what this baby can do...
install simply run the downloaded executable. That's it. You should be
able to install it over any older version, but I'd rather not take chances.
As it's so small, installing is a breeze, and it definitely doesn't hurt
to keep a copy or two around.
In the past I suggested the use of JaPBe, but I guess JaPBe is now a thing of the past, as the included editor (since 4.20 or so) does a fine job. The PB editor has been adopting many features of JaPBe, honoured some user requests, and now includes some functionality that was provided by third party applications in the past (such as my own CodeCaddy).
Planning to do some programming using WinApi calls? Then you'll might find some use for these:
(Note: there are three versions of the win32.hlp file... an old one dating back to 1996 with all images removed (approx. 12 MB), a re-edited one (approx. 24 MB) which includes all images and some additional WinApi descriptions, and somewhere (although I've never seen it) must be the original file... It doesn't matter much which one you use though.)
A similar thing can be done for inline assembly:
You can now type some assembly and hit F1 for more info on that instruction. I don't know why, but for some people F1 does launch WIN32.HLP but not ASM.HLP... strange. You can still access those help files from the IDE using Help / External help.
Here's a little example to test it with:
Keep in mind that the WIN32.HLP file is old... If you need all information on all API's, in particular the newer ones, it's probably better to check on the Internet, and / or download the MicroSoft Platform SDK. You should be able to find most (if not all) of this information online as well, on msdn.microsoft.com. If you still want to use .HLP files on Vista, Windows 7, 8 or 10, you will have to download and install winhlp32.exe from MicroSoft. You will be prompted by an error message the first time you try to open a .HLP file, which will then allow you to download the right program.
PureBasic was traditionally a bit lacking in the documentation and tutorials department, but things have improved greatly since 4.00, have a good look at the included help file (F1).
On the PureBasic website you will find a 1200+ page .PDF file called (surprisingly) PureBasic.PDF. I suspect it's the same thing as the onboard help file PureBasic.CHM, but obviously I haven't checked all those 1200 pages :-)
There is some good stuff to be had at purearea.net but be aware, some is in German, and some examples are based on older versions of PureBasic.
Kale was so kind to offer his PureBasic Beginner's Guide for free. It may not be entirely up-to-date with the latest version of PureBasic, but it's a very good source of information. I've added a copy here.
Yet, in my opinion, the ultimate source of wisdom is the PureBasic forum. Feel free to ask stupid questions. I've done that more than enough myself :-) Please note that on the forum there may be a lot of older code floating around, as there were quite a few improvements over time, but its relatively easy to rewrite them.
I guess it's pretty much inspired by JaPBe (which itself was based upon an earlier version of the standard PB editor itself) and though at one time it was rather limited it has become my editor of choice.
To fold or unfold use the plus or minus boxes behind the line number, or use [F4].
In the IDE you can specify what can be folded, this is a great way to be able to fold enumeration or data section blocks! See the menu item File / Preferences / Editor / Folding.
Yeah, the IDE can now format your code 'on the fly', as well as upon your request. Highlight a section of your code and hit [Ctrl] + [I].
When typing code, the IDE will show you 'possibilities', ie. commands, variable names, procedure names, structure members etcetera. What is shown, can be set here: File / Preferences / Editor / AutoComplete.
I prefer to display everything in the AutoComplete list except for ASM keywords and Interfaces. I also prefer to use [Esc] and [Enter] for escaping and selecting the suggested word. These shortcuts can be set under File / Preferences / General / Shortcuts, where you will find at the bottom of the list the options 'Close the AutoComplete Window' and 'Insert the selected AutoComplete Word'.
Yes! Finally :-) Segments of code can be spread over multiple lines, like this:
x.s = "b" + ; comments are allowedIf a line of code ends on a plus, minus, pipe, And, Xor, Or, then it will be regarded as a multiline statement.
used a different approach, but the two do not bite each other.)
Online syntax check
Sorry GfaBasic users. No such thing.
It seems at one time an online syntax check was in the plans, but it got shelved in favour of other goals.
As of 5.50 (5.40?) PureBasic keeps a copy of old versions of your code in a local database. This is great if you accidentally edited your code, and need to retrace your steps because something broke... (And you know that does happen, don't you?)
You can find this function under File / Session History. The help file did not include any details, but you can configure this function via File / Preferences / Editor / Session History and that helps to explain the mechanism. Of course, Session History is no replacement for backups!
here is an (incomplete) list of PB IDE vs. JaPBe shortcuts... You can change
all the PB IDE shortcuts though. Some functions do not exist in the PB
IDE, others do not exist in jaPBe.
that you can change (almost?) all keyboard shortcuts yourself, go to File
/ Preferences / General / Shortcuts.
The next section is aimed at more experienced programmers that just want to have a peek at PureBasic's features. Because they consider switching over, or have done so already.
If things are unclear consider reading the Primer first.
Most of the regular commands are here. If you've been gone for a long time you might notice that PureBasic does not use line numbers... just kidding, you already knew that :-) If you didn't, better start with the Primer first... (This page is about to get somewhat dense.) I am even considering a 'total beginners guide to basic' but that's not there yet, and may never be...
Okay, some characteristics so you know what you can expect...
Pure compiles top to bottom. In other words, if you want to use something you got to define it first. The following will compile:
; survival guide 1_4_100 code orderAnd this will not compile:
test1() ; can't compile as test1() is not yet defined... unless you tell the compiler that something is coming up by using Declare().
; survival guide 1_4_101 code order
Procedures and functions
Functions and procedures are treated the same way.
Call a procedure :
Procedure test3()Call a procedure (function) and retrieve the return value:
Procedure.l test4() ; tell the compiler what type of variable will be returnedCall a procedure with a value:
Procedure.l test5(a.l) ; what goes out and what goes in...
Procedure parameters and the stack
PureBasic uses the same approach as C for passing parameters on to a procedure. Parameters are pushed on the stack from right to left. In most cases it doesn't matter, but it is something to be aware of:
Procedure.l test6(x.l)Here's another example, this one illustrates the difference between expression evaluation (left to right) and parameter passing (right to left):
Procedure.l d(x.l)It will list 1, 2, 3, then 3, 2, 1.
During development, the Debug command comes in handy... It will display text or variables in a dedicated debug window.
Debug "test message"(Follow this link for more ifnormation on the debugger.)
For console applications (Dos prompt stuff or simple things that don't need a real 'Windows window', you can use the console. To generate a real 'console' application, you have to set under compiler options the executable format to 'console'. The Print() command only works on a console.
OpenConsole()Obviously, 'normal' Windows applications have to open a window first to display any output. Obviously there are commands in PureBasic to do so. See all stuff on windows and gadgets.
Before digging in: if you're a beginner then stick to three variations: .a for bytes from memory, .d for floating point calculation (antything with fractions) and .i for everything else.
When used the first time, you tell the compiler what type a variable is. Most numeric types are 'signed' but as of 4.40b1 some new unsigned types have shown up.
; survival guide 1_5_100 variables and expressionsWhen you reuse a variable, you don't have to specify its type again.
a.l = 1 ; the first time, so say what it isThe default type is .i or 'integer'. The size of .i depends on the platform / compiler version!
a = 1 ; no type defined so it's an integerYou cannot use the same name for different variable types. In most other basics you could say:
a$ = "appel"Not so in PureBasic:
a.s = "appel"But the following is allowed...
a$ = "appel" ; the $ is considered part of the name AND turns 'a$' into a string variableNote that * and $ are the exception. (Think of them as being part of the variable name AS WELL AS type definition if that makes you happier :-))
a.s = "appel"Most numeric variables are signed! This can cause some surprises if you don't pay attention.
; survival guide 1_5_101 signed and unsigned(Don't forget, to use PrintN() we need a console to be open!)
PureBasic has a specific way of dealing with type conversion and expression evaluation, which is described in more detail here.
All regular strings are zero terminated and cannot contain a null character (asci code 0). If they contain a zero, they will be truncated! If you are in a habit of using strings as buffers for binary content (that could contain one or more zero's) you will have to use so called 'fixed length strings' or do the right thing and just allocate memory...
Pre 5.50 Purebasic would offer two modes: Unicode and Ascii. In Ascii mode the string "ABC" would occupy 4 byes, 1 for each character, and a terminating zero:
text A B C 0In Unicode mode, all characters in memory occupy TWO bytes each, plus two terminating zeroes. For simplicty this would look something like this:
text A B C 0In other words, eacht character in a Unicode string occupies two bytes, and ends on a pair of two zeroes.
As of v4.00 there is a new type of string, the fixed length string, as well as a single character a sort of 'string companion / byte alternative' called char or .c.
a.s = "this is a test" ; variable size, zero terminated, cannot contain null charactersFixed length strings are expecially useful in certain structures and when calling external code libraries. (Those that dealt with old ISDN / TAPI / CAPI know what I mean.) The use of fixed length strings in structures may have been reduced now PureBasic no longer supports Ascii only strings, invalidating stuch structures, but they still have one use: when part of a structure, the string data is stored inside the memory space used by that structure, whilst a normal string would be a pointer towards the string data instead of the data itself.
There is no boolean type. Instead, use an integer: 0 is false, <> 0 is true.
As of 5.11 there's the new command Bool(). It returns #True or #False, depending on the expression:
; survival guide 1_5_102 booleansLife wouldn't be great if we couldn't say no :-) So there's NOT and it's boolean brethern to help us out.
a = (a = b) does not work. Don't even try or ask for it. Don't. Please. Don't. Ask. Ever. PureBasic is not C or C++. It just won't work. Don't ask for it. Please.
If you're a beginner you shouldn't be here at all! Please continue with the primer first and do not hang around here!
Still here? Well, you've asked for it...
If a regular string is a member of a structure, then the structure itself does not contain the actual string but a pointer to that string. If you want the string to be part of the structure, you have to use fixed length strings.
; survival guide 1_5_103 structuresIf you want to have a 'fixed length' string as part of a struct, you either create an array of chars (that sounds a little like c++), or use a fixed length string.
Here's how to do it with an array of chars. The show() procedure shows how this is stored into actual memory:
; survival guide 1_5_104 array of charsYou could replace an array of chars with a twice as large array of bytes, ie. replace y.c with y.b.
An alternative would be to use a fixed length string:
; survival guide 1_5_105 array of chars
Sometimes Pure does things in its own way. One of these things is the way expressions are evaluated, for example...
a.l = 2/3 + 2/3Surprised? Find out in detail what happens right here...
Make life easier
This is advanced stuff. Skip it if you're not into this (yet)...
A lot of standard windows functions are declared. Use the windows function name, add an underscore at the end of the name and try it!
If PureBasic knows the function, it will automatically open the appropriate dll and you don't have to use the OpenLibrary() function. (Even if the editor or jaPBe doesn't recognize the api, the compiler often does. Try to use it, and if there's an error then open the library (DLL) yourself.
demo version does not support Winapi calls!
In PureBasic on 32bit windows you don't have to force the type when calling a Winapi function. (In fact, you cannot even force the type in PureBasic.) So, when the function in WIN32.HLP tells you that the first parameter is a word, you don't bother and just pass it an integer ( or a quad, long, word, or byte) as you feel fit. Same goes for returning values, although obviously they have to fit.
A DLL that is not defined by PureBasic has to be opened by hand. Here's what you do:
1. Open the library using OpenLibrary().
ws_winsock_h.i = OpenLibrary(ws_winsock_pbh,"WSOCK32.DLL") ; load the DLL and get back the DLL handle2. Look for the function you need with GetFunction()...
*ws_wsastartup = GetFunction(ws_winsock_pbh,"WSAStartup") ; find the address of the function3. GetFunction() returned an address. Use that address as a parameter for CallFunctionFast() and pass the appropriate parameters.
ws_retval.i = CallFunctionFast(*ws_wsastartup,$101,@ws_wsadata)All together now:
ws_wsadata.WSADATA ; prepare a structureThe code above is only to illustrate the approach. Don't forget to close the library before ending your program. An alternative way is using CallFunction() or by using function pointers / prototypes. See here for more details.
Former GfaBasic users look here... some of those things might be of interest to people used to other dialects as well.
Over time I have asked some (stupid) questions regarding PureBasic... or witnessed those of others :-) Here are some of the answers that *might* be useful to you...
Q. I've seen a cheaper version on the internet!
A. Quite possible. PureBasic was available in other (boxed) versions as well, but only the 'expensive' version gets the lifetime free updates. All the 'boxed' 'editions' are worthy of some suspicion, so check on purebasic.com and the forums before buying anything! (In fact, there's no reason whatsoever to buy such a box, as those are old versions without a right to upgrade.)Q. Where can I find a list of all PB constants?
A.Open the structure viewer (from the tools menu in the editor) and select the constants tab.Q. And Windows constants?
A. Look around on the internet, there should be enough lists and utilities floating around... The Windows SDK is one option.Q. Nice, those files with all the constants, but they are very large and load slowly. Or I can't even read them...
A. Go to the Total Commander site and download lister.exe. In the standard editor as well as jaPBe you can add your own tools / config tools. Use path+lister.exe in the command line and path+filename for the file you want to view. Lister is fast and smart. And, while you are on the Total Commander site... register it. It's worth it. This shameless plug doesn't make me any money... (No money again? Damn!) As an alternative you could download CodeCaddy. (And that's another shameless plug that doesn't make me any money, I have to get smarter...)Q. So, PureBasic has loads of constants pre-defined... and structures too... or not?
A. How right you are. Browse through those files with constants, and you'll run into the structures as well. But, PureBasic offers you a nice boon. Hit [Alt] + [S] and you can browse through all predefined structures, including their fields. That will save you quite some time. (There were a few errors in the default structs though so check them before using them.)Q. What's an unsigned short?
A. A word. (Yes, I know, this is not entirely true. Don't bother.)Q. Why can't I find EventWParam() in the help file?
A. It's a command that's Windows specific and might disappear one day. Although it's not very likely it will disappear anytime soon so don't worry too much :-)Q. How can I check if a file exists?
A. Use the FileSize() function (it was listed in the newbies faq, and I still asked the question, yes, I'm thick too)...Q. Why does <whatever> not work?
A. Check out the FAQ on the forum, and do a search there.Q. Why does a = (a = b) not work?
A. PureBasic isn't C++. It just doesn't work. Don't even try or ask for it.
There are tons of questions and answers to be found on the forum... Make sure you read the faq and do a search on that forum before posting a question! (Fortunately, it's a very understanding community, hum :-) Just remember, the best answers are those you found yourself... Also the Primer may just address that one stupid question you were always afraid to ask...
Note: please make sure you use the right version of PureBasic, or be prepared for some decent DIY as some of those samples may be quite old!
to AlphaSnd / Fred, Fr34k / Freak, GPI, Inner, Pupil, Rings, Saboteur,
TerryHough, TheFool, WolfgangS, and all those other people I forgot to