{{fbdoc item="title" value="ABS"}}---- Calculates the absolute value of a number {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Abs** [[KeyPgOverload overload]] ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Abs** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgLongint longint]] ) [[KeyPgAs as]] [[KeyPgLongint longint]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Abs** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgDouble double]] ) [[KeyPgAs as]] [[KeyPgDouble double]] ## {{fbdoc item="usage"}}## result = **Abs**( //number// ) ## {{fbdoc item="param"}} ##//number//## Value to find the absolute value of. {{fbdoc item="ret"}} The absolute value of ##//number//##. {{fbdoc item="desc"}} The absolute value of a number is its unsigned magnitude. For example, ##Abs(-1)## and ##Abs(1)## both return ##1##. The required ##//number//## argument can be any valid numeric expression. ##Abs## returns its value as the same data type as the argument ##//number//##. The ##**Abs**## unary ##[[KeyPgOperator operator]]## can be overloaded with user defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/math/abs.bas"}}%%(freebasic) dim n as integer print Abs( -1 ) print Abs( -3.1415 ) print Abs( 42 ) print Abs( n ) n = -69 print Abs( n ) %% Output: %% 1 3.1415 42 0 69 %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgSgn Sgn]]## - ##[[KeyPgOperator Operator]]## {{fbdoc item="back" value="CatPgMath|Math"}}{{fbdoc item="title" value="ACCESS"}}---- Clause of the ##[[KeyPgOpen Open]]## statement to specify requested privileges {{fbdoc item="syntax"}}## [[KeyPgOpen open]] //filename// for [[KeyPgBinary binary]] **Access** {**Read** | **Write** | **Read Write**} as [#]//filenum// ## {{fbdoc item="usage"}}## open //filename// for binary **Access Read** as #//filenum// open //filename// for binary **Access Write** as #//filenum// open //filename// for binary **Access Read Write** as #//filenum// ## {{fbdoc item="param"}} ##Read## Open the file with only read privileges. ##Write## Open the file with only write privileges. ##Read Write## Open the file with read and write privileges. {{fbdoc item="desc"}} ##Access## is used with the ##[[KeyPgOpen Open]]## statement to request read, write, or read and write privileges. If the ##Access## clause is not specified, ##Read Write## is assumed. {{fbdoc item="ex"}} This example shows how to open the file "data.raw" with ##[[KeyPgReadFile read]]## and then "data.out" with ##[[KeyPgWriteFile write]]## access, in ##[[KeyPgBinary Binary]]## mode, in an open file number returned by ##[[KeyPgFreefile FreeFile]]##. {{fbdoc item="filename" value="examples/manual/fileio/access.bas"}}%%(freebasic) Dim As Integer o '' get an open file number. o = FreeFile '' open file for read-only access. Open "data.raw" For Binary Access Read As #o '' make a buffer in memory thats the entire size of the file Dim As uByte file_char( Lof( o ) - 1 ) '' get the file into the buffer. Get #o, , file_char() Close '' get another open file number. o = FreeFile '' open file for write-only access. Open "data.out" For Binary Access Write As #o '' put the buffer into the new file. Put #o, , file_char() Close Print "Copied file ""data.raw"" to file ""data.out""" Sleep %% {{fbdoc item="diff"}} - None known. {{fbdoc item="see"}} - ##[[KeyPgOpen Open]]## - ##[[KeyPgReadFile Read]]## - ##[[KeyPgWriteFile Write]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}}{{fbdoc item="title" value="ACOS"}}---- Finds the arccosine of an angle {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""Acos""** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgDouble double]] ) [[KeyPgAs as]] [[KeyPgDouble double]] ## {{fbdoc item="usage"}}## //result// = Acos( //number// ) ## {{fbdoc item="param"}} ##//number//## A cosine value in the range [-1..1]. {{fbdoc item="ret"}} The arccosine of ##//number//## in radians, in the range [0..Pi]. {{fbdoc item="desc"}} ##Acos## returns the arccosine of the argument ##//number//## as a ##[[KeyPgDouble Double]]## within the range of 0 to [[TutMathAngles Pi]]. The arccosine is the inverse of the ##[[KeyPgCos Cos]]## function. The returned angle is measured in [[TutMathAngles radians]] (not [[TutMathAngles degrees]]). {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/math/acos.bas"}}%%(freebasic) DIM h AS DOUBLE DIM a AS DOUBLE INPUT "Please enter the length of the hypotenuse of a triangle: ", h INPUT "Please enter the length of the adjacent side of the triangle: ", a PRINT "" PRINT "The angle between the sides is"; ACOS ( a / h ) SLEEP %% The output would look like: %% Please enter the length of the hypotenuse of a triangle: 5 Please enter the length of the adjacent side of the triangle: 4 The angle between the sides is 0.6435011087932843 %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Acos""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgCos Cos]]## - [[TutMathIntroTrig A Brief Introduction To Trigonometry]] {{fbdoc item="back" value="CatPgMath|Math"}}{{fbdoc item="title" value="ADD"}}---- Parameter to the ##[[KeyPgPutgraphics Put]]## graphics statement which selects addition as the blitting method {{fbdoc item="syntax"}}## **Put** [ //target//, ] [ STEP ] ( //x//,//y// ), //source// [ ,( //x1//,//y1// )-( //x2//,//y2// ) ], **Add**[ ,//multiplier// ] ## {{fbdoc item="param"}} ##**Add**## Required. ##//multiplier//## Optional value between 0 and 255. The source pixels are premultiplied by ##(//multiplier// / 256)## before being added. If omitted, this value defaults to 255. {{fbdoc item="desc"}} ##**Add**## selects addition as the method for blitting an image buffer. For each source and target pixel, the values of each respective component are added together to produce the result. The addition is saturated - i.e. if the sum of the two values is 256 or more, then it will be cropped down to 255. This method will work in all color modes. Mask colors (color 0 for indexed images, magenta (##[[KeyPgRgb RGB]](255, 0, 255)##) for full color images) will be skipped, though full color values of 0 (##[[KeyPgRgba RGBA]](0, 0, 0, 0)##) will have also have no effect. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/put-add.bas"}}%%(freebasic) ''open a graphics window screenres 320, 200, 16 ''create a sprite containing a circle const as integer r = 32 dim c as any ptr = imagecreate(r * 2 + 1, r * 2 + 1, 0) circle c, (r, r), r, rgb(255, 255, 192), , , 1, f ''put the sprite at three different multipier ''levels, overlapping each other in the middle put (146 - r, 108 - r), c, add, 64 put (174 - r, 108 - r), c, add, 128 put (160 - r, 84 - r), c, add, 192 ''free the memory used by the sprite imagedestroy c ''pause the program before closing sleep %% {{image class="center" title="Put Add example output" url="/images/add.png"}} {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} -##[[KeyPgTransGfx Trans]]## -##[[KeyPgAlphaGfx Alpha]]## -##[[KeyPgCustomgfx Custom]]## - ##[[KeyPgPutgraphics Put (Graphics)]]## {{fbdoc item="back" value="CatPgGfx2D|2D Drawing Functions"}}{{fbdoc item="title" value="ALIAS"}}---- Clause of the ##[[KeyPgSub Sub]]## and ##[[KeyPgFunction Function]]## statements that provides an alternate internal name {{fbdoc item="syntax"}}## [[[KeyPgDeclare declare]]] { [[KeyPgSub sub]] | [[KeyPgFunction function]] } //usablename// **Alias "//alternatename//"** (...) ## {{fbdoc item="usage"}}## declare sub //usablename// Alias "//alternatename//" ( ... ) ##//or//## declare function //usablename// Alias "//alternatename//" ( ... ) ##//or//## sub //usablename// Alias "//alternatename//" ( ... ) ... end sub ##//or//## function //usablename// Alias "//alternatename//" ( ... ) ... end function ## {{fbdoc item="desc"}} ##Alias## gives an alternate name to a procedure. This alternate name cannot be used within the program to call the procedure, but it is visible (if the function is not private) to the linker when linking with code written in other languages. ##Alias## is commonly used for procedures in libraries written in other languages when such procedure names are valid in the other language but invalid in BASIC. When using ##Alias## with ##[[KeyPgDeclare Declare]]##, only the alternate name is used by the linker. Differently from normal procedure names, ##Alias## does not change the case of the alternate name, so it is useful when external code requires an exported function with a particular name or with a particular case. {{fbdoc item="ex"}} If there is a sub called ##xClearScreen## in an external library and you want to reference it with the name ##""ClearVideoScreen""##, here is sample code to do so: {{fbdoc item="filename" value="examples/manual/procs/alias.bas"}}%%(freebasic) DECLARE SUB ClearVideoScreen ALIAS "xClearScreen" () %% A procedure meant to be used by external C code, exported as ##""MyExportedProc""##: {{fbdoc item="filename" value="examples/manual/procs/alias2.bas"}}%%(freebasic) FUNCTION MultiplyByFive CDECL ALIAS "MyExportedProc" (BYVAL Parameter AS INTEGER) AS INTEGER EXPORT RETURN Parameter * 5 END FUNCTION %% {{fbdoc item="diff"}} - In QB, ##Alias## only worked with ##[[KeyPgDeclare Declare]]##. {{fbdoc item="see"}} - ##[[KeyPgDeclare Declare]]## - ##[[KeyPgExport Export]]## {{fbdoc item="back" value="CatPgProcedures|Procedures"}}{{fbdoc item="title" value="ALLOCATE"}}---- Allocates a block of memory from the free store {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Allocate** ( //size// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] ## {{fbdoc item="usage"}}## //result// = **Allocate**( //size// ) ## {{fbdoc item="param"}} ##//size//## The size, in bytes, of the block of memory to allocate. {{fbdoc item="ret"}} If successful, the address of the start of the allocated memory is returned. Otherwise, if the requested block size could not be allocated, or if ##//count// < 0##, then the null pointer (##0##) is returned. {{fbdoc item="desc"}} Attempts to allocate, or reserve, ##//count//## number of bytes from the free store (heap). The initial value of newly allocated memory is unspecified. The pointer that is returned is an [[KeyPgAny any]] [[KeyPgPtr ptr]] and points to the start of the allocated memory. This pointer is guaranteed to be unique, even if ##//count//## is zero. Allocated memory must be deallocated, or returned back to the free store, with ##[[KeyPgDeallocate Deallocate]]## when no longer needed. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/memory/allocate.bas"}}%%(freebasic) '' This program uses the ALLOCATE(...) function to create a buffer of 15 integers that is '' then filled with the first 15 numbers of the Fibonacci Sequence, then output to the '' screen. Note the call to DEALLOCATE(...) at the end of the program. const integerCount as integer = 15 '' Try allocating memory for a number of integers. '' dim buffer as integer ptr buffer = allocate(integerCount * sizeof(integer)) if (0 = buffer) then print "Error: unable to allocate memory, quitting." end -1 end if '' Prime and fill the memory with the fibonacci sequence. '' buffer[0] = 0 buffer[1] = 1 for i as integer = 2 to integerCount - 1 buffer[i] = buffer[i - 1] + buffer[i - 2] next '' Display the sequence. '' for i as integer = 0 to integerCount - 1 print buffer[i] ; next deallocate(buffer) end 0 %% Output is: <<## 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377##>> ::c:: It is important to free allocated memory if it's not going to be used anymore. Unused memory that isn't freed is simply wasting memory, and if the address of that memory is somehow overwritten or forgotten, that memory can never be freed (this condition is known as a memory leak, and should be avoided at all costs). The following example demonstrates a function with a memory leak, where the address of allocated memory is lost, never to be freed (if this function is called frequently, the memory that is wasted can add up quickly). {{fbdoc item="filename" value="examples/manual/memory/allocate2.bas"}}%%(freebasic) sub AllocateExample2() dim p as byte ptr = 0 p = allocate(420) '' assign pointer to new memory p = allocate(420) '' reassign pointer to different memory, '' old address is lost and that memory is leaked deallocate(p) end sub AllocateExample2() end 0 %% {{fbdoc item="target"}} - This procedure is not guaranteed to be thread-safe. {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Allocate""**## {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgCallocate Callocate]]## - ##[[KeyPgReallocate Reallocate]]## - ##[[KeyPgDeallocate Deallocate]]## {{fbdoc item="back" value="CatPgMemory|Memory Functions"}}{{fbdoc item="title" value="ALPHA"}}---- Parameter to the ##[[KeyPgPutgraphics Put]]## graphics statement which selects alpha blending as the method {{fbdoc item="syntax"}}## **Put** [ //target//, ] [ STEP ] ( //x//,//y// ), //source// [ ,( //x1//,//y1// )-( //x2//,//y2// ) ], **Alpha** **Put** [ //target//, ] [ STEP ] ( //x//,//y// ), //source// [ ,( //x1//,//y1// )-( //x2//,//y2// ) ], **Alpha**, //alphaval// ## {{fbdoc item="param"}} ##**Alpha**## Required. ##//alphaval//## Optional alpha parameter in the range [0..255]. Overrides alpha values in individual pixels. {{fbdoc item="desc"}} ##**Alpha**## selects alpha blending as the method for ##[[KeyPgPutgraphics Put]]##ting an image. If the ##//alphaval//## parameter is specified, it overrides the alpha value of each pixel, and the mask color (magenta) will be treated as transparent. This works in 15, 16, 24, or 32-bit color depths. If ##//alphaval//## is not specified, ##**Alpha**## will only work in 32-bit color depth, and ##[[KeyPgPutgraphics Put]]## will use the alpha value embedded within each pixel. Pixels using the mask color will be treated as normal, and drawn with their given alpha value. ##**Alpha**## also has another mode which allows an 8-bit image to be ##[[KeyPgPutgraphics Put]]## on top of a 32-bit image. In this case, it will replace the alpha channel of the 32-bit image with the contents of the 8-bit image. Alpha values range between 0 and 255. An alpha value of 0 will not draw the image at all. All other alpha values are incremented by 1 to get a range between 2 and 256, and the result is then divided by 256 to get a value between 1/128 and 1, which is used to calculate the exact value of each pixel from the source and destination pixels. Thus, 255 is practically equivalent to drawing using Put with Trans blitting mode, 0 is equivalent to doing nothing at all, and all the other alpha values blend is expected. {{fbdoc item="ex"}} This example compares the two different ##**Alpha**## modes, including how they react to the mask color {{fbdoc item="filename" value="examples/manual/gfx/put-alpha.bas"}}%%(freebasic) '' Set up a 32-bit screen screenres 320, 200, 32 '' Draw checkered background for y as integer = 0 to 199 for x as integer = 0 to 319 pset (x, y), iif((x shr 2 xor y shr 2) and 1, rgb(160, 160, 160), rgb(128, 128, 128)) next x next y '' Make image sprite for Putting dim img as any ptr = imagecreate(32, 32, rgba(0, 0, 0, 0)) for y as single = -15.5 to 15.5 for x as single = -15.5 to 15.5 dim as integer r, g, b, a if y <= 0 then if x <= 0 then r = 255: g = 0: b = 0 '' red else r = 0: g = 0: b = 255 '' blue end if else if x <= 0 then r = 0: g = 255: b = 0 '' green else r = 255: g = 0: b = 255 '' magenta (transparent mask color) end if end if a = 255 - (x ^ 2 + y ^ 2) if a < 0 then a = 0': r = 255: g = 0: b = 255 pset img, (15.5 + x, 15.5 - y), rgba(r, g, b, a) next x next y '' Put with single Alpha value, Trans for comparison draw string (32, 10), "Single alpha" put (80 - 16, 50 - 16), img, alpha, 64 put (80 - 16, 100 - 16), img, alpha, 192 put (80 - 16, 150 - 16), img, trans '' Put with full Alpha channel draw string (200, 10), "Full alpha" put (240 - 16, 100 - 16), img, alpha '' Free the image memory imagedestroy img '' Wait for a keypress sleep %% {{image class="center" title="Put Alpha example output" url="/images/AL0.PNG"}} This example shows the special method for setting a 32-bit alpha channel using an 8-bit image {{fbdoc item="filename" value="examples/manual/gfx/put-alpha-8bit.bas"}}%%(freebasic) dim as any ptr img8, img32 dim as integer x, y, i '' Set up an 8-bit graphics screen screenres 320, 200, 8 for i = 0 to 255 palette i, i, i, i next i color 255, 0 '' Create an 8-bit image img8 = imagecreate(64, 64, 0, 8) for y = 0 to 63 for x = 0 to 63 dim as single x2 = x - 31.5, y2 = y - 31.5 dim as single t = sqr(x2 ^ 2 + y2 ^ 2) / 5 pset img8, (x, y), sin(t) ^ 2 * 255 next x next y draw string (16, 4), "8-bit Alpha sprite" put (16, 16), img8 sleep '' Set up a 32-bit graphics screen screenres 320, 200, 32 for y = 0 to 199 for x = 0 to 319 pset (x, y), iif(x - y and 3, rgb(160, 160, 160), rgb(128, 128, 128)) next x next y '' Create a 32-bit, fully opaque sprite img32 = imagecreate(64, 64, 0, 32) for y = 0 to 63 for x = 0 to 63 pset img32, (x, y), rgb(x * 4, y * 4, 128) next x next y draw string (16, 4), "Original Alpha channel" put (16, 16), img32, alpha '' Put a new alpha channel using the 8-bit image put img32, (0, 0), img8, alpha draw string (16, 104), "New Alpha channel" put (16, 116), img32, alpha ''Free the memory for the two images imagedestroy img8 imagedestroy img32 sleep%% {{image class="center" title="Put Alpha example 2 output" url="/images/AL1.PNG" }} {{fbdoc item="diff"}} - New to Freebasic {{fbdoc item="see"}} - ##[[KeyPgPutgraphics Put (Graphics)]]## - ##[[KeyPgTransGfx Trans]]## - ##[[KeyPgCustomgfx Custom]]## {{fbdoc item="back" value="CatPgGfx2D|2D Drawing Functions"}}{{fbdoc item="title" value="AND"}}---- Parameter to the ##[[KeyPgPutgraphics Put]]## graphics statement which uses a bit-wise ##[[KeyPgOpAnd And]]## as the blitting method {{fbdoc item="syntax"}}## **Put** [ //target//, ] [ STEP ] ( //x//,//y// ), //source// [ ,( //x1//,//y1// )-( //x2//,//y2// ) ], **And** ## {{fbdoc item="param"}} ##**And**## Required. {{fbdoc item="desc"}} The ##**And**## method combines each source pixel with the corresponding destination pixel, using the bit-wise ##[[KeyPgOpAnd And]]## function. The result of this is output as the destination pixel. This method works in all graphics modes. There is no mask color, although color values with all bits set (##255## for 8-bit palette modes, or ##[[KeyPgRgba RGBA]](255, 255, 255, 255)## in full-color modes) will have no effect, because of the behavior of ##[[KeyPgOpAnd And]]##. In full-color modes, each component (red, green, blue and alpha) is kept in a discrete set of bits, so the operation can be made to only affect some of the channels, by making sure the all the values of the other channels are set to ##255##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/put-and.bas"}}%%(freebasic) ''open a graphics window ScreenRes 320, 200, 16 line (0, 0)-(319, 199), RGB(255, 255, 255), bf ''create 3 sprites containing cyan, magenta and yellow circles Const As Integer r = 32 dim as any ptr cc, cm, cy cc = ImageCreate(r * 2 + 1, r * 2 + 1, RGBA(255, 255, 255, 255)) cm = ImageCreate(r * 2 + 1, r * 2 + 1, RGBA(255, 255, 255, 255)) cy = ImageCreate(r * 2 + 1, r * 2 + 1, RGBA(255, 255, 255, 255)) Circle cc, (r, r), r, RGB(0, 255, 255), , , 1, f Circle cm, (r, r), r, RGB(255, 0, 255), , , 1, f Circle cy, (r, r), r, RGB(255, 255, 0), , , 1, f ''put the three sprites, overlapping each other in the middle Put (146 - r, 108 - r), cc, and Put (174 - r, 108 - r), cm, and Put (160 - r, 84 - r), cy, and ''free the memory used by the sprites ImageDestroy cc ImageDestroy cm ImageDestroy cy ''pause the program before closing Sleep %% {{image class="center" title="Put And example output" url="/images/put-and.png"}} {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgOpAnd And]]## - ##[[KeyPgPutgraphics Put (Graphics)]]## {{fbdoc item="back" value="CatPgGfx2D|2D Drawing Functions"}} {{fbdoc item="title" value="ANY"}}---- Built-in pseudo data type used in declarations and initializers {{fbdoc item="syntax"}}## //identifier// [[KeyPgAs as]] **Any** [[KeyPgPointer Pointer]]|[[KeyPgPtr ptr]] //or// [[KeyPgDeclare declare]] { [[KeyPgSub sub]] | [[KeyPgFunction function]] } //identifier// ( [ ..., ] [[KeyPgByref byref]] //identifier// [[KeyPgAs as]] **Any** [ , ... ] ) //or// [[KeyPgDim Dim]] //identifier// [[KeyPgAs as]] [[DataType datatype]] = **Any** ## {{fbdoc item="usage"}}## Dim //identifier// as **Any** ptr //or// Declare Sub //identifier// ( byref //identifier// as **Any** ) //or// Declare Sub //identifier// ( [ byval | byref ] //identifier// as **Any** ptr ) //or// Dim //identifier// As //datatype// = **Any** ## {{fbdoc item="desc"}} ##**Any**## can be used in three contexts: pointers, variable initializers, pointer arguments of functions and function declarations to indicate an unknown data type. A pointer defined as an ##**Any** Ptr## disables the compiler checking for the type of data it points to. It is useful as it can point to different types of data. Before dereferencing it (accessing to the data it points to) it must be ##[[KeyPgCast Cast]]## to a known data type. This should not be confused with ##Variant##, a Visual Basic data type which can contain any type of variable, which is not intrinsically supported by FreeBASIC. ##**Any**## can be used as a fake initializer to disable the default initialization to 0 of the variables. This may save time in critical sections of the programs. Is up to the program to fill the variables with significant data. **##Any##** can be used in function parameter lists with ##[[KeyPgPtr Ptr]]## arguments to allow the passing of any type of pointers. In this case the function must ##[[KeyPgCast Cast]]## the pointer argument to a known data type before accessing it. **##Any##** can be used in function prototypes (in a ##[[KeyPgDeclare Declare]]## statement) with ##[[KeyPgByref ByRef]]## arguments to disable the compiler checking for the correct type of the variable passed. This use of ##**Any**## is deprecated and it is only there for compatibility with QB, where it was the only way of passing arrays as arguments. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/misc/any.bas"}}%%(freebasic) Declare Sub echo(ByVal x As Any Ptr) '' echo will accept any pointer type Dim As Integer a(0 To 9) = Any '' this variable is not initialized Dim As Double d(0 To 4) Dim p As Any Ptr Dim pa As Integer Ptr = @a(0) Print "Not initialized "; echo pa '' pass to echo a pointer to integer Dim pd As Double Ptr = @d(0) Print "Initialized "; echo pd '' pass to echo a pointer to double p = pa '' assign to p a pointer to integer p = pd '' assign to p a pointer to double Sleep Sub echo (ByVal x As Any Ptr) Dim As Integer i For i = 0 To 39 'echo interprets the data in the pointer as bytes Print Cast(UByte Ptr, x)[i] & " "; Next Print End Sub %% {{fbdoc item="filename" value="examples/manual/misc/any-param.bas"}}%%(freebasic) 'Example of ANY disabling the variable type checking Declare Sub echo (ByRef a As Any) '' ANY disables the checking for the type of data passed to the function Dim x As Single x = -15 echo x '' Passing a single to a function that expects an integer. The compiler does not complain!! Sleep Sub echo (ByRef a As Integer) Print Hex(a) End Sub %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect. {{fbdoc item="diff"}} - Pointers and initializers are new to FreeBASIC. {{fbdoc item="see"}} - ##[[KeyPgDim Dim]]## - ##[[KeyPgDeclare Declare]]## {{fbdoc item="back" value="CatPgProcedures|Procedures"}}{{fbdoc item="title" value="APPEND"}}---- Specifies text file to be opened for append mode {{fbdoc item="syntax"}}## [[KeyPgOpen open]] //filename// for **Append** [[[KeyPgEncoding encoding]] //encoding_type//] [[[KeyPgLock lock]] //lock_type//] as [#]//filenum// ## {{fbdoc item="param"}} ##//filename//## file name to open for append ##//encoding_type//## indicates encoding type for the file ##//lock_type//## locking to be used while the file is open ##//filenum//## unused file number to associate with the open file {{fbdoc item="desc"}} A file mode used with ##[[KeyPgOpen Open]]## to open a text file for writing. This mode is used to add text to an existing file with ##[[KeyPgPrintPp Print #]]##, or comma separated values with ##[[KeyPgWrite Write#]]##. Text files can't be simultaneously read and written in FreeBASIC, so if both functions are required on the same file, it must be opened twice. ##//filename//## must be a string expression resulting in a legal file name in the target OS, without wildcards. The file will be sought for in the present directory, unless the ##//filename//## contains a path . If the file does not exist, it is created. The pointer is set after the last character of the file. ##//Encoding_type//## indicates the Unicode ##[[KeyPgEncoding Encoding]]## of the file, so characters are correctly read. If omitted, "ascii" encoding is defaulted. Only little endian character encodings are supported at the moment. -"utf8", -"utf16" -"utf32" -"ascii" (the default) ##//Lock_type//## indicates the way the file is locked for other processes, it is one of: - **Read** - the file can be opened simultaneously by other processes, but not for reading - **Write** - the file can be opened simultaneously by other processes, but not for writing - **Read Write** - the file cannot be opened simultaneously by other processes (the default) ##//filenum//## Is a valid FreeBASIC file number (in the range 1-255) not being used for any other file presently open. The file number identifies the file for the rest of file operations. A free file number can be found using the ##[[KeyPgFreefile Freefile]]## function. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/fileio/for-append.bas"}}%%(freebasic) dim i as integer FOR i = 1 to 10 OPEN "test.txt" FOR APPEND as #1 PRINT #1, "extending test.txt" CLOSE #1 NEXT %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgInputfilemode Input (File Mode)]]## - ##[[KeyPgOpen Open]]## - ##[[KeyPgOutput Output]]## - ##[[KeyPgPrintPp Print #]]## - ##[[KeyPgWrite Write #]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}}{{fbdoc item="title" value="AS"}}---- Optional part of a declaration which specifies a data type, or part of the [[KeyPgOpen Open]] statement which specifies a file handle. {{fbdoc item="syntax"}}## //symbolname// **As** [[DataType datatype]] [[KeyPgOpen open]] ... **As** //#filenumber// [[KeyPgType type]] ... **As** [[DataType datatype]] ## {{fbdoc item="desc"}} ##**As**## is used to declare the type of variables, fields or arguments and is also used in the ##[[KeyPgOpen Open]]## statement to determine the file handle. ##**As**## is also used with the ##[[KeyPgTypeAlias Type (Alias)]]## syntax, similar to C's typedef statement. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/misc/as.bas"}}%%(freebasic) '' don't try to compile this code, the examples are unrelated Declare Sub mySub (X As Integer, Y As Single, Z As String) ' ... Dim X As Integer ' ... Type myType X As Integer Y As Single Z As String End Type ' ... Type TheNewType As myType ' ... Open "test" For Input As #1 ' ... %% {{fbdoc item="diff"}} - The [[KeyPgTypeAlias Type (Alias)]] syntax was not supported in QB. {{fbdoc item="see"}} - ##[[KeyPgDeclare Declare]]## - ##[[KeyPgDim Dim]]## - ##[[KeyPgType Type]]## - ##[[KeyPgOpen Open]]## {{fbdoc item="back" value="CatPgMisc|Miscellaneous"}}{{fbdoc item="title" value="ASC"}}---- Returns the corresponding ASCII or Unicode integer representation of a character {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Asc** [[KeyPgOverload overload]] ( [[KeyPgByref byref]] //str// [[KeyPgAs as]] [[KeyPgString string]], [[KeyPgByval byval]] //position// [[KeyPgAs as]] [[KeyPgInteger integer]] = 1 ) [[KeyPgAs as]] [[KeyPgUinteger uinteger]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Asc** ( [[KeyPgByval byval]] //str// [[KeyPgAs as]] [[KeyPgZstring zstring]] [[KeyPgPtr ptr]], [[KeyPgByval byval]] //position// [[KeyPgAs as]] [[KeyPgInteger integer]] = 1 ) [[KeyPgAs as]] [[KeyPgUinteger uinteger]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Asc** ( [[KeyPgByval byval]] //str// [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgPtr ptr]], [[KeyPgByval byval]] //position// [[KeyPgAs as]] [[KeyPgInteger integer]] = 1 ) [[KeyPgAs as]] [[KeyPgUinteger uinteger]] ## {{fbdoc item="usage"}}## //result// = **Asc**( //str// [, //position// ] ) ## {{fbdoc item="param"}} ##//str//## The source string. ##//position//## The position in the string of a character. {{fbdoc item="ret"}} The ASCII or Unicode integer representation of the character at ##//position//## in ##//str//##. {{fbdoc item="desc"}} If ##//str//## is a ##[[KeyPgString String]]## or a ##[[KeyPgZstring ZString]]##, an [[CptAscii ASCII]] code value is returned. If ##//str//## is a ##[[KeyPgWstring WString]]##, a [[CptAscii Unicode]] code value is returned. The function returns zero (0) if the string is a zero length string, ##//position//## is less than one (1), or ##//position//## is greater than the number of characters in ##//str//##. ##[[KeyPgChr Chr]]## performs the opposite function for ASCII strings, while ##[[KeyPgWchr WChr]]## is the opposite for Unicode strings, returning a string containing the character represented by the code passed as an argument. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/asc.bas"}}%%(freebasic) print "the ascii code of 'a' is:"; asc("a") print "the ascii code of 'b' is:"; asc("abc", 2) %% will produce the output: %%the ascii code of 'a' is: 97 the ascii code of 'b' is: 98 %% Unicode example (Note to documentation editors: don't put inside ""%%(qbasic)"" markers or the Russian text will disappear!) <<##dim a as wstring * 11 a = "Привет, мир" print "the Unicode of the second char of " & a & " is: " & asc(a) ##<<::c:: will produce the output: <<##the Unicode of the second char of Привет, мир is: 1088 ##<<::c:: {{fbdoc item="target"}} - DOS does not support the wide-character string version of ##**ASC**##. {{fbdoc item="diff"}} - The optional ##//position//## argument is new to FreeBASIC. - QB does not support the wide-character string version of ##**ASC**## {{fbdoc item="see"}} - [[CptAscii ASCII Character Codes]] - ##[[KeyPgChr Chr]]## - ##[[KeyPgStr Str]]## - ##[[KeyPgVal Val]]## {{fbdoc item="back" value="CatPgString|String Functions"}}{{fbdoc item="title" value="ASIN"}}---- Finds the arcsine of a number {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Asin** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgDouble double]] ) [[KeyPgAs as]] [[KeyPgDouble double]] ## {{fbdoc item="usage"}}## //result// = **Asin**( //number// ) ## {{fbdoc item="param"}} ##//number//## Sine value in the range [-1..1]. {{fbdoc item="ret"}} The arcsine of ##//number//##, in radians, in the range [-Pi/2..Pi/2]. {{fbdoc item="desc"}} ##**Asin**## returns the arcsine of the argument ##//number//## as a ##[[KeyPgDouble Double]]## within the range of -[[TutMathAngles Pi]]/2 to [[TutMathAngles Pi]]/2. The arcsine is the inverse of the ##[[KeyPgSin Sin]]## function. The returned angle is measured in [[TutMathAngles radians]] (not [[TutMathAngles degrees]]). {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/math/asin.bas"}}%%(freebasic) DIM h AS DOUBLE DIM o AS DOUBLE INPUT "Please enter the length of the hypotenuse of a triangle: ", h INPUT "Please enter the length of the opposite side of the triangle: ", o PRINT "" PRINT "The angle between the sides is"; ASIN ( o / h ) SLEEP %% The output would look like: %% Please enter the length of the hypotenuse of a triangle: 5 Please enter the length of the opposite side of the triangle: 3 The angle between the sides is 0.6435011087932844 %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Asin""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgSin Sin]]## - [[TutMathIntroTrig A Brief Introduction To Trigonometry]] {{fbdoc item="back" value="CatPgMath|Math"}}{{fbdoc item="title" value="ASM"}}---- Code block that allows the use of architecture-specific instructions. {{fbdoc item="syntax"}}## **Asm** //architecture-dependent instructions// End **Asm** ##//Or//## **Asm** //architecture-dependent instructions// ## {{fbdoc item="desc"}} The ##Asm## block is used to insert specific machine-code instructions in a program in order to perform operations that cannot be carried out using the features of the language or to hand-optimize performance-sensitive sections of code. The current FreeBASIC compiler currently only produces code for Intel 80x86-based machines; however, in the future, the compiler might be ported to a platform which does not support the same instruction set. Therefore, ##Asm## blocks should only be used when necessary, and a FreeBASIC-only alternative should be provided if possible. The return value of a function may be set by using the ##[[KeyPgFunction Function]]## keyword within brackets as shown in the example below. ##Asm## block comments have the same syntax as usual ""FreeBASIC"" [[KeyPgRem comments]]. [[x86 x86]] Specific: ==Syntax== The syntax of the inline assembler is a simplified form of Intel syntax. Intel syntax is used by the majority of x86 assemblers, such as MASM, TASM, NASM, YASM and FASM. In general, the destination of an instruction is placed first, followed by the source. Variables and functions defined by a program may be referenced in an Asm block. The assembler used by FreeBASIC is GAS, using the ##.intel_syntax noprefix## directive, and ASM blocks are passed through unmodified, except for the substitution of local variable names for stack frame references, and commenting removal - use FreeBASIC-like " ' " comments, not " ; " as usual in ASM. ==Register Preservation== When an ASM block is opened, the registers ##ebx##, ##esi##, and ##edi## are pushed to the stack, when the block is closed, these registers are popped back from the stack. This is because these registers are required to be preserved by most or all OS's using the x86 CPU. You can therefore use these registers without explicitly preserving them yourself. You should not change ##esp## and ##ebp##, since they are usually used to address local variables. ==Register Names== ~The names of the registers for the x86 architecture are written as follows in an ##Asm## block: ~- 4-byte integer registers: ##eax##, ##ebx##, ##ecx##, ##edx,## ##ebp##, ##esp##, ##edi##, ##esi## ~- 2-byte integer registers: ##ax##, ##bx##, ##cx##, ##dx##, ##bp##, ##sp##, ##di##, ##si## (low words of 4-byte ##e##- registers) ~- 1-byte integer registers: ##al##, ##ah##, ##bl##, ##bh##, ##cl##, ##ch##, ##dl##, ##dh## (low and high bytes of 2-byte -##x## registers) ~- Floating-point registers: ##st(0)##, ##st(1)##, ##st(2)##, ##st(3)##, ##st(4)##, ##st(5)##, ##st(6)##, ##st(7)## ~- MMX registers (aliased onto floating-point registers): ##mm0##, ##mm1##, ##mm2##, ##mm3##, ##mm4##, ##mm5##, ##mm6##, ##mm7## ~- SSE registers: ##xmm0##, ##xmm1##, ##xmm2##, ##xmm3##, ##xmm4##, ##xmm5##, ##xmm6##, ##xmm7## ==Instruction Set== See these external references: ~- [[http://developer.intel.com/design/Pentium4/documentation.htm Intel Pentium 4 manuals]] ~- [[http://home.comcast.net/~fbkotler/nasmdocb.html NASM x86 Instruction Reference]] (Please note that NASM is not the assembler used by FreeBASIC, but this page provides a good overview of x86 instructions) ==Unsafe instructions== ~Note that the FreeBASIC compiler produces 32-bit protected-mode code for the x86 which usually runs in an unprivileged user level; therefore, privileged and sensitive instructions will assemble fine, but possibly won't work correctly or cause a runtime "General Protection Fault", "Illegal instruction", or SIGILL error. The following are the privileged and sensitive instructions as of the Intel Pentium 4 and Xeon: ~- ##cli## *1 ~- ##clts## ~- ##hlt## ~- ##in## *1 ~- ##ins## *1 ~- ##int## *1 ~- ##into## *1 ~- ##invd## ~- ##invlpg## ~- ##lgdt## ~- ##lidt## ~- ##lldt## ~- ##lmsw## ~- ##ltr## ~- ##mov## to/from ##CR##n, ##DR##n, ##TR##n ~- ##out## *1 ~- ##outs## *1 ~- ##rdmsr## ~- ##rdpmc## *2 ~- ##rdtsc## *2 ~- ##sti## *1 ~- ##str## ~- ##wbinvd## ~- ##wrmsr## ~- all SSE2 and higher instructions *2 ~ *1: IOPL sensitive, fine in DOS ~ *2: sensitive to bits in CR4, see below The privileged instructions will work correctly in DOS when running on a Ring 0 DPMI kernel, like the (non-default) Ring 0 version of CWSDPMI, WDOSX or D3X. Nevertheless most of them are not really useful and dangerous when executed from DPMI code. RDTSC (Read Time Stamp Counter) has been shown to be allowed by most, or all OS'es. However the usefulness of RDTSC has been diminished with the advent of multi-core and hibernating CPUs. SSE2 and higher instructions are disabled by "default", Windows and Linux usually do enable them, in DOS it is business of the DPMI host: HDPMI32 will enable them, CWSDPMI won't. The INT instruction is usable in the DOS version/target only, note that it works slightly differently from real mode DOS, see also [[FaqDOS]]. The segment registers (##cs##, ##ds##, ##es##, ##fs##, ##gs##) should not be changed from an ##Asm## block, except in certain cases with the DOS port (note that they do NOT work the same way as in real-mode DOS, see also [[FaqDOS]]). The operating system or DPMI host is responsible for memory management; the meaning of segments (selectors) in protected mode is very different from real-mode memory addressing. Note that those "unsafe" instructions are not guaranteed to crash even with insufficient privilege - the OS or DPMI host can decide to "emulate" them, either functionally (reading from CRx under HDPMI32), or "dummy" (no spectacular crash, will pass silently, like a NOP). {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/misc/asm.bas"}}%%(freebasic) '' This is an example for the x86 architecture. Function AddFive(ByVal num As Integer) As Integer Asm mov eax, [num] add eax, 5 mov [Function], eax End Asm End Function Dim i As Integer = 4 Print "4 + 5 ="; AddFive(i) %% ##%%4 + 5 = 9%%## FreeBASIC's Assembler is AS, the GCC assembler, so an external program. Some quirks apply: The error lines returned by FBC for asm / end asm blocks are not related the source file. As FBC simply displays the errors returned by AS , the lines are related to the assembly file. To make FreeBASIC preserve it, the compiler must be invoked with the //[[CompilerOptr -r]]// option. The label names are case sensitive inside asm /end asm blocks. {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Asm""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgFunction Function]]## {{fbdoc item="back" value="DocToc|Table of Contents"}}{{fbdoc item="back" value="CatPgProgrammer|Programmer's Guide"}}{{fbdoc item="title" value="ASSERT"}}---- Debugging macro that halts program execution if an expression is evaluated to 0. {{fbdoc item="syntax"}}## [[KeyPgPpdefine #define]] **ASSERT**(//expression//) [[KeyPgIfthen if]] (expression) = 0 [[KeyPgThen then]] : fb_Assert( [[KeyPgDdfile __FILE__]], [[KeyPgDdline __LINE__]], [[KeyPgDdfunction __FUNCTION__]], [[KeyPgOpPpStringize #]]expression ) : [[KeyPgEndif end if]] ## {{fbdoc item="usage"}}## **ASSERT**( //expression// ) ## {{fbdoc item="param"}} ##//expression//## Any valid expression. If ##//expression//## evaluates to 0, execution is halted. {{fbdoc item="desc"}} The ##**ASSERT**## macro is intended for use in debugging and works only if the ##-g## option is selected in the FBC command line. In this case it stops the program execution if ##//expression//## evaluates to 0. Its normal use is to check the correct value of the variables during debugging. If ##-g## is not passed to fbc, the macro does not generate any code. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/debug/assert.bas"}}%%(freebasic) sub foo dim a as integer a=0 assert(a=1) end sub foo '' If -g is used this code stops with: test.bas(3): assertion failed at FOO: a=1 %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__ASSERT""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgAssertwarn ASSERTWARN]]## {{fbdoc item="back" value="CatPgMisc|Miscellaneous"}}{{fbdoc item="title" value="ASSERTWARN"}}---- Debugging macro that prints a warning if an expression evaluates to 0. {{fbdoc item="syntax"}}## [[KeyPgPpdefine #define]] **ASSERTWARN**(//expression//) [[KeyPgIfthen if]] (expression) = 0 [[KeyPgThen then]] : fb_AssertWarn( [[KeyPgDdfile __FILE__]], [[KeyPgDdline __LINE__]], [[KeyPgDdfunction __FUNCTION__]], [[KeyPgOpPpStringize #]]expression ) : [[KeyPgEndif end if]] ## {{fbdoc item="usage"}}## **ASSERTWARN**( //expression// ) ## {{fbdoc item="param"}} ##//expression//## Any valid expression. If ##//expression//## evaluates to 0, a warning message is printed to stdout (console). {{fbdoc item="desc"}} The ##**ASSERTWARN**## macro is intended for use in debugging and works only if the ##-g## option is selected in the FBC command line. In this case it prints a warning message if ##//expression//## evaluates to 0. It doesn't stop the program execution like [[KeyPgAssert ASSERT]] does. Its normal use is to check the correct value of the variables during debugging. If ##-g## is not passed to fbc, the macro does not generate any code. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/debug/assertwarn.bas"}}%%(freebasic) sub foo dim a as integer a=0 assertwarn(a=1) end sub foo '' If -g is used this code prints: test.bas(3): assertion failed at FOO: a=1 %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__ASSERTWARN""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgAssert ASSERT]]## {{fbdoc item="back" value="CatPgMisc|Miscellaneous"}}{{fbdoc item="title" value="ATAN2"}}---- Returns the arctangent of a ratio {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""ATan2""** ( [[KeyPgByval byval]] //y// [[KeyPgAs as]] [[KeyPgDouble double]], [[KeyPgByval byval]] //x// [[KeyPgAs as]] [[KeyPgDouble double]] ) [[KeyPgAs as]] [[KeyPgDouble double]] ## {{fbdoc item="usage"}}## //result// = ""ATan2""( //y//, //x// ) ## {{fbdoc item="param"}} ##y## Vertical component of the ratio. ##x## Horizontal component of the ratio. {{fbdoc item="ret"}} The angle whose tangent is ##//y/////x//##, in radians, in the range [-Pi..Pi]. {{fbdoc item="desc"}} ##""ATan2""## returns the arctangent of the ratio ##//y/////x//## as a ##[[KeyPgDouble Double]]## within the range of -[[TutMathAngles Pi]] to [[TutMathAngles Pi]]. The arctangent is the inverse of the ##[[KeyPgTan Tan]]## function. The returned angle is measured in [[TutMathAngles radians]] (not [[TutMathAngles degrees]]). {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/math/atan2.bas"}}%%(freebasic) PRINT ATAN2 ( 4, 5 ) 'this is the same as PRINT ATN ( 4 / 5 ) %% The output would be: %% 0.6747409422235527 %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Atan2""**##. {{fbdoc item="see"}} - ##[[KeyPgTan Tan]]## - ##[[KeyPgAtn Atn]]## - [[TutMathIntroTrig A Brief Introduction To Trigonometry]] {{fbdoc item="back" value="CatPgMath|Math"}}{{fbdoc item="title" value="ATN"}}---- Returns the arctangent of a number {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Atn** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgDouble double]] ) [[KeyPgAs as]] [[KeyPgDouble double]] ## {{fbdoc item="usage"}}## //result// = Atn( //number// ) ## {{fbdoc item="param"}} ##//number//## A number. {{fbdoc item="ret"}} The angle, in radians, whose tangent is ##//number//##, in the range [-Pi/2..Pi/2]. {{fbdoc item="desc"}} ##Atn## returns the arctangent of the argument ##//number//## as a ##[[KeyPgDouble Double]]## within the range of -[[TutMathAngles Pi]]/2 to [[TutMathAngles Pi]]/2. The arctangent is the inverse of the ##[[KeyPgTan Tan]]## function. The returned angle is measured in [[TutMathAngles radians]] (not [[TutMathAngles degrees]]). {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/math/atn.bas"}}%%(freebasic) PRINT "Pi ="; ATN ( 1.0 ) * 4 PRINT ATN ( 4 / 5 ) %% The output would be: %% Pi = 3.141592653589793 0.6747409422235527 %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgTan Tan]]## - ##[[KeyPgAtan2 ATan2]]## - [[TutMathIntroTrig A Brief Introduction To Trigonometry]] {{fbdoc item="back" value="CatPgMath|Math"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:49:25 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 2ad783ae460db4ad84535e964c53b2de Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 621 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="BEEP"}}---- Produces a beep sound. {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Beep** ( ) ## {{fbdoc item="usage"}}## Beep ## {{fbdoc item="desc"}} ##Beep## tells the system to sound a beep noise. Note that this might not work on some platforms. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/system/beep.bas"}}%%(freebasic) Beep %% {{fbdoc item="diff"}} - In QB, this was a single tone noise generated through the PC speaker. Now this might not be the case. {{fbdoc item="see"}} - {{fbdoc item="back" value="CatPgMisc|Miscellaneous"}} {{fbdoc item="title" value="BIN"}}---- Returns a binary (base 2) string representation of an integer {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Bin** [[KeyPgOverload overload]] ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgByte byte]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Bin** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgShort short]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Bin** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Bin** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByval byval]] //digits// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Bin** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgLongint longint]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Bin** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgLongint longint]], [[KeyPgByval byval]] //digits// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgString string]] ## {{fbdoc item="usage"}}## //result// = **Bin**[$]( //number// [, //digits// ] ) ## {{fbdoc item="param"}} ##//number//## A number or expression evaluating to a number. A floating-point number will be converted to a ##[[KeyPgLongint longint]]##. ##//digits//## Desired number of digits in the returned string. {{fbdoc item="ret"}} A string containing the unsigned binary representation of ##//number//##. {{fbdoc item="desc"}} Returns a string representing the unsigned binary value of the integer ##//number//##. Binary digits range from 0 to 1. If you specify ##//digits//## > 0, the result string will be exactly that length. It will be truncated or padded with zeros on the left, if necessary. The length of the string will not go longer than the maximum number of digits required for the type of ##//number//## (32 for an ##[[KeyPgInteger integer]]##, 64 for a ##[[KeyPgLongint Longint]])##. If you want to do the opposite, i.e. convert an binary string back into a number, the easiest way to do it is to prepend the string with ##"&B"##, and convert it using ##[[KeyPgValint Valint]]## or ##[[KeyPgVallng Vallng]]##, similarly to a normal numeric string. E.g. ##[[KeyPgValint Valint]]("&B101")## {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/bin.bas"}}%%(freebasic) Print Bin(54321) Print Bin(54321, 5) Print Bin(54321, 20) %% will produce the output: %%1101010000110001 10001 00001101010000110001 %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Bin""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgOct Oct]]## - ##[[KeyPgHex Hex]]## - ##[[KeyPgValint Valint]]## - ##[[KeyPgVallng Vallng]]## {{fbdoc item="back" value="CatPgString|String Functions"}}{{fbdoc item="title" value="BINARY"}}---- Specifies file or device to be opened for binary mode {{fbdoc item="syntax"}}## [[KeyPgOpen Open]] //filename// for **Binary** [[[KeyPgAccess Access]] //access_type//] [[[KeyPgLock Lock]] //lock_type//] as [#]//filenum// ## {{fbdoc item="param"}} ##//filename//## file name to open ##//access_type//## indicates whether the file may be read from, written to or both ##//lock_type//## locking to be used while the file is open ##//filenum//## unused file number to associate with the open file {{fbdoc item="desc"}} Opens a file or device for reading and/or writing binary data in the file ##//filenum//##, with free format. If the file does not exist, a new file will be created. The file pointer is initialized by ##[[KeyPgOpen Open]]## at byte no. 1. ##[[KeyPgGetfileio Get #]]## and ##[[KeyPgPutfileio Put #]]## file operations move the file pointer according to the size of the data, the pointer can be set to any byte in the file. The data existing in the file is preserved by ##[[KeyPgOpen Open]]##. This file mode can use any buffer variable to read/write data in the file. The data is saved in binary mode, in the same internal format FreeBASIC uses, by means of ##[[KeyPgGetfileio Get #]]## and ##[[KeyPgPutfileio Put #]]##. ##//filename//## must be a string expression resulting in a legal file name in the target OS, without wildcards. The file will be sought for in the present directory, unless a path is given. ##//Access_type//## By default ##**Binary**## mode allows to both read and write the file, unless an ##[[KeyPgAccess Access]]## type is specified, it mus be one of: - ##**Read**## - the file is opened for input only - ##**Write**## - the file is opened for output only - ##**Read Write**## - the file is opened for input and output (the default) ##//Lock_type//## indicates the way the file is locked for other processes (users or threads), it is one of: - ##**Shared**## - The file can be freely accessed by other processes - ##**Lock Read**## - The file can't be opened simultaneously for reading - ##**Lock Write**## - The file can't be opened simultaneously for writing - ##**Lock Read Write**## - The file cannot be opened simultaneously by other processes. If no lock type is stated, the file will be ##**Shared**## for other threads of the program and ##**Lock Read Write**## for other programs. ##[[KeyPgLock Lock]]## and ##[[KeyPgUnlock Unlock]]## can be used to restrict temporally access to parts of a file. ##//filenum//## is a valid file number (in the range 1-255) not being used for any other file presently open. The file number identifies the file for the rest of file operations. A free file number can be found using the ##[[KeyPgFreefile FreeFile]]## function. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/fileio/binary-write.bas"}}%%(freebasic) '' Create a binary data file with one number in it Dim x As Single = 17.164 Open "MyFile.Dat" For Binary As #1 '' put without a position setting will put from the last known file position '' in this case, the very beginning of the file. Put #1, , x Close #1 %% {{fbdoc item="filename" value="examples/manual/fileio/binary-read.bas"}}%%(freebasic) '' Now read the number from the file Dim x As Single = 0 Open "MyFile.Dat" For Binary As #1 Get #1, , x Close #1 Print x %% {{fbdoc item="filename" value="examples/manual/fileio/binary-text.bas"}}%%(freebasic) '' Read entire contents of a file to a string Dim txt As String Open "myfile.txt" For Binary Access Read As #1 If Lof(1) > 0 Then '' our string has as many characters as the file has in bytes txt = String(Lof(1), 0) '' size of txt is known. entire string filled with file data Get #1, , txt End If Close #1 Print txt %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgOpen Open]]## - ##[[KeyPgPutfileio Put #]]## - ##[[KeyPgGetfileio Get #]]## - ##[[KeyPgRandom Random]]## - ##[[KeyPgAppend Append]]## - ##[[KeyPgOutput Output]]## - ##[[KeyPgInputfilemode Input]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}}{{fbdoc item="title" value="BIT"}}---- Macro that returns the value of one bit of an integer {{fbdoc item="syntax"}}## [[KeyPgPpdefine #define]] **Bit**( //value//, //bit_number// ) (((//value//) [[KeyPgOpAnd and]] ([[KeyPgCast Cast]]([[KeyPgTypeof TypeOf]](//Value//), 1) [[KeyPgOpShiftLeft shl]] (//bit_number//))) <> 0) ## {{fbdoc item="usage"}}## //result// = **Bit**(//value//, //bit_number//) ## {{fbdoc item="param"}} ##//value//## Value in which to test the bit. ##//bit_number//## Zero-based number of the bit to test, where 0 is the least-significant bit. {{fbdoc item="ret"}} ""-1"" if bit ##//bit_number//## is set in ##//value//##, else 0. {{fbdoc item="desc"}} ##**Bit**## returns -1 if the bit ##//bit_number//## of ##//value//## is 1, returns 0 if bit is 0. ##foo = **Bit**( bar, 10 )## is the same as ##foo = (bar and 1 shl 10) <> 0##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/bits/bit.bas"}}%%(freebasic) PRINT BIT(4,2) PRINT BIT(5,1) PRINT BIT(&H8000000000000000ULL,63) %% will produce the output: %% -1 0 -1 %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgBitset Bitset]]## - ##[[KeyPgBitreset Bitreset]]## {{fbdoc item="back" value="CatPgBits|Bit Manipulation"}}{{fbdoc item="title" value="BITRESET"}}---- Macro that clears a bit in an integer {{fbdoc item="syntax"}}## [[KeyPgPpdefine #define]] **Bitreset**( //value//, //bit_number// ) ((//value//) [[KeyPgOpAnd and]] [[KeyPgOpNot not]] ([[KeyPgCast Cast]]([[KeyPgTypeof TypeOf]](//Value//), 1) [[KeyPgOpShiftLeft shl]] (//bit_number//))) ## {{fbdoc item="usage"}}## //result// = **Bitreset**(//value//, //bit_number//) ## {{fbdoc item="param"}} ##//value//## The integer value to clear a bit in. It is not modified. ##//bit_number//## The zero-based number of the bit to clear; 0 is the least-significant bit. {{fbdoc item="ret"}} ##//value//## with bit ##//bit_number//## cleared. {{fbdoc item="desc"}} Macro returning ##//value//## with the bit ##//bit_number//## reset to 0. ##foo = **Bitreset**( bar, 5 )## does the same as ##foo = bar and not (1 shl 5)##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/bits/bitreset.bas"}}%%(freebasic) print bitreset(5,0) print hex(bitreset(&h8000000000000001,63)) %% will produce the output: %% 4 1 %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect. {{fbdoc item="diff"}} - New to FreeBASIC. {{fbdoc item="see"}} - ##[[KeyPgBit Bit]]## - ##[[KeyPgBitset Bitset]]## {{fbdoc item="back" value="CatPgBits|Bit Manipulation"}}{{fbdoc item="title" value="BITSET"}}---- Macro that sets a bit in an integer {{fbdoc item="syntax"}}## [[KeyPgPpdefine #define]] **Bitset**( //value//, //bit_number// ) ((//value//) [[KeyPgOpOr or]] ([[KeyPgCast Cast]]([[KeyPgTypeof TypeOf]](//Value//), 1) [[KeyPgOpShiftLeft shl]] (//bit_number//))) ## {{fbdoc item="usage"}}## //result// = **Bitset**(//value//, //bit_number//) ## {{fbdoc item="param"}} ##//value//## The integer value to set a bit in. It is not modified. ##//bit_number//## The zero-based number of the bit to set; 0 is the least-significant bit. The valid range for this number is 0 to 31, unless ##//value//## is a ##[[KeyPgLongint LongInt]]##, in which case the range is from 0 to 63. {{fbdoc item="ret"}} ##//value//## with bit ##//bit_number//## set to 1. {{fbdoc item="desc"}} Macro returning ##//value//## with the bit ##//bit_number//## set to 1. ##foo = **Bitset**( bar, 5 )## does the same as ##foo = bar or (1 shl 5)##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/bits/bitset.bas"}}%%(freebasic) print bitset(4, 0) print hex(bitset(1ull, 63)) %% will produce the output: %% 5 8000000000000001 %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect. {{fbdoc item="diff"}} - New to FreeBASIC. {{fbdoc item="see"}} - ##[[KeyPgBit Bit]]## - ##[[KeyPgBitreset Bitreset]]## {{fbdoc item="back" value="CatPgBits|Bit Manipulation"}}{{fbdoc item="title" value="BLOAD"}}---- Loads arbitrary data from a file created with ##[[KeyPgBsave Bsave]]##, or a compatible BMP image file. {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Bload** ( [[KeyPgByref byref]] //filename// [[KeyPgAs as]] [[KeyPgString string]], [[KeyPgByval byval]] //dest// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] = 0, [[KeyPgByval byval]] //pal// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] = 0 ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **Bload**( //filename// [, [ //dest// ] [, //pal// ] ] ) ## {{fbdoc item="param"}} ##//filename//## the name of the file to load the image from; can include a file path ##//dest//## the memory location to load the image to, or null (##0##) to copy the image to the current graphics screen work page ##//pal//## the memory location to load the palette to, or null (##0##) to change the current graphics screen palette, if it uses one {{fbdoc item="ret"}} Returns zero (##0##) if successful, or a non-zero error code to indicate a failure. //[[ProPgErrorHandling (throws a runtime error)]]// {{fbdoc item="desc"}} ##**Bload**## can be used to load image data or any other data from a file created with ##[[KeyPgBsave Bsave]]##, and store that data in an array or paste it to the screen. If ##//dest//## is not null (##0##), the image data is copied to memory starting at the address specified. Otherwise, it is pasted to the current graphics screen work page. ##**Bload**## can load 3 different types of files: - Old QB-like data files, saved with BSAVE from QB code, containing "raw" data preceded by a 7-byte header, beginning with 0xFD, up to 64 KiB in size - New FB-like data files, saved with BSAVE from FB code, containing "raw" data preceded by a 7-byte header, beginning with 0xFE, no 64 KiB limit anymore - BMP image files, supports a subset of valid ("Windows") .BMP files, beginning with "BM", saved from FB code with BSAVE, or created / saved in a compatible format using a graphics editor / converter. Image files with 8-bit per pixel resolution or lower contain a palette that describes the color values used in the images. If ##//pal//## is not null (##0##), the palette is copied to memory starting at the address specified. Otherwise, if the current graphics screen uses a palette then its palette is changed to match that of the image file. When using one of the 2 "non-BMP" file formats to save images (nonrecommended), the image files must have been created with ##[[KeyPgBsave Bsave]]## in the same graphics screen mode as it is being loaded into. When using the BMP file format, this restriction doesn't apply. When loading a BMP using ##**Bload**##, the images must be true-color (24- or 32- bits per pixel) or palettized/indexed (8-bit or lower in resolution). The image data will be converted to the proper pixel format for the current color depth, except true-color won't get reduced to a palettized image. ##**Bload**## doesn't support 15 or 16 bpp BMP's (rare), BMP's using the optional RLE compression (also rare), or other image file types (PNG, JPG, GIF, ...). **Runtime errors:** ##**Bload**## throws one of the following [[ProPgErrorHandling runtime errors]]: //(##1##) Illegal function call// - ##//dest//## was not specified or was null (##0##), and no graphics screen was set. - The Bitmap is high-color (15 or 16 bits per pixel). - The Bitmap is true-color (24 or 32 bits per pixel) and the current graphics screen uses a palette (8 bits per pixel or lower). //(##2##) File not found// - The file ##//filename//## could not be found. //(##3##) File I/O error// - The file doesn't have any of the supported types - A general read error occurred. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/bload.bas"}}%%(freebasic) 'Load a graphic to current work page SCREEN 18, 32 cls bload "picture.bmp" sleep %% {{fbdoc item="filename" value="examples/manual/gfx/bload2.bas"}}%%(freebasic) 'Load a 48x48 bitmap into an array SCREEN 18, 32 dim myImage as any ptr = imagecreate( 48, 48 ) bload "picture.bmp", myImage put (10,10), myImage imagedestroy( myImage ) sleep %% {{fbdoc item="diff"}} - Support for loading BMP files is new to ""FreeBASIC"". - Support for retrieving the palette from BMP files is new to ""FreeBASIC"". - For non-BMP files, FB uses a different file format, not having the 64 KiB limit, and unsupported by QB {{fbdoc item="see"}} - ##[[KeyPgBsave Bsave]]## - ##[[KeyPgPalette Palette]]## - ##[[GfxInternalFormats Internal Pixel Formats]]## {{fbdoc item="back" value="CatPgGfx2D|2D Drawing Functions"}}{{fbdoc item="title" value="BSAVE"}}---- Saves an array of arbitrary data and palette information to a file on disk {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Bsave** ( [[KeyPgByref byref]] //filename// [[KeyPgAs as]] [[KeyPgString string]], [[KeyPgByval byval]] //source// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]], [[KeyPgByval byval]] //size// [[KeyPgAs as]] [[KeyPgInteger integer]] = 0, [[KeyPgByval byval]] //pal// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] = 0 ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **Bsave**( //filename//, //source// [,[ //size// ][, //pal// ]] ) ## {{fbdoc item="param"}} ##//filename//## the name of the file to create for storing the pixel and palette data. ##//source//## the address of the data to store, or null (##0##) to store pixel data from the current screen work page. ##//size//## the total number of bytes of data to store. ##//pal//## the address of a buffer holding palette information, or null (##0##) to use the current screen palette. {{fbdoc item="ret"}} Returns zero (##0##) if successful, or a non-zero error code to indicate a failure. //[[ProPgErrorHandling (throws a runtime error)]]// {{fbdoc item="desc"}} ##**Bsave**## is used for saving arbitrary data from memory into a file, using a file format specific to FB, or saving images into a standard BMP image file, replacing an existing file if necessary. ##**Bsave**## outputs a __total__ of ##//size//## bytes of arbitrary data located at ##//source//## to a specified file. If ##//source//## is null (##0##), then ##**Bsave**## outputs a __maximum__ of ##//size//## bytes from the current work page's pixel buffer, which is structured in the current screen mode's internal pixel format. Palette information is obtained from ##//pal//## if non-null, or if null (##0##), from the current screen palette. A BMP image file can be created if ##//filename//## has a file extension of """BMP""". ##//source//## is assumed to point to a valid image buffer whose entire pixel data will be stored in the BMP file. If ##//source//## is null (##0##), the entire current work page will be stored instead. Palette information is obtained from ##//pal//## if non-null, or if null (##0##), from the current screen palette. The ##//size//## parameter is ignored when saving BMP files. **Runtime errors:** ##**Bsave**## throws one of the following [[ProPgErrorHandling runtime errors]]: //(##2##) File not found// - The file could not be created. - ##//size//## is less than zero (##0##), or ##//size//## is zero and ##//source//## is non-null. //(##3##) File I/O error// - The file could not be written to. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/bsave.bas"}}%%(freebasic) ' Set gfx mode SCREENRES 320, 200, 32 ' Clear with black on white COLOR RGB(0, 0, 0), RGB(255, 255, 255) CLS LOCATE 13, 15: PRINT "Hello world!" ' Save as BMP BSAVE "hello.bmp", 0 %% {{fbdoc item="diff"}} - Support for saving more than 64KiB of arbitrary data is new to ""FreeBASIC"". - Support for saving BMP files is new to ""FreeBASIC"". - ""QB"" cannot use ##[[KeyPgBload Bload]]## to load files created with ##**Bsave**## in ""FreeBASIC"", but ""FreeBASIC"" can use ##[[KeyPgBload Bload]]## to load files created with ##**Bsave**## in ""QB"" {{fbdoc item="see"}} - ##[[KeyPgBload Bload]]## - ##[[KeyPgPalette Palette]]## {{fbdoc item="back" value="CatPgGfx2D|2D Drawing Functions"}}{{fbdoc item="title" value="BYREF"}}---- Declaration specifier to explicitly pass a parameter by reference {{fbdoc item="syntax"}}## **Byref** //param// [[KeyPgAs as]] [[DataType datatype]] ## {{fbdoc item="usage"}}## [ [[KeyPgDeclare declare]] ] { [[KeyPgSub sub]] | [[KeyPgFunction function]] } //proc_name// ( **Byref** //param// [[KeyPgAs as]] [[DataType datatype]] ) ## {{fbdoc item="desc"}} Passes a variable by reference, that is its address, to a subroutine or function. When a variable is passed by reference, the contents of the variable can be changed by the target subroutine or function. In //[[CompilerOptlang -lang qb]]// and //[[CompilerOptlang -lang fblite]]// dialects, ##**Byref**## is the default parameter passing convention, unless ##[[KeyPgOptionbyval Option ByVal]]## is in effect. Opposite of ##[[KeyPgByval ByVal]]##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/procs/byref.bas"}}%%(freebasic) dim MyVar as integer sub ChangeVar(byref AVar as integer) AVar = AVar + 1 end sub MyVar = 1 print "MyVar: "; MyVar 'output = 1 ChangeVar MyVar print "MyVar: "; MyVar 'output = 2 sleep end %% {{fbdoc item="lang"}} - In //[[CompilerOptlang -lang fb]]// dialect, ##**Byval**## is the default parameter passing convention for all built-in types except ##[[KeyPgString String]]##; String and user-defined ##[[KeyPgType Type]]##s are passed ##[[KeyPgByref Byref]]## by default. - In //[[CompilerOptlang -lang qb]]// and //[[CompilerOptlang -lang fblite]]// dialects, ##**Byref**## is the default parameter passing convention. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - [[ProPgPassingArguments Passing Arguments to Procedures]] - ##[[KeyPgDeclare Declare]]## - ##[[KeyPgByval ByVal]]## {{fbdoc item="back" value="CatPgProcedures|Procedures"}}{{fbdoc item="title" value="BYTE"}}---- Standard data type: 8 bit signed {{fbdoc item="syntax"}}## [[KeyPgDim dim]] //variable// [[KeyPgAs as]] **Byte** ## {{fbdoc item="desc"}} 8-bit signed whole-number data type. Can hold a value in the range of -128 to 127. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/datatype/byte2.bas"}}%%(freebasic) DIM bytevar AS BYTE bytevar = 100 PRINT "bytevar= ", bytevar %% {{fbdoc item="filename" value="examples/manual/datatype/byte.bas"}}%%(freebasic) Dim x As Byte = Cbyte(&H80) Dim y As Byte = CByte(&H7F) Print "Byte Range = "; x; " to "; y %% **Output:** %%Byte Range = -128 to 127%% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Byte""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgUbyte Ubyte]]## - ##[[KeyPgCbyte Cbyte]]## {{fbdoc item="back" value="CatPgStdDataTypes|Standard Data Types"}}{{fbdoc item="title" value="BYVAL"}}---- Declaration specifier to explicitly pass a parameter by value {{fbdoc item="syntax"}}## **Byval** //param// [[KeyPgAs as]] [[DataType datatype]] ## {{fbdoc item="usage"}}## [ [[KeyPgDeclare declare]] ] { [[KeyPgSub sub]] | [[KeyPgFunction function]] } //proc_name// ( **Byval** //param// [[KeyPgAs as]] [[DataType datatype]] ) ## {{fbdoc item="desc"}} ##**Byval**## in a parameter list of a declare statement causes a copy of the variable to be passed to the procedure (for example, a sub or function) by its value. This means that if the value of the variable //##x##// is passed, then the original variable //##x##// will not be modified in any way; however, if the variable were passed ##[[KeyPgByref Byref]]##, the value of the original variable //##x##// could be modified by the called function. For string arguments, ##**Byval**## currently has a different meaning: it passes a pointer to the string, while ##[[KeyPgByref Byref]]## passes a pointer to the FreeBASIC string descriptor. This behavior allows passing a ##**Byval**## ##[[KeyPgString String]]## directly to C procedures. The string passed this way should not be changed by the ##[[KeyPgSub Sub]]##/##[[KeyPgFunction Function]]##, as the string descriptor would not be updated. The meaning of passing a ##[[KeyPgString String]]## ##**Byval**## might change in the future; therefore, passing a ##[[KeyPgString String]]## ##**Byval**## should be avoided. ##[[KeyPgZstring Zstring]]## is more suited for the purpose of passing zero-terminated strings to C functions. Opposite of ##[[KeyPgByref ByRef]]##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/procs/byval.bas"}}%%(freebasic) Sub MySub(byval value as integer) value += 1 End Sub Dim MyVar As Integer MyVar = 1 Print "MyVar: "; MyVar 'output = 1 MySub MyVar Print "MyVar: "; MyVar 'output = 1, because byval won't change the values passed into it globally. Sleep End %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang fb]]// dialect, ##**Byval**## is the default parameter passing convention for all built-in types except ##[[KeyPgString String]]##; String and user-defined ##[[KeyPgType Type]]##s are passed ##[[KeyPgByref Byref]]## by default. - In //[[CompilerOptlang -lang qb]]// and //[[CompilerOptlang -lang fblite]]// dialects, ##**Byref**## is the default parameter passing convention. {{fbdoc item="diff"}} - QB only used ##**Byval**## in declarations to non-Basic subroutines {{fbdoc item="see"}} - [[ProPgPassingArguments Passing Arguments to Procedures]] - ##[[KeyPgDeclare Declare]]## - ##[[KeyPgByref ByRef]]## {{fbdoc item="back" value="CatPgProcedures|Procedures"}}{{fbdoc item="title" value="CALL"}}---- Statement to invoke a subroutine {{fbdoc item="syntax"}}## **Call** //procname// ([//parameter list//]) ## {{fbdoc item="desc"}} Calls a ##[[KeyPgSub Sub]]## or ##[[KeyPgFunction Function]]##. This keyword is a holdover from earlier dialects of BASIC, and is mainly deprecated. In //[[CompilerOptlang -lang qb]]//, it can be used to call ##[[KeyPgSub sub]]##s in code before they are declared. The function will be implicitly ##[[KeyPgDeclare Declare]]##'d, with any parameters passed ##[[KeyPgByref Byref]] As [[KeyPgAny Any]]## {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/procs/callsub.bas"}}%%(freebasic) '' Compile with -lang qb or -lang fblite declare sub foobar(byval x as integer, byval y as integer) call foobar(35, 42) sub foobar(byval x as integer, byval y as integer) print x; y end sub %% {{fbdoc item="filename" value="examples/manual/procs/callfunc.bas"}}%%(freebasic) '' Compile with -lang qb or -lang fblite function f ( ) as integer f = 42 end function call f ' execute function f, but ignore the answer %% {{fbdoc item="filename" value="examples/manual/procs/call-fwd.bas"}}%%(freebasic) '' Compile with -lang qb call mysub(15, 16) '' call "mysub" before it has been declared, or even mentioned. sub mysub(byref a as integer, byref b as integer) print a, b end sub %% {{fbdoc item="lang"}} - The use of ##**Call**## is not allowed in the //[[CompilerOptlang -lang fb]]// dialect. - The //[[CompilerOptlang -lang fblite]]// dialect does not allow you to call functions that have not been previously declared. {{fbdoc item="diff"}} - The procedure must have already been declared. - ##**Call**## in QB will make a copy of all parameters, so changes made to the arguments inside the called ##[[KeyPgSub Sub]]## will not be reflected in the variables in the caller. {{fbdoc item="see"}} - ##[[KeyPgDeclare Declare]]## - ##[[KeyPgSub Sub]]## {{fbdoc item="back" value="CatPgProcedures|Procedures"}}{{fbdoc item="title" value="CALLOCATE"}}---- Allocates memory for a certain number of elements from the free store and clears the contents {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Callocate** [[KeyPgCdecl cdecl]] ( [[KeyPgByval byval]] //num_elements// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByval byval]] //size// [[KeyPgAs as]] [[KeyPgInteger integer]] = 1 ) [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] ## {{fbdoc item="usage"}}## //result// = **Callocate**( //bytes// [, //size// ] ) ## {{fbdoc item="param"}} ##//num_elements//## The number of elements to allocate memory for. ##//size//## The size, in bytes, of each element. {{fbdoc item="ret"}} If successful, the address of the start of the allocated memory is returned. Otherwise, the null pointer (##0##) is returned. {{fbdoc item="desc"}} Similar to ##[[KeyPgAllocate Allocate]]##, ##**Callocate**## initializes the allocated memory with zeros. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/memory/callocate.bas"}}%%(freebasic) ' Allocate and initialize space for 10 integer elements. dim p as integer ptr = callocate(10, sizeof(integer)) ' Fill the memory with integer values. for index as integer = 0 to 9 p[index] = (index + 1) * 10 next ' Display the integer values. for index as integer = 0 to 9 print p[index] ; next ' Free the memory. deallocate(p) %% Outputs: %% 10 20 30 40 50 60 70 80 90 100%% {{fbdoc item="target"}} - This procedure is not guaranteed to be thread-safe. {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Callocate""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgAllocate Allocate]]## - ##[[KeyPgDeallocate Deallocate]]## - ##[[KeyPgReallocate Reallocate]]## {{fbdoc item="back" value="CatPgMemory|Memory Functions"}}{{fbdoc item="title" value="CASE"}}---- Control flow statement {{fbdoc item="syntax"}}## **Case** //expression// ## {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgSelectcase Select Case]]## {{fbdoc item="back" value="CatPgControlFlow|Control Flow"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:49:40 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: ae34809510b30226edb6206d8b23bae5 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 917 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="CAST"}}---- Converts an expression to a specified data type {{fbdoc item="syntax"}}## Cast( [[DataType datatype]], //expression// ) ## {{fbdoc item="desc"}} Converts ##//expression//## to a ##[[DataType datatype]]##. Useful to be used in macros when ##[[DataType datatype]]## is unknown and also when converting to [[KeyPgTypeAlias Type Alias]]. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/casting/cast.bas"}}%%(freebasic) '' will print -128 because the integer literal will be converted to a signed byte print cast( byte, &h0080 ) %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Cast""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgCptr Cptr]]## - ##[[KeyPgCint Cint]]## {{fbdoc item="back" value="CatPgCasting|Converting Data Types"}} {{fbdoc item="title" value="CBYTE"}}---- Converts numeric or string expression to ##[[KeyPgByte Byte]]##. {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Cbyte** ( [[KeyPgByval byval]] //expression// [[KeyPgAs as]] [[DataType datatype]] ) [[KeyPgAs as]] [[KeyPgByte byte]] [[KeyPgType Type]] //typename// [[KeyPgDeclare declare]] [[KeyPgOperator operator]] [[KeyPgCast cast]] ( ) [[KeyPgAs as]] [[KeyPgByte byte]] End Type ## {{fbdoc item="usage"}}## //result// = **Cbyte**( //numeric expression// ) //result// = **Cbyte**( //string expression// ) //result// = **Cbyte**( //user defined type// ) ## {{fbdoc item="param"}} ##//expression//## A numeric, string, or pointer expression to cast to a ##[[KeyPgByte Byte]]## value. ##//datatype//## Any numeric, string, or pointer data type. ##//typename//## A user defined type. {{fbdoc item="ret"}} A ##[[KeyPgByte Byte]]## value. {{fbdoc item="desc"}} The ##**Cbyte**## function rounds off the decimal part and returns a 8 bit ##[[KeyPgByte Byte]]## value. The function does not check for an overflow, so be sure not to pas a value thats less/larger then -128 to 127. The name can be explained as 'Convert to Byte'. If the argument is a string expression, it is converted to numeric by using ##[[KeyPgValint Valint]]##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/casting/cbyte.bas"}}%%(freebasic) ' Using the CBYTE function to convert a numeric value 'Create an BYTE variable DIM numeric_value AS BYTE 'Convert a numeric value numeric_value = CBYTE(-66.30) 'Print the result, should return -66 PRINT numeric_value SLEEP %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Cbyte""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgCubyte Cubyte]]## - ##[[KeyPgCshort Cshort]]## - ##[[KeyPgCushort Cushort]]## - ##[[KeyPgCint Cint]]## - ##[[KeyPgCuint Cuint]]## - ##[[KeyPgClng Clng]]## - ##[[KeyPgCulng Culng]]## - ##[[KeyPgClngint Clngint]]## - ##[[KeyPgCulngint Culngint]]## - ##[[KeyPgCsng Csng]]## - ##[[KeyPgCdbl Cdbl]]## {{fbdoc item="back" value="CatPgCasting|Converting Data Types"}}{{fbdoc item="title" value="CDBL"}}---- Converts numeric or string expression to ##[[KeyPgDouble Double]]## precision floating point {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Cdbl** ( [[KeyPgByval byval]] //expression// [[KeyPgAs as]] [[DataType datatype]] ) [[KeyPgAs as]] [[KeyPgDouble double]] [[KeyPgType Type]] //typename// [[KeyPgDeclare declare]] [[KeyPgOperator operator]] [[KeyPgCast cast]] ( ) [[KeyPgAs as]] [[KeyPgDouble double]] End Type ## {{fbdoc item="usage"}}## //result// = **Cdbl**( //numeric expression// ) //result// = **Cdbl**( //string expression// ) //result// = **Cdbl**( //user defined type// ) ## {{fbdoc item="param"}} ##//expression//## a numeric, string, or pointer expression to cast to a ##[[KeyPgDouble Double]]## value ##//datatype//## any numeric, string, or pointer data type ##//typename//## a user defined type {{fbdoc item="ret"}} A ##[[KeyPgDouble Double]]## precision value. {{fbdoc item="desc"}} The ##**CDbl**## function returns a 64-bit ##[[KeyPgDouble Double]]## value. The function does not check for an overflow, so be sure not to pass a value outside the representable range of the ##[[KeyPgDouble Double]]## data type. The name can be explained as 'Convert to ""DouBLe""'. If the argument to ##**CDbl**## is a string expression, it is first converted to numeric by using ##[[KeyPgVal Val]]##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/casting/cdbl.bas"}}%%(freebasic) ' Using the CDBL function to convert a numeric value 'Create an DOUBLE variable DIM numeric_value AS DOUBLE 'Convert a numeric value numeric_value = CDBL(-12345678.123) 'Print the result, should return -12345678.123 PRINT numeric_value SLEEP %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgCbyte Cbyte]]## - ##[[KeyPgCubyte Cubyte]]## - ##[[KeyPgCshort Cshort]]## - ##[[KeyPgCushort Cushort]]## - ##[[KeyPgCint Cint]]## - ##[[KeyPgCuint Cuint]]## - ##[[KeyPgClng Clng]]## - ##[[KeyPgCulng Culng]]## - ##[[KeyPgClngint Clngint]]## - ##[[KeyPgCulngint Culngint]]## - ##[[KeyPgCsng Csng]]## {{fbdoc item="back" value="CatPgCasting|Converting Data Types"}}{{fbdoc item="title" value="CDECL"}}---- Specifies a //cdecl//-style calling convention in a procedure declaration {{fbdoc item="syntax"}}## [[KeyPgDeclare Declare]] [[[KeyPgStatic Static]]] [[KeyPgSub Sub]] //procedure_name// [[[KeyPgOverload Overload]]] **Cdecl** [[[KeyPgAlias Alias]] //"""external_name"""//] [([//parameter_list//])] [[[KeyPgModuleConstructor Constructor]] [//priority//]] [[[KeyPgStatic Static]]] [[[KeyPgExport Export]]] [[KeyPgDeclare Declare]] [[[KeyPgStatic Static]]] [[KeyPgFunction Function]] //procedure_name// [[[KeyPgOverload Overload]]] **Cdecl** [[[KeyPgAlias Alias]] //"""external_name"""//] [([//parameter_list//])] [[KeyPgAs as]] //return_type// [[[KeyPgStatic Static]]] [[[KeyPgExport Export]]] [[[KeyPgPublic Public]]|[[KeyPgPrivate Private]]] [[KeyPgSub Sub]] //procedure_name// [[[KeyPgOverload Overload]]] **Cdecl** [[[KeyPgAlias Alias]] //"""external_name"""//] [([//parameter_list//])] [[[KeyPgModuleConstructor Constructor]] [//priority//]] [[[KeyPgStatic Static]]] [[[KeyPgExport Export]]] //..procedure body..// [[KeyPgEnd End]] [[KeyPgSub Sub]] [[[KeyPgPublic Public]]|[[KeyPgPrivate Private]]] [[KeyPgFunction Function]] //procedure_name// [[[KeyPgOverload Overload]]] **Cdecl** [[[KeyPgAlias Alias]] //"""external_name"""//] [([//parameter_list//])] [[KeyPgAs as]] //return_type// [[[KeyPgStatic Static]]] [[[KeyPgExport Export]]] //..procedure body..// [[KeyPgEnd End]] [[KeyPgFunction Function]] ## {{fbdoc item="desc"}} In procedure declarations, ##**Cdecl**## specifies that a procedure will use the ##**cdecl**## calling convention. In the ##**cdecl**## calling convention, any parameters are to be passed (pushed onto the stack) in the reverse order in which they are listed, that is, from right to left. The procedures need not preserve the ##EAX##, ##ECX## or ##EDX## registers, and must not clean up the stack (pop any parameters) before it returns - that is left to the calling code. ##**cdecl**## is the default calling convention for procedures declared within ##[[KeyPgExternBlock Extern "C"]]## and ##[[KeyPgExternBlock Extern "C++"]]## blocks. ##**cdecl**## is also typically the default calling convention for many C compilers. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/procs/cdecl.bas"}}%%(freebasic) ' declaring 'strcpy' from the standard C library Declare Function strcpy cdecl Alias "strcpy" (ByVal dest As ZString Ptr, ByVal src As ZString Ptr) As ZString Ptr %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - [[KeyPgPascal Pascal]], [[KeyPgStdcall Stdcall]] - [[KeyPgDeclare Declare]] - [[KeyPgSub Sub]], [[KeyPgFunction Function]] {{fbdoc item="back" value="CatPgProcedures|Procedures"}}{{fbdoc item="title" value="CHAIN"}}---- Temporarily transfers control to an external program {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Chain** ( [[KeyPgByref byref]] //program// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **Chain**( //program// ) ## {{fbdoc item="param"}} ##//program//## The file name (including file path) of the program (executable) to transfer control to. {{fbdoc item="ret"}} Returns the external program's exit code if executed successfully, or negative one (-1) otherwise. {{fbdoc item="desc"}} Transfers control over to an external program. When the program exits, execution resumes immediately after the call to ##**Chain**##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/system/chain.bas"}}%%(freebasic) #ifdef FB__LINUX #define CHAIN2 "chain2" #else #define CHAIN2 "chain2.exe" #endif print "chain1 begins" chain CHAIN2 print "chain1 ends" sleep %% {{fbdoc item="target"}} - Linux requires the ##//program//## name case matches the real name of the file. Windows and DOS are case insensitive. The program chained may be case sensitive for its command line parameters. - Path separators in Linux are forward slashes / . Windows uses backward slashes \ but it allows for forward slashes . DOS uses backward \ slashes. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgExec Exec]]## - ##[[KeyPgRun Run]]## {{fbdoc item="back" value="CatPgOpsys|Operating System Functions"}}{{fbdoc item="title" value="CHDIR"}}---- Changes the current drive and directory {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Chdir** ( [[KeyPgByref byref]] //path// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **Chdir**( //path// ) ## {{fbdoc item="param"}} ##//path//## A ##[[KeyPgString string]]## argument specifying the path to change to. {{fbdoc item="ret"}} Returns zero (0) on success and negative one (-1) on failure. {{fbdoc item="desc"}} Changes the current drive and directory to that specified. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/system/chdir.bas"}}%%(freebasic) Dim pathname As String = "x:\folder" Dim result As Integer = ChDir(pathname) If 0 <> result Then Print "error changing current directory to " & pathname & "." %% {{fbdoc item="target"}} - Linux requires the //filename// case matches the real name of the file. Windows and DOS are case insensitive. - Path separators in Linux are forward slashes / . Windows uses backward slashes \ but it allows for forward slashes . DOS uses backward \ slashes. {{fbdoc item="diff"}} - In QB, the drive could not be specified. {{fbdoc item="see"}} - ##[[KeyPgMkdir Mkdir]]## - ##[[KeyPgRmdir Rmdir]]## {{fbdoc item="back" value="CatPgOpsys|Operating System Functions"}}{{fbdoc item="title" value="CHR"}}---- Returns a string of characters from one or more ASCII integer values {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Chr** ( [[KeyPgByval byval]] //ch// [[KeyPgAs as]] [[KeyPgInteger integer]] [, ... ] ) [[KeyPgAs as]] [[KeyPgString string]] ## {{fbdoc item="usage"}}## //result// = **Chr**[$]( //ch0// [, //ch1// ... //chN// ] ) ## {{fbdoc item="param"}} ##//ch//## The [[CptAscii ASCII]] integer value of a character. {{fbdoc item="ret"}} Returns a string containing the character(s). {{fbdoc item="desc"}} ##**Chr**## returns a string containing the character(s) represented by the [[CptAscii ASCII]] values passed to it. When ##**Chr**## is used with numerical constants or literals, the result is evaluated at compile-time, so it can be used in variable initializers. ##[[KeyPgAsc ASC]]## performs the opposite function, returning the [[CptAscii ASCII]] code of a character represented by a string. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/chr.bas"}}%%(freebasic) print "the character represented by"; print " the ASCII code of 97 is: "; CHR(97) print chr(97, 98, 99) ' prints abc ' s initially has the value "abc" dim s as string = chr(97, 98, 99) print s %% {{fbdoc item="lang"}} - The string type suffix "$" is obligatory in the //[[CompilerOptlang -lang qb]]// dialect. - The string type suffix "$" is optional in the //[[CompilerOptlang -lang fblite]]// and //[[CompilerOptlang -lang fb]]// dialects. {{fbdoc item="diff"}} - FreeBASIC accepts multiple integer values as arguments, QB accepted only one. - FreeBASIC evaluates the CHR function at compile time when used with constants or literals. {{fbdoc item="see"}} - [[CptAscii ASCII Character Codes]] - ##[[KeyPgAsc Asc]]## - ##[[KeyPgStr Str]]## - ##[[KeyPgVal Val]]## {{fbdoc item="back" value="CatPgString|String Functions"}}{{fbdoc item="title" value="CINT"}}---- Converts numeric or string expression to an ##[[KeyPgInteger Integer]]## {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Cint** ( [[KeyPgByval byval]] //expression// [[KeyPgAs as]] [[DataType datatype]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgType Type]] //typename// [[KeyPgDeclare declare]] [[KeyPgOperator operator]] [[KeyPgCast cast]] ( ) [[KeyPgAs as]] [[KeyPgInteger integer]] End Type ## {{fbdoc item="usage"}}## //result// = **Cint**( //numeric expression// ) //result// = **Cint**( //string expression// ) //result// = **Cint**( //user defined type// ) ## {{fbdoc item="param"}} ##//expression//## a numeric, string, or pointer expression to cast to a ##[[KeyPgInteger Integer]]## value ##//datatype//## any numeric, string, or pointer data type ##//typename//## a user defined type {{fbdoc item="ret"}} An ##[[KeyPgInteger Integer]]## value. {{fbdoc item="desc"}} The ##**Cint**## function rounds off the decimal part of ##//numeric expression//## and returns a 32-bit ##[[KeyPgInteger Integer]]##. The function does not check for an overflow, so be sure not to pass a value which is less than -2 147 483 648 or larger than 2 147 483 647. The name is derived from 'Convert to INTeger'. If the argument is a string expression, it is converted to numeric by using ##[[KeyPgValint Valint]]##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/casting/cint.bas"}}%%(freebasic) ' Using the CINT function to convert a numeric value 'Create an INTEGER variable DIM numeric_value AS INTEGER 'Convert a numeric value numeric_value = CINT(-300.23) 'Print the result, should return -300 PRINT numeric_value SLEEP %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, ##**Cint**## will return a 16-bit integer, like in QB. {{fbdoc item="diff"}} - The string argument was not allowed in QB {{fbdoc item="see"}} - ##[[KeyPgCbyte Cbyte]]## - ##[[KeyPgCubyte Cubyte]]## - ##[[KeyPgCshort Cshort]]## - ##[[KeyPgCushort Cushort]]## - ##[[KeyPgCuint Cuint]]## - ##[[KeyPgClng Clng]]## - ##[[KeyPgCulng Culng]]## - ##[[KeyPgClngint Clngint]]## - ##[[KeyPgCulngint Culngint]]## - ##[[KeyPgCsng Csng]]## - ##[[KeyPgCdbl Cdbl]]## {{fbdoc item="back" value="CatPgCasting|Converting Data Types"}}{{fbdoc item="title" value="CIRCLE"}}---- Graphics statement to draw a circle {{fbdoc item="syntax"}}## **Circle** [//target//,] [STEP] (x,y), radius[, [color][, [start][, [end][, [aspect][, F]]]]] ## {{fbdoc item="param"}} ##//target//## specifies buffer to draw on. ##STEP## indicates that coordinates are relative ##(//x, y//)## coordinates of the circle's center. ##//radius//## radius ##//color//## the color attribute. ##//start//## starting angle ##//end//## ending angle ##//aspect//## aspect ratio ##F## fill mode indicator {{fbdoc item="desc"}} ##**Circle**## will draw a circle, ellipse, or arc based on the parameters given to it. ##//target//## specifies buffer to draw on. ##//target//## may be an image created with ##[[KeyPgImagecreate Imagecreate]]## or ##[[KeyPgGetgraphics Get (Graphics)]]##. If omitted, ##//target//## defaults to the screen's current work page. (See ##[[KeyPgScreenset Screenset]]##) The center of the shape will be placed on the destination surface at ##(//X//,//Y//)##. ##//Radius//## denotes the radius of the shape. If aspect ratio is used, the biggest radius must be given here. ##//Color//## denotes the color attribute, which is mode specific (see ##[[KeyPgColor Color]]## and ##[[KeyPgScreengraphics Screen (Graphics)]]## for details). If omitted, the current foreground color as set by the ##[[KeyPgColor Color]]## statement is used. The ##STEP## option specifies that ##//X//## and ##//Y//## are offsets relative to the current graphics cursor position. ##//start//## and ##//end//## are angles are in ##[[ProPgRadians radians]]##. These can range -2PI to 2PI; if you specify a negative angle, its value is changed sign and a line is drawn from the center up to that point in the arc. End angle can be less than start angle. If you do not specify start and end, a full circle/ellipse is drawn; if you you specify start but not end, end is assumed to be 2PI; if you specify end but not start, start is assumed to be 0. ##//aspect//## is the aspect ratio, or the ratio of the y radius over the x radius. The default value is the value required to draw a perfect circle on the screen, keeping pixel aspect ratio in mind. This value can be calculated as follows: ##ratio = (y_radius / x_radius) * pixel_aspect_ratio## Where pixel_aspect_ratio is the ratio of the current mode width over the current mode height, assuming a 4:3 standard monitor. If aspect ratio is less than 1, radius is the x radius; if aspect is more or equal to 1, radius is the y radius. 'f' is the fill flag. If you specify this flag, the circle/ellipse will be filled with the selected color. This has no effect if you're drawing an arc. Custom coordinates system set up by ##[[KeyPgWindow Window]]## and/or ##[[KeyPgViewgraphics View (Graphics)]]## affect the drawing operation; clipping set by ##[[KeyPgViewgraphics View]]## also applies. When ##**Circle**## finishes drawing, the current graphics cursor position is set to the supplied center. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/circle.bas"}}%%(freebasic) ' Set 640x480 mode, 256 colors screen 18 ' Draws a circle in the center circle (320, 240), 200, 15 ' Draws a filled ellipse circle (320, 240), 200, 2, , , 0.2, F ' Draws a small arc circle (320, 240), 200, 4, 0.83, 1.67, 3 sleep %% {{image class="center" title="Circle example output" url="/images/circle.png"}} {{fbdoc item="diff"}} - As the FreeBASIC implementation obviously uses a different algorithm for ellipse/arc drawing than QB, the result may not be equal to QB for every pixel. - The F flag to draw filled circles/ellipses is new in FreeBASIC. - ##//target//## new to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgScreengraphics Screen (Graphics)]]## - ##[[KeyPgColor Color]]## {{fbdoc item="back" value="CatPgGfx2D|2D Drawing Functions"}}{{fbdoc item="title" value="CLASS"}}---- Declares a class object {{fbdoc item="syntax"}}## **Class** //typename// ... ## {{fbdoc item="param"}} ##//typename//## name of the ##**Class**## {{fbdoc item="desc"}} We would have put something useful here (honest) except this feature isn't implemented in the compiler yet. But since it will get added in future, and there are several other document pages that need to link here, we thought it safe to include in anyway. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/check/KeyPgClass_1.bas"}}%%(freebasic) '' sample code %% Output: %% sample output %% {{fbdoc item="lang"}} - Object-related features are supported only in the //[[CompilerOptlang -lang fb]]// option {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgEnum Enum]]## - ##[[KeyPgType Type]]##{{fbdoc item="title" value="CLEAR"}}---- Clears or initializes some memory {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Clear** [[KeyPgCdecl cdecl]] ( [[KeyPgByref byref]] //dst// [[KeyPgAs as]] [[KeyPgAny any]], [[KeyPgByval byval]] //value// [[KeyPgAs as]] [[KeyPgInteger integer]] = 0, [[KeyPgByval byval]] //bytes// [[KeyPgAs as]] [[KeyPgInteger integer]] ) ## {{fbdoc item="usage"}}## **Clear**( //dst//, //value//, //bytes// ) ## {{fbdoc item="param"}} ##//dst//## starting address of some memory ##//value//## the value to set all bytes equal to ##//bytes//## number of bytes to clear {{fbdoc item="desc"}} ##**Clear**## sets one or more bytes in memory to a certain value (the default value is zero (0) if not specified). The starting address is taken from a reference to a variable or array element. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/array/clear.bas"}}%%(freebasic) dim array(1 to 100) as integer clear array(1), 0, len(array(1)) * ubound(array) %% {{fbdoc item="diff"}} -New to FreeBASIC -The keyword ##CLEAR## was used in QB to erase all variables, close all files, and optionally change the stack size. This use is not supported in FreeBASIC. {{fbdoc item="see"}} - ##[[KeyPgErase Erase]]## - ##[[KeyPgReset Reset]]## {{fbdoc item="back" value="CatPgMemory|Memory Functions"}}{{fbdoc item="title" value="CLNG"}}---- Converts numeric or string expression to ##[[KeyPgLong Long]]## having the same size as ##[[KeyPgSizeof Sizeof]]([[KeyPgAny Any]] [[KeyPgPtr Ptr]])## {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Clng** ( [[KeyPgByval byval]] //expression// [[KeyPgAs as]] [[DataType datatype]] ) [[KeyPgAs as]] [[KeyPgLong long]] [[KeyPgType Type]] //typename// [[KeyPgDeclare declare]] [[KeyPgOperator operator]] [[KeyPgCast cast]] ( ) [[KeyPgAs as]] [[KeyPgLong long]] End Type ## {{fbdoc item="usage"}}## //result// = **Clng**( //numeric expression// ) //result// = **Clng**( //string expression// ) //result// = **Clng**( //user defined type// ) ## {{fbdoc item="param"}} ##//expression//## a numeric, string, or pointer expression to cast to a ##[[KeyPgLong Long]]## value ##//datatype//## any numeric, string, or pointer data type ##//typename//## a user defined type {{fbdoc item="ret"}} A ##[[KeyPgLong Long]]## value. {{fbdoc item="desc"}} The ##**Clng**## function rounds off the decimal part and returns a 32 bit ##[[KeyPgInteger Integer]]## or 64 bit ##[[KeyPgLongint Longint]]## value. The function does not check for an overflow. The name can be explained as 'Convert to ""LoNG""'. If the argument is a string expression, it is converted to numeric by using ##[[KeyPgValint Valint]]## or ##[[KeyPgVallng Vallng]]##. ##**Long**## has the same size as ##[[KeyPgSizeof Sizeof]]([[KeyPgAny Any]] [[KeyPgPtr Ptr]])##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/casting/clng.bas"}}%%(freebasic) ' Using the CLNG function to convert a numeric value 'Create an LONG variable DIM numeric_value AS LONG 'Convert a numeric value numeric_value = CLNG(-300.23) 'Print the result, should return -300 PRINT numeric_value SLEEP %% {{fbdoc item="diff"}} - The string argument was not allowed in QB - LONG is always 32 bit in QB {{fbdoc item="see"}} - ##[[KeyPgCbyte Cbyte]]## - ##[[KeyPgCubyte Cubyte]]## - ##[[KeyPgCshort Cshort]]## - ##[[KeyPgCushort Cushort]]## - ##[[KeyPgCint Cint]]## - ##[[KeyPgCuint Cuint]]## - ##[[KeyPgCulng Culng]]## - ##[[KeyPgClngint Clngint]]## - ##[[KeyPgCulngint Culngint]]## - ##[[KeyPgCsng Csng]]## - ##[[KeyPgCdbl Cdbl]]## {{fbdoc item="back" value="CatPgCasting|Converting Data Types"}}{{fbdoc item="title" value="CLNGINT"}}---- Converts numeric or string expression to 64-bit integer (##[[KeyPgLongint Longint]]##) {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Clngint** ( [[KeyPgByval byval]] //expression// [[KeyPgAs as]] [[DataType datatype]] ) [[KeyPgAs as]] [[KeyPgLongint longint]] [[KeyPgType Type]] //typename// [[KeyPgDeclare declare]] [[KeyPgOperator operator]] [[KeyPgCast cast]] ( ) [[KeyPgAs as]] [[KeyPgLongint longint]] End Type ## {{fbdoc item="usage"}}## //result// = **Clngint**( //numeric expression// ) //result// = **Clngint**( //string expression// ) //result// = **Clngint**( //user defined type// ) ## {{fbdoc item="param"}} ##//expression//## a numeric, string, or pointer expression to cast to a ##[[KeyPgLongint Longint]]## value ##//datatype//## any numeric, string, or pointer data type ##//typename//## a user defined type {{fbdoc item="ret"}} A ##[[KeyPgLongint Longint]]## value. {{fbdoc item="desc"}} The ##**Clngint**## function rounds off the decimal part and returns a 64 bit ##[[KeyPgLongint Longint]]## value. The function does not check for an overflow, so be sure not to pas a value thats less/larger than -9 223 372 036 854 775 808 to 9 223 372 036 854 775 807. The name can be explained as 'Convert to ""LoNG INTeger""'. If the argument is a string expression, it is converted to numeric by using ##[[KeyPgVallng Vallng]]##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/casting/clngint.bas"}}%%(freebasic) ' Using the CLNGINT function to convert a numeric value 'Create an LONG INTEGER variable DIM numeric_value AS LONGINT 'Convert a numeric value numeric_value = CLNGINT(-12345678.123) 'Print the result, should return -12345678 PRINT numeric_value SLEEP %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Clngint""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgCbyte Cbyte]]## - ##[[KeyPgCubyte Cubyte]]## - ##[[KeyPgCshort Cshort]]## - ##[[KeyPgCushort Cushort]]## - ##[[KeyPgCint Cint]]## - ##[[KeyPgCuint Cuint]]## - ##[[KeyPgClng Clng]]## - ##[[KeyPgCulng Culng]]## - ##[[KeyPgCulngint Culngint]]## - ##[[KeyPgCsng Csng]]## - ##[[KeyPgCdbl Cdbl]]## {{fbdoc item="back" value="CatPgCasting|Converting Data Types"}}{{fbdoc item="title" value="CLOSE"}}---- Stream I/O function to terminate access to a device {{fbdoc item="syntax"}}## **Close** [[#]//filenum// ] [, [#]//filenum// ...] ## {{fbdoc item="param"}} ##//filenum//## list of file numbers to close {{fbdoc item="desc"}} Closes the files whose file numbers are passed as arguments. If an unused file number is passed, ##**Close**## returns an error. ##**Close**## without arguments closes all the files presently opened. Terminating the program using an ##[[KeyPgEnd End]]## statement will automatically close all files. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/fileio/close.bas"}}%%(freebasic) ' Create a string and fill it. Dim buffer As String, f as integer buffer = "Hello World within a file." ' Find the first free file number. f = Freefile ' Open the file "file.ext" for binary usage, using the number "f". Open "file.ext" For Binary As #f ' Place our string inside the file, using number "f". Put #f, , buffer ' Close the file. We could also do 'Close #f', but it's only necessary if more than one number is open. Close ' End the program. (Check the file "file.ext" upon running to see the output.) End %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgOpen Open]]## - ##[[KeyPgPutfileio Put (File I/O)]]## - ##[[KeyPgGetfileio Get (File I/O)]]## - ##[[KeyPgFreefile Freefile]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}}{{fbdoc item="title" value="CLS"}}---- Clears the screen in both text modes and graphics modes {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Cls** ( [[KeyPgByval byval]] //mode// [[KeyPgAs as]] [[KeyPgInteger integer]] = 0 ) ## {{fbdoc item="usage"}}## **Cls** //mode// ## {{fbdoc item="param"}} ##//mode//## A optional numeric variable with a value from 0 to 2. {{fbdoc item="desc"}} An optional //mode// parameter may be given, If omitted, CLS clears either the text or graphics viewport. If a graphics viewport has been defined using the ##[[KeyPgViewgraphics View (Graphics)]]## statement, the graphics viewport is cleared. Otherwise, if a text viewport has been defined, it is cleared. Otherwise, the entire screen is cleared. If 0, clears the entire screen If 1, clears the graphics viewport if defined. Otherwise, clears the entire screen. If 2, clears the text viewport {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/console/cls.bas"}}%%(freebasic) Color , 1 Cls Locate 12, 35 Print "Hello Universe!" %% Using C's ##memset## instead of CLS might give you a speed boost: {{fbdoc item="filename" value="examples/manual/gfx/cls-memset.bas"}}%%(freebasic) #include "crt.bi" Const x_res = 640, y_res = 480, bpp = 32 Dim scrbuf As Any Ptr, scrsize As Integer Dim i As Integer, j As Integer ScreenRes x_res, y_res, bpp scrbuf = ScreenPtr scrsize = x_res * y_res * bpp / 8 Do ScreenLock memset scrbuf, 0, scrsize Circle (320, 240), i ScreenUnlock If j = 0 Then i = i + 1 If i >= 100 Then j = 1 ElseIf j = 1 Then i = i - 1 If i <= 0 Then j = 0 End If Sleep 1, 1 Loop While Inkey=""%% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgColor Color]]## - ##[[KeyPgLocate Locate]]## - ##[[KeyPgPrint Print]]## - ##[[KeyPgViewgraphics View (Graphics)]]## {{fbdoc item="back" value="CatPgConsole|Console Functions"}}{{fbdoc item="back" value="CatPgGfxScreen|Screen Functions Index"}}{{fbdoc item="title" value="COLOR"}}---- Sets the display foreground / background color that is used with console output and graphics output of text {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Color** ( [[KeyPgByval byval]] //foreground// [[KeyPgAs as]] [[KeyPgInteger integer]] , [[KeyPgByval byval]] //background// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## **Color** [//foreground//] [, //background//] //result// = **Color** [( [//foreground//] [, //background//] )] ## {{fbdoc item="param"}} ##//foreground//## the foreground color to set ##//background//## the background color to set {{fbdoc item="ret"}} Returns a 32 bit ##[[KeyPgInteger Integer]]## containing the current foreground color in the [[KeyPgLoWord low word]] and the current background color in the [[KeyPgHiword high word]]. The old color values can be retrieved at the same time as setting new ones. {{fbdoc item="desc"}} The ##**Color**## statement sets the current foreground and/or background colors. ##[[KeyPgCircle Circle]]##, ##[[KeyPgDraw Draw]]##, ##[[KeyPgLinegraphics Line (Graphics)]]##, ##[[KeyPgCls Cls]]##, ##[[KeyPgPaint Paint]]##, ##[[KeyPgPrint Print]]##, ##[[KeyPgPreset PReset]]## and ##[[KeyPgPset PSet]]## all use the last colors set by this function when you don't specify a color to them, where applicable. The color values that ##**Color**## accepts depend on the current graphics mode. {{table columns="2" cellpadding="1" cells="Mode;Meaning;1;foreground is screen color (ranging 0-15). background modulo 4 is the emulated CGA palette to be used: 0 (green, red, and brown), 1 (cyan, magenta and white), 2 (same as 0, but with bright colors) or 3 (same as 1, but with bright colors);2, 11;foreground is a color index in current palette (ranging 0-1). background is a color index in current palette (ranging 0-1).;7, 8;foreground is a color index in current palette (ranging 0-15). background is screen color index in current palette (ranging 0-15).;9;foreground is a color index in current palette (ranging 0-63). background is screen color index in current palette (ranging 0-63).;12;foreground is a color index in current palette (ranging 0-15). background is a color index in current palette (ranging 0-15).;13 and up;foreground is a color index in current palette (ranging 0-255). background is a color index in current palette (ranging 0-255)."}} If you are using a color depth higher than 8bpp, foreground and background are direct ##[[KeyPgRgb RGB]]## color values in the form ##&hAARRGGBB##, where ##AA##, ##RR##, ##GG## and ##BB## are the alpha, red, green and blue components ranging ##&h00-&hFF## (0-255 in decimal notation). While in hi/truecolor modes, you can use the ##[[KeyPgRgb RGB]]## or ##[[KeyPgRgba RGBA]]## macro to obtain a valid color value. A [[GfxDefPalettes Default Palette]] is automatically set when entering a ##[[KeyPgScreengraphics Screen]]## mode. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/color.bas"}}%%(freebasic) ' Sets 320x240 in 32bpp color depth screen 14, 32 ' Sets orange foreground and dark blue background color color RGB(255, 128, 0), RGB(0, 0, 64) ' Clears the screen to the background color cls ' Prints "Hello World!" in the middle of the screen locate 15, 14 print "Hello World!" sleep %% {{image class="center" title="Color example" url="/images/color.png"}} {{fbdoc item="filename" value="examples/manual/console/color.bas"}}%%(freebasic) Dim c As Uinteger 'retrieve current color values c = Color() 'extract color values from c using LOWORD and HIWORD Print "Console colors:" Print "Foreground: " & LOWORD(c) Print "Background: " & HIWORD(c) %% {{fbdoc item="diff"}} - Direct color modes were not supported in QB. - There is no border argument. {{fbdoc item="see"}} - ##[[KeyPgRgb RGB]]## - ##[[KeyPgRgba RGBA]]## - ##[[KeyPgLoWord LOWORD]]## - ##[[KeyPgHiword HIWORD]]## - ##[[KeyPgLocate Locate]]## - ##[[KeyPgPalette Palette]]## - ##[[KeyPgScreengraphics Screen]]## {{fbdoc item="back" value="CatPgGfx2D|2D Drawing Functions"}}{{fbdoc item="back" value="CatPgConsole|Console Functions"}}{{fbdoc item="title" value="COMMAND"}}---- Returns command line parameters used to call the program {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Command** ( [[KeyPgByval byval]] //index// [[KeyPgAs as]] [[KeyPgInteger integer]] = -1 ) [[KeyPgAs as]] [[KeyPgString string]] ## {{fbdoc item="usage"}}## //result// = **Command**[$]( [ //index// ] ) ## {{fbdoc item="param"}} ##//index//## Zero-based index for a particular command-line argument. {{fbdoc item="ret"}} Returns the command-line arguments(s). {{fbdoc item="desc"}} ##**Command**## returns command-line arguments passed to the program upon execution. If ##//index//## is less than zero (< 0), a space-separated list of all command-line arguments is returned, otherwise, a single argument is returned. A value of zero (0) returns the name of the executable; and values of one (1) and greater return each command-line argument. If ##//index//## is greater than the number of arguments passed to the program, the null string (##"####"##) is returned. When the command line is parsed for arguments, everything between double quotes in the parameter list will be considered as a single parameter, and is returned with the double quotes. By default, filename globbing for arguments (expansion of wildcards to filenames) is used on all ports of FreeBASIC for compatibility. Arguments on the command line containing wildcards are typically not expanded if when no file is matched or if properly quoted. Other special characters for redirection are typically not returned unless properly quoted. Consult the documentation on the shell being used for more information on the proper quoting of command line arguments. ~&//**WARNING**: By nature of constructor precedence in FreeBASIC and main() initialization, calling ##**Command**## within a global constructor is not safe. At the moment your app will not crash, but you will only receive the null string (##"####"##). This *may* be able to be fixed in the future, but it would be wise not to rely on that.// __Disabling filename globbing under Win32__ For mingw32 and cygwin builds, link the FreeBASIC program with CRT_noglob.o or define the following somewhere in the source: {{fbdoc item="filename" value="examples/manual/check/KeyPgCommand_1.bas"}}%%(freebasic) Extern _CRT_glob Alias "_CRT_glob" As Integer Dim Shared _CRT_glob As Integer = 0 %% __Disabling filename globbing under Dos__ Define the following function somewhere in the source: {{fbdoc item="filename" value="examples/manual/check/KeyPgCommand_2.bas"}}%%(freebasic) Public Function __crt0_glob_function Alias "__crt0_glob_function" ( ByVal arg As UByte Ptr ) As UByte Ptr Ptr Return 0 End Function %% __Disabling filename globbing under Linux__ Filename globbing is handled by the command shell. Quote the argument containing wildcards or disable filename globbing in the shell prior to executing the command. For example in bash use 'set -f' to disable wildcard expansion {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/system/command.bas"}}%%(freebasic) '' '' command-line arguments example '' print "exe name= "; command( 0 ) dim argc as integer, argv as string argc = 1 do argv = command( argc ) if( len( argv ) = 0 ) then exit do end if print "arg"; argc; " = """; argv; """" argc += 1 loop if( argc = 1 ) then print "(no arguments)" end if print "The complete list: ";command %% {{fbdoc item="lang"}} - The string type suffix "$" is obligatory in the //[[CompilerOptlang -lang qb]]// dialect. - The string type suffix "$" is optional in the //[[CompilerOptlang -lang fblite]]// and //[[CompilerOptlang -lang fb]]// dialects. {{fbdoc item="diff"}} - The numeric argument was not supported in QB. - QB converted the parameter list to uppercase before returning it, FreeBASIC doesn't. - By default arguments containing wildcard characters are expanded (filename globbing) {{fbdoc item="see"}} - ##[[KeyPgExec Exec]]## - ##[[KeyPgRun Run]]## {{fbdoc item="back" value="CatPgOpsys|Operating System Functions"}}{{fbdoc item="title" value="COMMON"}}---- Variable declaration and scope modifier {{fbdoc item="syntax"}}## **Common** [[[KeyPgShared Shared]]] //symbolname//[()] [AS [[DataType DataType]]] [, ...] ## {{fbdoc item="desc"}} Declares a variable which is shared between code modules. A matching ##**Common**## statement must appear in all other code modules using the variable. The ##**Shared**## optional parameter makes the variable global so that it can be used inside sub's and functions, as well as at module level. ##**Common**## arrays are always variable-length, and must be defined with an empty parameter list (), and its dimensions set in a later ##[[KeyPgDim Dim]]## or ##[[KeyPgRedim Redim]]## statement. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/module/common1.bas"}}%%(freebasic) '' common1.bas Declare Sub initme() Common Shared foo() As Double Redim foo(0 To 2) As Double initme() Print foo(0), foo(1), foo(2) %% {{fbdoc item="filename" value="examples/manual/module/common2.bas"}}%%(freebasic) '' common2.bas Common Shared foo() As Double Sub initme() foo(0) = 4*Atn(1) foo(1) = foo(0)/3 foo(2) = foo(1)*2 End Sub %% Output: %% 3.141592653589793 1.047197551196598 2.094395102393195 %% {{fbdoc item="diff"}} - The arrays will be always variable-length. - ##/blockname/## is not needed and must be removed because the order of declaration no longer matters, only the symbol names. {{fbdoc item="see"}} - ##[[KeyPgDim Dim]]## - ##[[KeyPgErase Erase]]## - ##[[KeyPgExtern Extern]]## - ##[[KeyPgLbound Lbound]]## - ##[[KeyPgRedim Redim]]## - ##[[KeyPgPreserve Preserve]]## - ##[[KeyPgShared Shared]]## - ##[[KeyPgStatic Static]]## - ##[[KeyPgUbound Ubound]]## - ##[[KeyPgVar Var]]## {{fbdoc item="back" value="CatPgModularizing|Modularizing"}}{{fbdoc item="title" value="CONDBROADCAST"}}---- Restarts all threads ##[[KeyPgCondWait Condwait]]##ing for the handle {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Condbroadcast** ( [[KeyPgByval byval]] //handle// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]]) ## {{fbdoc item="usage"}}## **Condbroadcast** ( //handle// ) ## {{fbdoc item="param"}} ##//handle//## The handle of a conditional variable, or the null pointer (0) on failure. {{fbdoc item="desc"}} Once the conditional is ##[[KeyPgCondCreate Condcreate]]## and the threads are started, one of more of them can be set to ##[[KeyPgCondWait Condwait]]## for the conditional, they will be stopped until some other thread ##[[KeyPgCondSignal Condsignal]]##s that the waiting thread can restart. ##[[KeyPgCondBroadcast Condbroadcast]]## can be used to restart all threads waiting for the conditional. At the end of the program ##[[KeyPgCondDestroy Conddestroy]]## must be used to avoid leaking resources in the OS. {{fbdoc item="ex"}} See ##[[KeyPgCondCreate Condcreate]]## {{fbdoc item="target"}} - **Condbroadcast** is not available with the DOS version / target of FreeBASIC, because multithreading is not supported by DOS kernel nor the used extender. - In Linux the threads are always started in the order they are created, this can't be assumed in Win32. It's an OS, not a FreeBASIC issue. {{fbdoc item="lang"}} - Threading is not allowed in //[[CompilerOptlang -lang qb]]// {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgCondCreate Condcreate]]## - ##[[KeyPgCondDestroy Conddestroy]]## - ##[[KeyPgCondSignal Condsignal]]## - ##[[KeyPgCondWait Condwait]]## - ##[[KeyPgThreadCreate Threadcreate]]## {{fbdoc item="back" value="CatPgThreading|Threading Support Functions"}}{{fbdoc item="title" value="CONDCREATE"}}---- Creates a conditional variable to be used in synchronizing threads {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Condcreate** ( ) [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] ## {{fbdoc item="usage"}}## //result// = **Condcreate** ## {{fbdoc item="ret"}} A handle to a newly created conditional variable, or the null pointer (0) on failure. {{fbdoc item="desc"}} Once the conditional is ##**KeyPgCondCreate Condcreate**##d and the threads are started, one or more of them can be set to ##[[KeyPgCondWait Condwait]]## for the conditional, they will be stopped until some other thread ##[[KeyPgCondSignal Condsignal]]##s that the waiting thread can restart. ##[[KeyPgCondBroadcast Condbroadcast]]## can be used to restart all threads waiting for the conditional. At the end of the program ##[[KeyPgCondDestroy Conddestroy]]## must be used to avoid leaking resources in the OS. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/threads/condcreate.bas"}}%%(freebasic) '' '' make newly-created threads wait until all threads are ready, then start them all at once '' dim shared hcondstart as any ptr dim shared hmutexstart as any ptr dim shared start as integer = 0 dim shared threadcount as integer dim shared hmutexready as any ptr dim shared hcondready as any ptr sub mythread(byval id_ptr as any ptr) dim id as integer = cast(integer, id_ptr) print "Thread #" & id & " is waiting..." '' signal that this thread is ready mutexlock hmutexready threadcount += 1 condsignal hcondready mutexunlock hmutexready '' wait for the start signal Mutexlock hmutexstart do while start = 0 Condwait hcondstart, hmutexstart loop '' now this thread holds the lock on hmutexstart Mutexunlock hmutexstart '' print out the number of this thread for i as integer = 1 to 40 print id; next i end sub dim threads(1 to 9) as any ptr hcondstart = condcreate() hmutexstart = mutexcreate() hcondready = condcreate() hmutexready = mutexcreate() threadcount = 0 for i as integer = 1 to 9 threads(i) = ThreadCreate(@mythread, cast(any ptr, i)) if threads(i) = 0 then print "unable to create thread" end if next i print "Waiting until all threads are ready..." mutexlock(hmutexready) do until threadcount = 9 condwait(hcondready, hmutexready) loop mutexunlock(hmutexready) print "Go!" mutexlock hmutexstart start = 1 condbroadcast hcondstart mutexunlock hmutexstart '' wait for all threads to complete for i as integer = 1 to 9 if threads(i) <> 0 then threadwait threads(i) end if next i mutexdestroy hmutexready conddestroy hcondready mutexdestroy hmutexstart conddestroy hcondstart %% {{fbdoc item="target"}} - **Condcreate** is not available with the DOS version / target of FreeBASIC, because multithreading is not supported by DOS kernel nor the used extender. {{fbdoc item="lang"}} - Threading is not allowed in //[[CompilerOptlang -lang qb]]// {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgCondBroadcast Condbroadcast]]## - ##[[KeyPgCondDestroy Conddestroy]]## - ##[[KeyPgCondSignal Condsignal]]## - ##[[KeyPgCondWait Condwait]]## - ##[[KeyPgMutexCreate Mutexcreate]]## - ##[[KeyPgMutexLock Mutexlock]]## - ##[[KeyPgMutexUnlock Mutexunlock]]## - ##[[KeyPgThreadCreate Threadcreate]]## {{fbdoc item="back" value="CatPgThreading|Threading Support Functions"}}{{fbdoc item="title" value="CONDDESTROY"}}---- Destroys a multi-threading conditional variable when it is no more needed {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Conddestroy** ( [[KeyPgByval byval]] //handle// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] ) ## {{fbdoc item="usage"}}## **Conddestroy** ( //handle// ) ## {{fbdoc item="param"}} ##//handle//## The handle of a conditional variable to destroy. {{fbdoc item="desc"}} Once the conditional is ##[[KeyPgCondCreate Condcreate]]##d and the threads are started, one of more of them can be set to ##[[KeyPgCondWait Condwait]]## for the conditional, they will be stopped until some other thread ##[[KeyPgCondSignal Condsignal]]##s that the waiting thread can restart. ##[[KeyPgCondBroadcast Condbroadcast]]## can be used to restart all threads waiting for the conditional. At the end of the program ##[[KeyPgCondDestroy Conddestroy]]## must be used to avoid leaking resources in the OS. {{fbdoc item="ex"}} See ##[[KeyPgCondCreate Condcreate]]## {{fbdoc item="target"}} - **Conddestroy** is not available with the DOS version / target of FreeBASIC, because multithreading is not supported by DOS kernel nor the used extender. {{fbdoc item="lang"}} - Threading is not allowed in //[[CompilerOptlang -lang qb]]// {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgCondCreate Condcreate]]## - ##[[KeyPgCondBroadcast Condbroadcast]]## - ##[[KeyPgCondSignal Condsignal]]## - ##[[KeyPgCondWait Condwait]]## - ##[[KeyPgThreadCreate Threadcreate]]## {{fbdoc item="back" value="CatPgThreading|Threading Support Functions"}}{{fbdoc item="title" value="CONDSIGNAL"}}---- Restarts a thread suspended by a call to ##[[KeyPgCondWait Condwait]]## {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Condsignal** ( [[KeyPgByval byval]] //handle// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]]) ## {{fbdoc item="usage"}}## **Condsignal** ( //handle// ) ## {{fbdoc item="param"}} ##//handle//## The handle of a conditional variable, or the null pointer (0) on failure. {{fbdoc item="desc"}} Once the conditional is created with ##[[KeyPgCondCreate Condcreate]]## and the threads are started, one of more of them can be set to ##[[KeyPgCondWait Condwait]]## for the conditional, they will be stopped until some other thread ##[[KeyPgCondSignal Condsignal]]##s that the waiting thread can restart. ##[[KeyPgCondBroadcast Condbroadcast]]## can be used to restart all threads waiting for the conditional. At the end of the program ##[[KeyPgCondDestroy Conddestroy]]## must be used to avoid leaking resources in the OS. {{fbdoc item="ex"}} See ##[[KeyPgCondCreate Condcreate]]## {{fbdoc item="lang"}} - Threading is not allowed in //[[CompilerOptlang -lang qb]]// {{fbdoc item="target"}} - **Condsignal** is not available with the DOS version / target of FreeBASIC, because multithreading is not supported by DOS kernel nor the used extender. - In Linux the threads are always started in the order they are created, this can't be assumed in Win32. It's an OS, not a FreeBASIC issue. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgCondCreate Condcreate]]## - ##[[KeyPgCondDestroy Conddestroy]]## - ##[[KeyPgCondBroadcast Condbroadcast]]## - ##[[KeyPgCondWait Condwait]]## - ##[[KeyPgThreadCreate Threadcreate]]## {{fbdoc item="back" value="CatPgThreading|Threading Support Functions"}}{{fbdoc item="title" value="CONDWAIT"}}---- Stops execution of current thread until some condition becomes true {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Condwait** ( [[KeyPgByval byval]] //handle// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]], [[KeyPgByval byval]] //mutex// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] ) ## {{fbdoc item="usage"}}## **Condwait** ( //handle//, //mutex// ) ## {{fbdoc item="param"}} ##//handle//## The handle of a conditional variable, or the null pointer (0) on failure. ##//mutex//## The mutex associated with this conditional variable, which must be locked when testing the condition and calling ##**Condwait**## {{fbdoc item="desc"}} Function that stops the thread where it is called until some other thread ##[[KeyPgCondSignal Condsignal]]##s or ##[[KeyPgCondBroadcast Condbroadcast]]##s the handle. Once the conditional variable is created with ##[[KeyPgCondCreate Condcreate]]## and the threads are started, one of more of them can be set to ##**Condwait**## for the conditional; they will be stopped until some other thread ##[[KeyPgCondSignal Condsignal]]##s that the waiting thread can restart. ##[[KeyPgCondBroadcast Condbroadcast]]## can be used to restart all threads waiting for the conditional. At the end of the program ##[[KeyPgCondDestroy Conddestroy]]## must be used to avoid leaking resources in the OS. When calling ##**Condwait**##, ##//mutex//## should already be locked. An atomic unlock of the mutex and wait on the conditional variable will occur. When the condition variable becomes signaled, ##//mutex//## will be locked again and then execution will return to the thread after the ##**Condwait**## call. {{fbdoc item="ex"}} See ##[[KeyPgCondCreate Condcreate]]## {{fbdoc item="target"}} - **Condwait** is not available with the DOS version / target of FreeBASIC, because multithreading is not supported by DOS kernel nor the used extender. - In Linux the threads are always started in the order they are created, this can't be assumed in Win32. It's an OS, not a FreeBASIC issue. {{fbdoc item="lang"}} - Threading is not allowed in //[[CompilerOptlang -lang qb]]// {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgCondCreate Condcreate]]## - ##[[KeyPgCondDestroy Conddestroy]]## - ##[[KeyPgCondBroadcast Condbroadcast]]## - ##[[KeyPgCondSignal Condsignal]]## - ##[[KeyPgMutexCreate Mutexcreate]]## - ##[[KeyPgMutexLock Mutexlock]]## - ##[[KeyPgMutexUnlock Mutexunlock]]## - ##[[KeyPgThreadCreate Threadcreate]]## {{fbdoc item="back" value="CatPgThreading|Threading Support Functions"}}{{fbdoc item="title" value="CONST"}}---- Non-modifiable variable declaration. {{fbdoc item="syntax"}}## **Const** //symbolname// [AS [[DataType DataType]]] = //value// [, ...] ## {{fbdoc item="desc"}} Declares non-modifiable constant data that can be integer or decimal (floating-point) numbers or strings. The constant type will be inferred if //DataType// isn't explicitly given. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/variable/const.bas"}}%%(freebasic) const Red = RGB(252, 2, 4) const Black as uinteger = RGB(0, 0, 0) const Text = "This is red text on a black bkgnd." locate 1, 1 color Red, Black print Text sleep end %% {{fbdoc item="diff"}} - QB does not support the ##[[KeyPgAs as]]## ##[[DataType datatype]]## syntax. {{fbdoc item="see"}} - ##[[KeyPgPpdefine #Define]]## - ##[[KeyPgConstQualifier Const (Qualifier)]]## - ##[[KeyPgConstMember Const (Member)]]## - ##[[KeyPgEnum Enum]]## - ##[[KeyPgVar Var]]## {{fbdoc item="back" value="CatPgVariables|Variable Declarations"}}{{fbdoc item="title" value="CONST (Member)"}}---- Specifies that a member procedure is read only. {{fbdoc item="syntax"}}## [[KeyPgType Type]] //typename// [[KeyPgDeclare declare]] **Const** //membertype// //membername// ... End Type ## {{fbdoc item="param"}} ##//typename//## Name of a user defined data type. ##//membertype//## ##[[KeyPgMemberSub Sub]]## or ##[[KeyPgMemberFunction Function]]##. ##//membername// ...## Name of the member to declare or define with parameter list or return value following. {{fbdoc item="desc"}} Specifies that the ##//membertype//## immediately to the right of the ##**Const**## qualifier is to be considered as read only. Read-only (##**Const**##) declarations are a measure of type safety that can be read as 'promises not to change.' The compiler uses the const declarations to check operations on variables and parameters and generate an error at compile time if their data could potentially change. There is no runtime overhead for using ##**Const**## qualifiers since all of the checks are made at compile time. ##**Const**##, when used preceding ##//membertype//## at the beginning of a declaration indicates that the hidden ##[[KeyPgThis This]]## parameter is considered read-only. The declaration can be read as 'invoking ##//membertype//## promises not to change ##//typename//##', and the compiler will error if the member procedure tries to change any of the data fields, or calls a non-const member procedure. Member procedures can not be both ##**Const**## and ##[[KeyPgStaticMember Static]]## since static member procedures do not have a hidden ##[[KeyPgThis This]]## parameter. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/udt/const-proc.bas"}}%%(freebasic) '' Const Member Procedures type foo x as integer c as const integer = 0 declare const sub Inspect1() declare const sub Inspect2() declare sub Mutate1() declare sub Mutate2() end type '' sub foo.Mutate1() '' we can change non-const data fields x = 1 '' but we still can't change const data '' fields, they are promised not to change '' c = 1 '' Compile error end sub '' sub foo.Mutate2() '' we can call const members Inspect1() '' and non-const members Mutate1() end sub '' sub foo.Inspect1() '' can use data members dim y as integer y = c + x '' but not change them because Inspect1() '' is const and promises not to change foo '' x = 10 '' Compile error end sub '' sub foo.Inspect2() '' we can call const members Inspect1() '' but not non-const members '' Mutate1() '' Compile error end sub %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgConst Const]]## - ##[[KeyPgConstQualifier Const (Qualifier)]]## - ##[[KeyPgDim Dim]]## - ##[[KeyPgType Type]]## {{fbdoc item="back" value="CatPgProcedures|Procedures"}}{{fbdoc item="back" value="CatPgUserDefTypes|User Defined Types"}}{{fbdoc item="title" value="CONST (Qualifier)"}}---- Specifies that a data type or pointer data type is read only. {{fbdoc item="syntax"}}## ... [[KeyPgAs as]] [**Const**] //[[DataType datatype]]// [ [**Const**] [[KeyPgPtr ptr]] ... ] ## {{fbdoc item="param"}} ##//datatype//## Name of a standard or user defined data type. {{fbdoc item="desc"}} Specifies that the ##//datatype//## or ##[[KeyPgPtr ptr]]## immediately to the right of the ##**Const**## qualifier is to be considered as read only. Read-only (##**Const**##) declarations are a measure of type safety that can be read as 'promises not to change.' The compiler uses the const declarations to check operations on variables and parameters and generate an error at compile time if their data could potentially change. There is no runtime overhead for using ##**Const**## qualifiers since all of the checks are made at compile time. ##**Const**## can be used anywhere data type declarations are made. This includes variables, parameters, function return results, user defined type fields, type aliases, and casting. The ##//datatype//## can be any built-in standard data type or user defined type. Read-only variables must have an initializer since modifying a read-only variable through an assignment will generate a compiler error. The initializer may appear after the declaration of the variable. Both non-const and const variables may be passed to a procedure expecting a const parameter. However, a const variable may not be passed to a procedure taking a non-const parameter, and will generate a compile error. Procedures can be overloaded based on the const-ness of parameters. For example a procedure can be overloaded where one version of the procedure takes a ##'byref foo as bar'## parameter and another version of the procedure takes a ##'byref foo as const bar'## parameter. With pointer declarations, ##**Const**## can be used to indicate which part of the pointer declaration is read-only (all other parts are by default read-write). The read-only portion of the pointer data type could be the pointer itself (the address), what the pointer points to (the data), or both. In a declaration with more than one level of ##[[KeyPgPtr Ptr]]## indirection, the right most ##[[KeyPgPtr Ptr]]## indicates the highest order level of indirection and is therefore dereferenced first. The compiler has an internal hard-limit of eight (8) levels of pointer indirection with respect to const qualifiers and the behavior of using ##**Const**## with ##[[KeyPgPtr Ptr]]## data types having greater than eight (8) levels of indirection is undefined. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/datatype/const-var.bas"}}%%(freebasic) '' Const Variables '' procedure taking a const parameter sub proc1( byref x as const integer ) '' can't change x because it is const '' x = 10 '' compile error '' but we can use it in expressions and '' assign it to other variables dim y as integer y = x y = y * x + x end sub '' procedure taking a non-const parameter sub proc2( byref x as integer ) '' we can change the value x = 10 end sub '' declare a non-const and const variable dim a as integer dim b as const integer = 5 '' proc1() will accept a non-const or const '' argument because proc1() promises not to '' change the variable passed to it. proc1( a ) proc1( b ) '' proc2() will accept a non-const argument proc2( a ) '' but not a const argument because proc2() '' might change the variable's data and we '' promised that 'b' would not change. '' proc2( b ) '' compile error %% {{fbdoc item="filename" value="examples/manual/datatype/const-ptr.bas"}}%%(freebasic) '' Const Pointers '' an integer dim x as integer = 1 dim y as integer = 2 dim z as integer = 3 '' To check that the compiler generates errors '' when attempting to reassign const variables, '' uncomment the assignments below. '' scope '' a pointer to an integer dim p as integer ptr = @x p = @y /' OK - pointer can be changed '/ *p = z /' OK - data can be changed '/ end scope '' scope '' a pointer to a constant integer dim p as const integer ptr = @x p = @y /' OK - pointer can be changed '/ '' *p = z /' Error - data is const '/ end scope '' scope '' a constant pointer to an integer dim p as integer const ptr = @x '' p = @y /' Error - pointer is const '/ *p = z /' OK - data can be changed '/ end scope '' scope '' a constant pointer to a constant integer dim p as const integer const ptr = @x '' p = @y /' Error - pointer is const '/ '' *p = z /' Error - data is const '/ end scope %% {{fbdoc item="filename" value="examples/manual/datatype/const-ovl.bas"}}%%(freebasic) '' Const Parameters in an Overloaded Procedure '' procedure with non-const parameter sub foo overload( byref n as integer ) print "called 'foo( byref n as integer )'" end sub '' procedure with const parameter sub foo overload( byref n as const integer ) print "called 'foo( byref n as const integer )'" end sub dim x as integer = 1 dim y as const integer = 2 foo( x ) foo( y ) '' OUTPUT: '' called 'foo( byref n as integer )' '' called 'foo( byref n as const integer )' %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgConst Const]]## - ##[[KeyPgConstMember Const (Member)]]## - ##[[KeyPgDim Dim]]## - ##[[KeyPgType Type]]## {{fbdoc item="back" value="CatPgStdDataTypes|Standard Data Types"}}{{fbdoc item="title" value="CONSTRUCTOR"}}---- Called automatically when a class or user defined type is created {{fbdoc item="syntax"}}## [[KeyPgType Type]] //typename// [[KeyPgDeclare declare]] **Constructor** ( ) [[KeyPgDeclare declare]] **Constructor** ( [ [[KeyPgByref byref]] | [[KeyPgByval byval]] ] //parameter// [[KeyPgAs as]] [[DataType datatype]] [ = //default// ] [, ... ] ) End Type **Constructor** //typename// ( [ //parameters// ] ) //statements// **End Constructor** ## {{fbdoc item="param"}} ##//typename//## name of the ##[[KeyPgType Type]]## of ##[[KeyPgClass Class]]## {{fbdoc item="desc"}} ##**Constructor**## methods are called when a user defined ##[[KeyPgType Type]]## or ##[[KeyPgClass Class]]## variable is created. ##//typename//## is the name of the type for which the ##**Constructor**## method is declared and defined. Name resolution for ##//typename//## follows the same rules as procedures when used in a ##[[KeyPgNamespace Namespace]]##. More than one constructor may exist for a type or class. The exact constructor method called depends on the ##//parameter//## signature matched when the variable is initialized. More than one ##//parameter//## may exist in a constructor method declaration. A constructor method is passed a hidden ##[[KeyPgThis this]]## parameter having the same type as ##//typename//##. ##[[KeyPgThis this]]## is optionally used to access the fields of the ##[[KeyPgType Type]]## or ##[[KeyPgClass Class]]## which is to be initialized in the ##**Constructor**## method. Chaining of constructors in nested types is supported. Any fields that have their own default constructor are called first. Constructors are called when declaring global or local static instances of ##//typename//## and when allocating ##//typename//## dynamically using the ##[[KeyPgOpNew New]]## operator. {{fbdoc item="ex"}} Simple constructor example for beginners. {{fbdoc item="filename" value="examples/manual/udt/constructor-ptr.bas"}}%%(freebasic) Type MyObj Foo As Integer Ptr '' Constructor to create our integer, and set its value. Declare Constructor( ByVal DefVal As Integer = 0 ) '' Destroy our integer on object deletion. Declare Destructor() End Type Constructor MyObj( ByVal DefVal As Integer = 0 ) Print "Creating a new integer in MyObj!" Print "The Integer will have the value of: " & DefVal Print "" '' Create a pointer, and set its value to the one passed to the '' Constructor. This.Foo = New Integer *This.Foo = DefVal End Constructor Destructor MyObj() Print "Deleting our Integer in MyObj!" Print "" '' Delete the pointer we created in MyObj. Delete This.Foo This.Foo = 0 End Destructor Scope '' Create a MyObj type object '' Send the value of '10' to the constructor Dim As MyObj Bar = 10 '' See if the integer's been created. Print its value. Print "The Value of our integer is: " & *Bar.Foo Print "" Sleep End Scope '' We've just gone out of a scope. The Destructor should be called now '' Because our objects are being deleted. Sleep %% More advanced construction example, showing constructor overloading among other things. {{fbdoc item="filename" value="examples/manual/udt/constructor.bas"}}%%(freebasic) type sample _text as string declare constructor () declare constructor ( a as integer ) declare constructor ( a as single ) declare constructor ( a as string, b as byte ) declare operator cast () as string end type constructor sample () print "constructor sample ()" print this._text = "Empty" end constructor constructor sample ( a as integer ) print "constructor sample ( a as integer )" print " a = "; a print this._text = str(a) end constructor constructor sample ( a as single ) print "constructor sample ( a as single )" print " a = "; a print this._text = str(a) end constructor constructor sample ( a as string, b as byte ) print "constructor sample ( a as string, b as byte )" print " a = "; a print " b = "; b print this._text = str(a) + "," + str(b) end constructor operator sample.cast () as string return this._text end operator print "Creating x1" dim x1 as sample print "Creating x2" dim x2 as sample = 1 print "Creating x3" dim x3 as sample = 99.9 print "Creating x4" dim x4 as sample = sample( "aaa", 1 ) print "Values:" print " x1 = "; x1 print " x2 = "; x2 print " x3 = "; x3 print " x4 = "; x4 %% {{fbdoc item="lang"}} - Object-related features are supported only in the //[[CompilerOptlang -lang fb]]// option {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgType Class]]## - ##[[KeyPgModuleConstructor Constructor (Module)]]## - ##[[KeyPgOpNew New]]## - ##[[KeyPgDestructor Destructor]]## - ##[[KeyPgType Type]]## {{fbdoc item="back" value="CatPgUserDefTypes|User Defined Types"}}{{fbdoc item="title" value="CONTINUE"}}---- Control flow statement to continue next iteration of a loop {{fbdoc item="syntax"}}## **Continue** {[[KeyPgDoloop do]] | [[KeyPgFornext for]] | [[KeyPgWhilewend while]]} ## {{fbdoc item="desc"}} Skips all code until the end clause of a loop structure, i.e. ##[[KeyPgDoloop Do...Loop]]##, ##[[KeyPgFornext For...Next]]##, or a ##[[KeyPgWhilewend While...Wend]]## block, then executes the limit condition check. In the case of a ##[[KeyPgFornext For...Next]]##, the variable is incremented according to the ##[[KeyPgStep Step]]## specified. Where there are multiple ##[[KeyPgDoloop Do]]## / ##[[KeyPgFornext For]]## / ##[[KeyPgWhilewend While]]## blocks nested, it will continue on the innermost block of that type, i.e. the last one entered. You can continue an earlier block of that type by giving the word multiple times, separated by commas. e.g. ##**continue while, while**## {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/control/continue.bas"}}%%(freebasic) Dim As Integer n Print "Here are odd numbers between 0 and 10!" Print For n = 0 To 10 If ( n Mod 2 ) = 0 Then Continue For End If Print n Next n %% {{fbdoc item="filename" value="examples/manual/control/continue2.bas"}}%%(freebasic) '' simple prime number finder Print "Here are the prime numbers between 1 and 20!" Print Dim n As Integer, d As Integer For n = 2 To 20 For d = 2 To Int(Sqr(n)) If ( n Mod d ) = 0 Then ' d divides n Continue For, For ' n is not prime, so try next n End If Next d Print n Next n %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Continue""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgExit Exit]]## {{fbdoc item="back" value="CatPgControlFlow|Control Flow"}}{{fbdoc item="title" value="COS"}}---- Returns the cosine of a number {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Cos** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgDouble double]] ) [[KeyPgAs as]] [[KeyPgDouble double]] ## {{fbdoc item="usage"}}## //result// = **Cos** ( //number// ) ## {{fbdoc item="param"}} ##//number//## the angle (in radians) {{fbdoc item="ret"}} Returns the cosine of the argument ##//number//## as a ##[[KeyPgDouble Double]]## within the range of -1 to 1. {{fbdoc item="desc"}} The argument ##//number//## is measured in [[TutMathAngles radians]] (not [[TutMathAngles degrees]]). The required ##//number//## argument can be any valid numeric expression. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/math/cos.bas"}}%%(freebasic) CONST PI AS DOUBLE = 3.1415926535897932 DIM a AS DOUBLE DIM r AS DOUBLE INPUT "Please enter an angle in degrees: ", a r = a * PI / 180 'Convert the degrees to Radians PRINT "" PRINT "The cosine of a" ; a; " degree angle is"; COS ( r ) SLEEP %% Output: %% Please enter an angle in degrees: 30 The cosine of a 30 degree angle Is 0.8660254037844387 %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgAcos Acos]]## - [[TutMathIntroTrig A Brief Introduction To Trigonometry]] {{fbdoc item="back" value="CatPgMath|Math"}}{{fbdoc item="title" value="CPTR"}}---- Converts a pointer expression to a specified data type pointer {{fbdoc item="syntax"}}## **Cptr**( [[DataType DataType]] [[KeyPgPtr ptr]], //expression// ) ## {{fbdoc item="desc"}} Converts ##//expression//## to a pointer to a [[DataType DataType]]. ##//expression//## may be a another pointer type or an ##[[KeyPgInteger Integer]]##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/casting/cptr.bas"}}%%(freebasic) dim intval as integer dim intptr as integer ptr intval = &h0080 intptr = @intval '' will print -128 and 128, as the first expression will be "seen" as an signed byte print *cptr( byte ptr, intptr ), *intptr %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Cptr""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgCast Cast]]## - ##[[KeyPgCbyte Cbyte]]## - ##[[KeyPgCshort Cshort]]## - ##[[KeyPgCint Cint]]## - ##[[KeyPgClngint Clngint]]## - ##[[KeyPgCsng Csng]]## - ##[[KeyPgCdbl Cdbl]]## {{fbdoc item="back" value="CatPgCasting|Converting Data Types"}}{{fbdoc item="title" value="CSHORT"}}---- Converts numeric or string expression to an integer (##[[KeyPgShort Short]]##) {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Cshort** ( [[KeyPgByval byval]] //expression// [[KeyPgAs as]] [[DataType datatype]] ) [[KeyPgAs as]] [[KeyPgShort short]] [[KeyPgType Type]] //typename// [[KeyPgDeclare declare]] [[KeyPgOperator operator]] [[KeyPgCast cast]] ( ) [[KeyPgAs as]] [[KeyPgShort short]] End Type ## {{fbdoc item="usage"}}## //result// = **Cshort**( //numeric expression// ) //result// = **Cshort**( //string expression// ) //result// = **Cshort**( //user defined type// ) ## {{fbdoc item="param"}} ##//expression//## a numeric, string, or pointer expression to cast to a ##[[KeyPgShort Short]]## value ##//datatype//## any numeric, string, or pointer data type ##//typename//## a user defined type {{fbdoc item="ret"}} A ##[[KeyPgShort Short]]## value. {{fbdoc item="desc"}} The ##**Cshort**## function rounds off the decimal part and returns a 16 bit ##[[KeyPgShort Short]]## value. The function does not check for an overflow, so be sure not to pas a value thats less/larger then -32768 to 32767. The name can be explained as 'Convert to Short'. If the argument is a string expression, it is converted to numeric by using ##[[KeyPgValint Valint]]##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/casting/cshort.bas"}}%%(freebasic) ' Using the CSHORT function to convert a numeric value 'Create an SHORT variable DIM numeric_value AS SHORT 'Convert a numeric value numeric_value = CSHORT(-4500.66) 'Print the result, should return -4501 PRINT numeric_value SLEEP %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Cshort""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgCbyte Cbyte]]## - ##[[KeyPgCubyte Cubyte]]## - ##[[KeyPgCushort Cushort]]## - ##[[KeyPgCint Cint]]## - ##[[KeyPgCuint Cuint]]## - ##[[KeyPgClng Clng]]## - ##[[KeyPgCulng Culng]]## - ##[[KeyPgClngint Clngint]]## - ##[[KeyPgCulngint Culngint]]## - ##[[KeyPgCsng Csng]]## - ##[[KeyPgCdbl Cdbl]]## {{fbdoc item="back" value="CatPgCasting|Converting Data Types"}}{{fbdoc item="title" value="CSIGN"}}---- Converts an expression to signed {{fbdoc item="syntax"}}## **Csign** ( //expression// ) ## {{fbdoc item="usage"}}## //variable// = **Csign** ( //expression// ) ## {{fbdoc item="desc"}} Converts an unsigned ##//expression//## to a signed one, useful to force signed behavior of division or multiplication (including with ##[[KeyPgOpShiftLeft Shl]]## and ##[[KeyPgOpShiftRight Shr]]##). This is the opposite of ##[[KeyPgCunsg Cunsg]]##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/casting/csign.bas"}}%%(freebasic) dim value as ushort = 65535 print csign(value) '' will print -1 %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Csign""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgCunsg Cunsg]]## {{fbdoc item="back" value="CatPgCasting|Converting Data Types"}}{{fbdoc item="title" value="CSNG"}}---- Converts numeric or string expression to ##[[KeyPgSingle Single]]## precision floating point {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Csng** ( [[KeyPgByval byval]] //expression// [[KeyPgAs as]] [[DataType datatype]] ) [[KeyPgAs as]] [[KeyPgSingle single]] [[KeyPgType Type]] //typename// [[KeyPgDeclare declare]] [[KeyPgOperator operator]] [[KeyPgCast cast]] ( ) [[KeyPgAs as]] [[KeyPgSingle single]] End Type ## {{fbdoc item="usage"}}## //result// = **Csng**( //numeric expression// ) //result// = **Csng**( //string expression// ) //result// = **Csng**( //user defined type// ) ## {{fbdoc item="param"}} ##//expression//## a numeric, string, or pointer expression to cast to a ##[[KeyPgSingle Single]]## value ##//datatype//## any numeric, string, or pointer data type ##//typename//## a user defined type {{fbdoc item="ret"}} A ##[[KeyPgSingle Single]]## precision value. {{fbdoc item="desc"}} The ##**Csng**## function returns a 32-bit ##[[KeyPgSingle Single]]## value. The function does not check for an overflow, so be sure not to pass a value outside the representable range of the ##[[KeyPgSingle Single]]## data type. The name can be explained as 'Convert to ""SiNGle""'. If the argument to ##**Csng**## is a string expression, it is first converted to numeric by using ##[[KeyPgVal Val]]##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/casting/csng.bas"}}%%(freebasic) ' Using the CSNG function to convert a numeric value 'Create an SINGLE variable DIM numeric_value AS SINGLE 'Convert a numeric value numeric_value = CSNG(-12345.123) 'Print the result, should return -12345.123 PRINT numeric_value SLEEP %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgCbyte Cbyte]]## - ##[[KeyPgCubyte Cubyte]]## - ##[[KeyPgCshort Cshort]]## - ##[[KeyPgCushort Cushort]]## - ##[[KeyPgCint Cint]]## - ##[[KeyPgCuint Cuint]]## - ##[[KeyPgClng Clng]]## - ##[[KeyPgCulng Culng]]## - ##[[KeyPgClngint Clngint]]## - ##[[KeyPgCulngint Culngint]]## - ##[[KeyPgCdbl Cdbl]]## {{fbdoc item="back" value="CatPgCasting|Converting Data Types"}}{{fbdoc item="title" value="CSRLIN"}}---- Returns the row position of the cursor {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Csrlin** ( ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **Csrlin** ## {{fbdoc item="ret"}} An [[KeyPgInteger integer]] specifying the current row of the cursor. {{fbdoc item="desc"}} Returns the current line position (row) of the cursor (##//csr//## for cursor, ##//lin//## for line). {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/console/csrlin.bas"}}%%(freebasic) print "The cursor is on row:"; CSRLIN %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgLocate Locate]]## - ##[[KeyPgPos Pos]]## {{fbdoc item="back" value="CatPgConsole|Console Functions"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:50:03 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: ee69a8352964b30f03d7a089b76ba74a Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 2298 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="CUBYTE"}}---- Converts numeric or string expression to an unsigned byte (##[[KeyPgUbyte Ubyte]]##) {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Cubyte** ( [[KeyPgByval byval]] //expression// [[KeyPgAs as]] [[DataType datatype]] ) [[KeyPgAs as]] [[KeyPgUbyte ubyte]] [[KeyPgType Type]] //typename// [[KeyPgDeclare declare]] [[KeyPgOperator operator]] [[KeyPgCast cast]] ( ) [[KeyPgAs as]] [[KeyPgUbyte ubyte]] End Type ## {{fbdoc item="usage"}}## //result// = **Cubyte**( //numeric expression// ) //result// = **Cubyte**( //string expression// ) //result// = **Cubyte**( //user defined type// ) ## {{fbdoc item="param"}} ##//expression//## a numeric, string, or pointer expression to cast to a ##[[KeyPgUbyte Ubyte]]## value ##//datatype//## any numeric, string, or pointer data type ##//typename//## a user defined type {{fbdoc item="ret"}} A ##[[KeyPgUbyte Ubyte]]## value. {{fbdoc item="desc"}} The ##**Cubyte**## function rounds off the decimal part and returns a 8 bit ##[[KeyPgUbyte Ubyte]]## value. The function does not check for an overflow, so be sure not to pass a value thats less/larger then 0 to 255. The name can be explained as 'Convert to Unsigned Byte'. If the argument is a string expression, it is converted to numeric by using ##[[KeyPgValuint Valuint]]##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/casting/cubyte.bas"}}%%(freebasic) ' Using the CUBYTE function to convert a numeric value 'Create an UNSIGNED BYTE variable DIM numeric_value AS UBYTE 'Convert a numeric value numeric_value = CUBYTE(123.55) 'Print the result, should return 124 PRINT numeric_value SLEEP %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Cubyte""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgCbyte Cbyte]]## - ##[[KeyPgCshort Cshort]]## - ##[[KeyPgCushort Cushort]]## - ##[[KeyPgCint Cint]]## - ##[[KeyPgCuint Cuint]]## - ##[[KeyPgClng Clng]]## - ##[[KeyPgCulng Culng]]## - ##[[KeyPgClngint Clngint]]## - ##[[KeyPgCulngint Culngint]]## - ##[[KeyPgCsng Csng]]## - ##[[KeyPgCdbl Cdbl]]## {{fbdoc item="back" value="CatPgCasting|Converting Data Types"}} {{fbdoc item="title" value="CUINT"}}---- Converts numeric or string expression to an unsigned integer (##[[KeyPgUinteger Uinteger]]##) {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Cuint** ( [[KeyPgByval byval]] //expression// [[KeyPgAs as]] [[DataType datatype]] ) [[KeyPgAs as]] [[KeyPgUinteger uinteger]] [[KeyPgType Type]] //typename// [[KeyPgDeclare declare]] [[KeyPgOperator operator]] [[KeyPgCast cast]] ( ) [[KeyPgAs as]] [[KeyPgUinteger uinteger]] End Type ## {{fbdoc item="usage"}}## //result// = **Cuint**( //numeric expression// ) //result// = **Cuint**( //string expression// ) //result// = **Cuint**( //user defined type// ) ## {{fbdoc item="param"}} ##//expression//## a numeric, string, or pointer expression to cast to a ##[[KeyPgUinteger Uinteger]]## value ##//datatype//## any numeric, string, or pointer data type ##//typename//## a user defined type {{fbdoc item="ret"}} A ##[[KeyPgUinteger Uinteger]]## value. {{fbdoc item="desc"}} The ##**Cuint**## function rounds off the decimal part and returns a 32 bit ##[[KeyPgUinteger Uinteger]]## value. The function does not check for an overflow, so be sure not to pas a value thats less/larger then 0 to 4 294 967 296. The name can be explained as 'Convert to Unsigned INTeger'. If the argument is a string expression, it is converted to numeric by using ##[[KeyPgValuint Valuint]]##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/casting/cuint.bas"}}%%(freebasic) ' Using the CUINT function to convert a numeric value 'Create an UNSIGNED INTEGER variable DIM numeric_value AS UINTEGER 'Convert a numeric value numeric_value = CUINT(300.23) 'Print the result = 300 PRINT numeric_value SLEEP %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Cuint""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgCbyte Cbyte]]## - ##[[KeyPgCubyte Cubyte]]## - ##[[KeyPgCshort Cshort]]## - ##[[KeyPgCushort Cushort]]## - ##[[KeyPgCint Cint]]## - ##[[KeyPgClng Clng]]## - ##[[KeyPgCulng Culng]]## - ##[[KeyPgClngint Clngint]]## - ##[[KeyPgCulngint Culngint]]## - ##[[KeyPgCsng Csng]]## - ##[[KeyPgCdbl Cdbl]]## {{fbdoc item="back" value="CatPgCasting|Converting Data Types"}}{{fbdoc item="title" value="CULNG"}}---- Converts numeric or string expression to ##[[KeyPgUlong Ulong]]## having the same size as ##[[KeyPgSizeof Sizeof]]([[KeyPgAny Any]] [[KeyPgPtr Ptr]])## {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Culng** ( [[KeyPgByval byval]] //expression// [[KeyPgAs as]] [[DataType datatype]] ) [[KeyPgAs as]] [[KeyPgUlong ulong]] [[KeyPgType Type]] //typename// [[KeyPgDeclare declare]] [[KeyPgOperator operator]] [[KeyPgCast cast]] ( ) [[KeyPgAs as]] [[KeyPgUlong ulong]] End Type ## {{fbdoc item="usage"}}## //result// = **Culng**( //numeric expression// ) //result// = **Culng**( //string expression// ) //result// = **Culng**( //user defined type// ) ## {{fbdoc item="param"}} ##//expression//## a numeric, string, or pointer expression to cast to a ##[[KeyPgUlong Ulong]]## value ##//datatype//## any numeric, string, or pointer data type ##//typename//## a user defined type {{fbdoc item="ret"}} A ##[[KeyPgUlong Ulong]]## value. {{fbdoc item="desc"}} The ##**Culng**## function rounds off the decimal part and returns a 32 bit ##[[KeyPgUinteger Uinteger]]## or 64 bit ##[[KeyPgUlongint Ulongint]]## value. The function does not check for an overflow. The name can be explained as 'Convert to Unsigned ""LoNG""'. If the argument is a string expression, it is converted to numeric by using ##[[KeyPgValuint Valuint]]## or ##[[KeyPgValulng Valulng]]##. ##[[KeyPgUlong Ulong]]## has the same size as ##[[KeyPgSizeof Sizeof]]([[KeyPgAny Any]] [[KeyPgPtr Ptr]])##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/casting/culng.bas"}}%%(freebasic) ' Using the CULNG function to convert a numeric value 'Create an UNSIGNED LONG variable DIM numeric_value AS ULONG 'Convert a numeric value numeric_value = CULNG(300.23) 'Print the result = 300 PRINT numeric_value SLEEP %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Culng""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgCbyte Cbyte]]## - ##[[KeyPgCubyte Cubyte]]## - ##[[KeyPgCshort Cshort]]## - ##[[KeyPgCushort Cushort]]## - ##[[KeyPgCint Cint]]## - ##[[KeyPgCuint Cuint]]## - ##[[KeyPgClng Clng]]## - ##[[KeyPgClngint Clngint]]## - ##[[KeyPgCulngint Culngint]]## - ##[[KeyPgCsng Csng]]## - ##[[KeyPgCdbl Cdbl]]## {{fbdoc item="back" value="CatPgCasting|Converting Data Types"}}{{fbdoc item="title" value="CULNGINT"}}---- Converts numeric or string expression to 64-bit unsigned integer (##[[KeyPgUlongint Ulongint]]##) {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Culngint** ( [[KeyPgByval byval]] //expression// [[KeyPgAs as]] [[DataType datatype]] ) [[KeyPgAs as]] [[KeyPgUlongint ulongint]] [[KeyPgType Type]] //typename// [[KeyPgDeclare declare]] [[KeyPgOperator operator]] [[KeyPgCast cast]] ( ) [[KeyPgAs as]] [[KeyPgUlongint ulongint]] End Type ## {{fbdoc item="usage"}}## //result// = **Culngint**( //numeric expression// ) //result// = **Culngint**( //string expression// ) //result// = **Culngint**( //user defined type// ) ## {{fbdoc item="param"}} ##//expression//## a numeric, string, or pointer expression to cast to a ##[[KeyPgUlongint Ulongint]]## value ##//datatype//## any numeric, string, or pointer data type ##//typename//## a user defined type {{fbdoc item="ret"}} A ##[[KeyPgUlongint Ulongint]]## value. {{fbdoc item="desc"}} The ##**Culngint**## function rounds off the decimal part and returns a 64 bit ##[[KeyPgUlongint Ulongint]]## value. The function does not check for an overflow, so be sure not to pas a value thats less/larger than 0 to 18 446 744 073 709 551 615. The name can be explained as 'Convert to Unsigned ""LoNG INTeger""'. If the argument is a string expression, it is converted to numeric by using ##[[KeyPgValulng Valulng]]##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/casting/culngint.bas"}}%%(freebasic) ' Using the CLNGINT function to convert a numeric value 'Create an UNSIGNED LONG INTEGER variable DIM numeric_value AS ULONGINT 'Convert a numeric value numeric_value = CULNGINT(12345678.123) 'Print the result, should return 12345678 PRINT numeric_value SLEEP %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Culngint""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgCbyte Cbyte]]## - ##[[KeyPgCubyte Cubyte]]## - ##[[KeyPgCshort Cshort]]## - ##[[KeyPgCushort Cushort]]## - ##[[KeyPgCint Cint]]## - ##[[KeyPgCuint Cuint]]## - ##[[KeyPgClng Clng]]## - ##[[KeyPgCulng Culng]]## - ##[[KeyPgClngint Clngint]]## - ##[[KeyPgCsng Csng]]## - ##[[KeyPgCdbl Cdbl]]## {{fbdoc item="back" value="CatPgCasting|Converting Data Types"}}{{fbdoc item="title" value="CUNSG"}}---- Converts an expression to unsigned {{fbdoc item="syntax"}}## **Cunsg** ( //expression// ) ## {{fbdoc item="usage"}}## //variable// = **Cunsg** ( //expression// ) ## Converts a signed ##//expression//## to an unsigned one, useful to force unsigned behavior of division or multiplication (including with ##[[KeyPgOpShiftLeft Shl]]## and ##[[KeyPgOpShiftRight Shr]]##). This is the opposite of ##[[KeyPgCsign Csign]]##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/casting/cunsg.bas"}}%%(freebasic) dim value as short = -1 print cunsg(value) '' will print 65535 %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Cunsg""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgCsign Csign]]## {{fbdoc item="back" value="CatPgCasting|Converting Data Types"}}{{fbdoc item="title" value="CURDIR"}}---- Returns the current directory/folder {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Curdir** ( ) [[KeyPgAs as]] [[KeyPgString string]] ## {{fbdoc item="usage"}}## //result// = **Curdir** ## {{fbdoc item="ret"}} A ##[[KeyPgString string]]## which is set to the name of the current directory/folder. {{fbdoc item="desc"}} Returns the current directory/folder. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/system/curdir.bas"}}%%(freebasic) print curdir %% output will vary. {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Curdir""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgOpen Open]]## - ##[[KeyPgDir Dir]]## - ##[[KeyPgMkdir Mkdir]]## - ##[[KeyPgRmdir Rmdir]]## {{fbdoc item="back" value="CatPgOpsys|Operating System Functions"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:50:14 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 3a78791ccc1b7728fc53743ec88238c9 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 2320 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="CUSHORT"}}---- Converts numeric or string expression to an unsigned integer (##[[KeyPgUshort Ushort]]##) {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Cushort** ( [[KeyPgByval byval]] //expression// [[KeyPgAs as]] [[DataType datatype]] ) [[KeyPgAs as]] [[KeyPgUshort ushort]] [[KeyPgType Type]] //typename// [[KeyPgDeclare declare]] [[KeyPgOperator operator]] [[KeyPgCast cast]] ( ) [[KeyPgAs as]] [[KeyPgUshort ushort]] End Type ## {{fbdoc item="usage"}}## //result// = **Cushort**( //numeric expression// ) //result// = **Cushort**( //string expression// ) //result// = **Cushort**( //user defined type// ) ## {{fbdoc item="param"}} ##//expression//## a numeric, string, or pointer expression to cast to a ##[[KeyPgUshort Ushort]]## value ##//datatype//## any numeric, string, or pointer data type ##//typename//## a user defined type {{fbdoc item="ret"}} A ##[[KeyPgUshort Ushort]]## value. {{fbdoc item="desc"}} The ##**Cushort**## function rounds off the decimal part and returns a 16 bit ##[[KeyPgUshort Ushort]]## value. The function does not check for an overflow, so be sure not to pas a value thats less/larger then 0 to 65535. The name can be explained as 'Convert to Unsigned Short'. If the argument is a string expression, it is converted to numeric by using ##[[KeyPgValuint Valuint]]##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/casting/cushort.bas"}}%%(freebasic) ' Using the CUSHORT function to convert a numeric value 'Create an USHORT variable DIM numeric_value AS USHORT 'Convert a numeric value numeric_value = CUSHORT(36000.4) 'Print the result, should return 36000 PRINT numeric_value SLEEP %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Cushort""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgCbyte Cbyte]]## - ##[[KeyPgCubyte Cubyte]]## - ##[[KeyPgCshort Cshort]]## - ##[[KeyPgCint Cint]]## - ##[[KeyPgCuint Cuint]]## - ##[[KeyPgClng Clng]]## - ##[[KeyPgCulng Culng]]## - ##[[KeyPgClngint Clngint]]## - ##[[KeyPgCulngint Culngint]]## - ##[[KeyPgCsng Csng]]## - ##[[KeyPgCdbl Cdbl]]## {{fbdoc item="back" value="CatPgCasting|Converting Data Types"}} {{fbdoc item="title" value="CUSTOM"}}---- Parameter to the ##[[KeyPgPutgraphics Put]]## graphics statement which selects a custom method {{fbdoc item="syntax"}}## **Put** [ //target//, ] [ STEP ] ( //x//,//y// ), //source// [ ,( //x1//,//y1// )-( //x2//,//y2// ) ], **Custom**, //custom_function_ptr// [, //parameter//] ## {{fbdoc item="param"}} ##**Custom**## Required. ##//custom_function_ptr//## name of the custom user defined function. ##//parameter//## optional [[KeyPgPointer pointer]] to be passed to the custom function; if omitted, the default value is zero. {{fbdoc item="desc"}} ##**Custom**## selects a custom user defined function as the method for blitting an image buffer. The ##Custom## method uses a user-defined function to calculate the final pixel values to be drawn to the destination buffer. This function will be called once for every pixel of the source image, and will receive the source and destination pixel values, and a data pointer passed by the ##[[KeyPgPutgraphics Put]]## function. The pixel value returned will be the value used to draw to the destination buffer. The function has the form: ##[[KeyPgDeclare declare]] [[KeyPgFunction function]] //identifier// ( [[KeyPgByval byval]] //source_pixel// [[KeyPgAs as]] [[KeyPgUinteger uinteger]], [[KeyPgByval byval]] //destination_pixel// [[KeyPgAs as]] [[KeyPgUinteger uinteger]], [[KeyPgByval byval]] //parameter// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] ) [[KeyPgAs as]] [[KeyPgUinteger uinteger]]## ##//identifier//## is the name of the function. Can be anything. ##//source_pixel//## is the current pixel value of the source image. ##//destination_pixel//## is the current pixel value of the destination image. ##//parameter//## is the parameter that is passed by the ##[[KeyPgPutgraphics Put]]## command. If it was omitted, its value will be zero. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/custom.bas"}}%%(freebasic) function dither ( byval source_pixel as uinteger, byval destination_pixel as uinteger, byval parameter as any ptr ) as uinteger ''either returns the source pixel or the destination pixel, depending on the outcome of rnd dim threshold as single = 0.5 if parameter <> 0 then threshold = *cptr(single ptr, parameter) if rnd() < threshold then return source_pixel else return destination_pixel end if end function dim img as any ptr, threshold as single '' set up a screen screenres 320, 200, 16, 2 screenset 0, 1 '' create an image img = imagecreate(32, 32) line img, ( 0, 0)-(15, 15), rgb(255, 0, 0), bf line img, (16, 0)-(31, 15), rgb( 0, 0, 255), bf line img, ( 0, 16)-(15, 31), rgb( 0, 255, 0), bf line img, (16, 16)-(31, 31), rgb(255, 0, 255), bf '' dither the image with varying thresholds do until len(inkey) cls threshold = 0.2 put ( 80 - 16, 100 - 16), img, custom, @dither, @threshold '' default threshold = 0.5 put (160 - 16, 100 - 16), img, custom, @dither threshold = 0.8 put (240 - 16, 100 - 16), img, custom, @dither, @threshold screencopy sleep 25 loop '' free the image memory imagedestroy img %% {{image class="center" title="Put Custom example output" url="/images/custom.png"}} {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgPutgraphics Put (Graphics)]]## {{fbdoc item="back" value="CatPgGfx2D|2D Drawing Functions"}}{{fbdoc item="title" value="CVD"}}---- Converts an eight byte string to a double-precision variable {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Cvd** ( [[KeyPgByref byref]] //str// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgDouble double]] ## {{fbdoc item="usage"}}## //result// = **Cvd**( //str// ) ## {{fbdoc item="param"}} ##//str//## A [[KeyPgString string]] exactly eight bytes in length with a binary copy of a double-precision variable stored in it. {{fbdoc item="ret"}} Returns a [[KeyPgDouble double-precision]] variable to copy the binary copy of a double to. {{fbdoc item="desc"}} Does a binary copy from a 8-byte-string to a double-precision variable. The result will have a sense only if the string contained a IEEE754 formated double value, as the one generated by ##[[KeyPgMkd Mkd]]##. This function is useful to read numeric values from buffers without using a ##[[KeyPgType Type]]## definition. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/cvd.bas"}}%%(freebasic) dim a as double, b as string a=4534.4243 b=mkd(a) print a, cvd(b) sleep %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgMkd Mkd]]## {{fbdoc item="back" value="CatPgString|String Functions"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:50:22 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: a8120ea40127a45d56348c60197773a7 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 2048 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="CVI"}}---- Converts an four byte string to an integer variable {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Cvi** ( [[KeyPgByref byref]] //str// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **Cvi**( //str// ) ## {{fbdoc item="param"}} ##//str//## A [[KeyPgString string]] exactly four bytes in length with a binary copy of an integer variable stored in it. {{fbdoc item="ret"}} An [[KeyPgInteger integer]] variable to copy the binary copy of a integer to. {{fbdoc item="desc"}} Returns a 32 bit ##[[KeyPgInteger Integer]]## value using the binary data contained in a string that is **exactly** four bytes in length. An integer value of zero (0) is returned if the string is not exactly four bytes in length. ##**Cvi**## is used to convert 4-byte-strings created with ##[[KeyPgMki Mki]]##. This function can also be used to convert 32 bit integer values from a memory or file buffer without the need for a ##[[KeyPgType ]]## structure. However, just as with the type structure, special care should be taken when using ##**Cvi**## to convert strings that have been read from a buffer. The ##[[KeyPgCvi Cvi]]## and ##[[KeyPgMki Mki]]## functions are processor dependent. That is, they will return different results depending on the endianness of the processor. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/cvi.bas"}}%%(freebasic) dim a as integer, b as string a=4534 b=mki(a) print a, cvi(b) sleep %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, ##**Cvi**## expects a 2-byte-string, since a QB integer is only 16 bits. Only the first two bytes of the string are used, even if the string happens to be longer than two bytes. {{fbdoc item="diff"}} - In QB an error occurs if the string passed is less than two bytes in length. {{fbdoc item="see"}} - ##[[KeyPgMki Mki]]## {{fbdoc item="back" value="CatPgString|String Functions"}} {{fbdoc item="title" value="CVL"}}---- Converts an four byte string to an integer (long) variable {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Cvl** ( [[KeyPgByref byref]] //str// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **Cvl**( //str// ) ## {{fbdoc item="param"}} ##//str//## A [[KeyPgString string]] exactly four bytes in length with a binary copy of an integer variable stored in it. {{fbdoc item="ret"}} A [[KeyPgInteger integer]] variable to copy the binary copy of a integer to. {{fbdoc item="desc"}} Does a binary copy from a 4-byte-string to a long variable. The result will have a sense only if the string contained a correctly formatted integer, as the one generated by ##[[KeyPgMkl Mkl]]## or ##[[KeyPgMki Mki]]##. This function is useful to read numeric values from buffers without using a ##[[KeyPgType Type]]## definition. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/cvl.bas"}}%%(freebasic) dim a as integer, b as string a=4534 b=mki(a) print a, cvi(b) sleep %% {{fbdoc item="diff"}} - None. {{fbdoc item="see"}} - ##[[KeyPgMkl Mkl]]## {{fbdoc item="back" value="CatPgString|String Functions"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:50:31 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 6ab08073ec34d18403dfe984376132bc Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 1521 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="CVLONGINT"}}---- Converts an eight byte string to a long integer variable {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Cvlongint** ( [[KeyPgByref byref]] //str// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgLongint longint]] ## {{fbdoc item="usage"}}## //result// = **Cvlongint**( //str// ) ## {{fbdoc item="param"}} ##//str//## A [[KeyPgString string]] exactly eight bytes in length with a binary copy of a long integer variable stored in it. {{fbdoc item="ret"}} A [[KeyPgLongint longint]] variable to copy the binary copy of a long integer to. {{fbdoc item="desc"}} Does a binary copy from an 8-byte-string to a longint variable. The result will have a sense only if the string contained a correctly formatted longint, as the one generated by ##[[KeyPgMklongint Mklongint]]## This function is useful to read numeric values from buffers without using a ##[[KeyPgType Type]]## definition. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/cvlongint.bas"}}%%(freebasic) dim a as longint, b as string a=4534 b=mklongint(a) print a, cvlongint(b) sleep %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Cvlongint""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgMklongint Mklongint]]## {{fbdoc item="back" value="CatPgString|String Functions"}} {{fbdoc item="title" value="CVS"}}---- Converts an four byte string to an single-precision variable {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Cvs** ( [[KeyPgByref byref]] //str// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgSingle single]] ## {{fbdoc item="usage"}}## //result// = **Cvs**( //str// ) ## {{fbdoc item="param"}} ##//str//## A [[KeyPgString string]] exactly four bytes in length with a binary copy of an single-precision variable stored in it. {{fbdoc item="ret"}} Returns a [[KeyPgSingle single]] variable to copy the binary copy of a single to. {{fbdoc item="desc"}} Does a binary copy from a 4-byte-string to a ##[[KeyPgSingle Single]]## variable. The result will have a sense only if the string contained a IEEE754 formated single value, as the one generated by ##[[KeyPgMks Mks]]##. This function is useful to read numeric values from buffers without using a ##[[KeyPgType Type]]## definition. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/cvs.bas"}}%%(freebasic) dim a as single, b as string a=4534.4243 b=mks(a) print a, cvs(b) sleep %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgMks Mks]]## {{fbdoc item="back" value="CatPgString|String Functions"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:50:39 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: f8d34fad9db2a63674707e81d8c28e1b Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 1535 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="CVSHORT"}}---- Converts an two byte string to a short variable {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Cvshort** ( [[KeyPgByref byref]] //str// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgShort short]] ## {{fbdoc item="usage"}}## //result// = **Cvshort**( //str// ) ## {{fbdoc item="param"}} ##//str//## A ##[[KeyPgString String]]## exactly two bytes in length with a binary copy of a short variable stored in it. {{fbdoc item="ret"}} Returns a ##[[KeyPgShort Short]]## variable to copy the binary copy of a short to. {{fbdoc item="desc"}} Does a binary copy from a 2-byte-string to a ##[[KeyPgShort Short]]## variable. The result will have a sense only if the string contained a correctly formatted ##[[KeyPgShort Short]]##, as the one generated by ##[[KeyPgMkshort Mkshort]]## This function is useful to read numeric values from buffers without using a ##[[KeyPgType Type]]## definition. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/cvshort.bas"}}%%(freebasic) dim a as short, b as string a=4534 b=mkshort(a) print a, cvshort(b) sleep %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Cvshort""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="diff"}} - In QBasic this function is called CVI {{fbdoc item="see"}} - ##[[KeyPgMkshort Mkshort]]## {{fbdoc item="back" value="CatPgString|String Functions"}} {{fbdoc item="title" value="DATA"}}---- Statement to store data at compile time. {{fbdoc item="syntax"}}## **Data** //constant_expression1// [,//constant_expression2//]... ## {{fbdoc item="desc"}} ##Data## stores a list of constant numeric or alphabetical expressions that are evaluated at compile time and stored as constants that can be read into variables by using ##[[KeyPgRead Read]]##. All the ##Data## statements in the program behave as a single chained list; after the last element of a ##Data## is read, the first element of the following ##Data## will be read. If a ##Read## is attempted after the last element of the last ##Data##, an error will occur. ##Data## statements are only visible from within the module in which they are defined. ##Data## constants can only be of simple types (numeric or string). String constants must be enclosed in double quotes. A numeric value can be read as a numeric literal into a string. A string read into a numeric variable will be evaluated by the ##[[KeyPgVal Val]]## function. ##[[KeyPgRestore Restore]]## //label// makes the first ##Data## item after the //label// the next item to be read, thus altering the order in which the items are ##Read##. ##Data## is normally used to initialize variables. FreeBASIC also allows the initialization of static variables in their declarations; see [[ProPgInitialization Variable Initializers]] for more information. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/data/data.bas"}}%%(freebasic) ' Create an array of 5 integers and a string to hold the data. DIM h(4) AS INTEGER DIM hs AS STRING dim read_data as integer ' Set up to loop 5 times (for 5 numbers... check the data) FOR read_data = 0 TO 4 ' Read in an integer. READ h(read_data) ' Display it. PRINT "Number"; read_data;" = "; h(read_data) NEXT ' Spacer. PRINT ' Read in a string. READ hs ' Print it. PRINT "String = " + hs ' Await a keypress. SLEEP ' Exit program. END ' Block of data. DATA 3, 234, 435/4, 23+433, 87643,"Good"+ "Bye!" %% {{fbdoc item="lang"}} - //[[CompilerOptlang -lang fb]]// and //[[CompilerOptlang -lang fblite]]// considers data items as constant expressions that are evaluated during compilation and its result stored in the program. - //[[CompilerOptlang -lang qb]]// considers data items as literals and stores then without change, as in QB. {{fbdoc item="diff"}} - Alphabetic string literals now **must** be enclosed within quotation marks, in QB this was optional. - In QB empty items evaluated to number 0 or to empty strings, in FreeBASIC they give a compile error. In QB a comma after the last item of a line of data made an empty item (between the comma and the carry return) and evaluated to 0 or empty string. In FreeBASIC that's an error. {{fbdoc item="see"}} - ##[[KeyPgRead Read]]## - ##[[KeyPgRestore Restore]]## {{fbdoc item="back" value="CatPgMisc|Miscellaneous"}}{{fbdoc item="title" value="DATE"}}---- Returns the current system date as a string {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Date** ( ) [[KeyPgAs as]] [[KeyPgString string]] ## {{fbdoc item="usage"}}## //result// = **Date** ## {{fbdoc item="ret"}} Returns the current system date, in the format ##mm-dd-yyyy## {{fbdoc item="desc"}} None {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/dates/date.bas"}}%%(freebasic) print date ' prints the current date %% {{fbdoc item="diff"}} - The QB DATE statement (to set the system date) is now called ##[[KeyPgSetdate Setdate]]##. {{fbdoc item="see"}} - ##[[KeyPgSetdate Setdate]]## - ##[[KeyPgTime Time]]## - ##[[KeyPgTimer Timer]]## {{fbdoc item="back" value="CatPgDate|Date and Time Functions"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:50:47 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 463d777c69d07ccf8f5a9217aadebfbe Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 1978 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="DateAdd"}}---- Offset a date with a specified interval {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""DateAdd""** ( //interval// [[KeyPgAs as]] [[KeyPgString string]], [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgDouble double]], [[KeyPgByval byval]] //date_serial// [[KeyPgAs as]] [[KeyPgDouble double]] ) [[KeyPgAs as]] [[KeyPgDouble double]] ## {{fbdoc item="usage"}}## #include "vbcompat.bi" //result// = **""DateAdd""**( //interval//, //number//, //date_serial// ) ## {{fbdoc item="param"}} ##//interval//## string indicating which period of time corresponds to one unit of ##//number//## ##//number//## the number of intervals to add to the base date. The number will be rounded to the nearest integer. ##//date_serial//## the base date {{fbdoc item="ret"}} Returns a [[ProPgDates Date Serial]] corresponding to the received ##//date_serial//## plus the ##//number//## of ##//intervals//##. {{fbdoc item="desc"}} Interval is specified as follows: {{table columns="2" cellpadding="1" cells="value;interval;yyyy;years;q;quarter(three months);m;months;ww;weeks;d,w,y;days;h;hours;n;minutes;s;seconds"}} The compiler will not recognize this function unless ##vbcompat.bi## or ##datetime.bi## is included. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/dates/dateadd.bas"}}%%(freebasic) #include "vbcompat.bi" const fmt = "ddddd ttttt" dim d as double d = now() print "1 hour from now is "; print Format( DateAdd( "h", 1, d ), fmt ) print "1 day from now is "; print Format( DateAdd( "d", 1, d ), fmt ) print "1 week from now is "; print Format( DateAdd( "ww", 1, d ), fmt ) print "1 month from now is "; print Format( DateAdd( "m", 1, d ), fmt ) %% {{fbdoc item="diff"}} - Did not exist in QB. This function appeared in Visual Basic. {{fbdoc item="see"}} - [[ProPgDates Date Serials]] {{fbdoc item="back" value="CatPgDate|Date and Time Functions"}} {{fbdoc item="title" value="DateDiff"}}---- Gets the difference of two dates measured by a specified interval {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""DateDiff""** ( //interval// [[KeyPgAs as]] [[KeyPgString string]], [[KeyPgByval byval]] //serial1// [[KeyPgAs as]] [[KeyPgDouble double]], [[KeyPgByval byval]] //serial2// [[KeyPgAs as]] [[KeyPgDouble double]], [[KeyPgByval byval]] //firstdayofweek// [[KeyPgAs as]] [[KeyPgInteger integer]] = fbUseSystem, [[KeyPgByval byval]] //firstdayofyear// [[KeyPgAs as]] [[KeyPgInteger integer]] = fbUseSystem ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## #include "vbcompat.bi" //result// = **""DateDiff""**( //interval//, //date_serial1//, //date_serial2// [, //firstdayofWeek// [, //firstweekofyear// ] ] ) ## {{fbdoc item="param"}} ##//interval//## the unit of time (interval) with which to measure the difference ##//date_serial1//## starting date serial ##//date_serial2//## end date serial ##//firstdayofweek//## first day of the week ##//firstdayofyear//## first day of the year {{fbdoc item="ret"}} Returns an integer corresponding to the number of ##//interval//##s found between two [[ProPgDates Date Serials]]. If ##//date_serial1//## > ##//date_serial2//##, the result is negative. {{fbdoc item="desc"}} ##//interval//## is specified as follows: {{table columns="2" cellpadding="1" cells="value;interval;yyyy;years;q;quarter(three months);m;months;w; seven day periods; ww;calendar weeks;d,y;days;h;hours;n;minutes;s;seconds"}} ##//first_dayofweek//## Affects the counting when ##'ww'## interval is used. {{table columns="3" cellpadding="1" cells="value;first day of week;constant;omitted;sunday;###;0;local settings;fbUseSystem;1;sunday;fbSunday;2;monday;fbMonday;3;tuesday;fbTuesday;4;wednesday;fbWednesday;5;thursday;fbThursday;6;friday;fbFriday;7;saturday;fbSaturday"}} ##//first_weekofyear//## specifies which year (previous or next) that the week which spans the end of one year and the beginning of the next should included with. {{table columns="3" cellpadding="1" cells="value;first week of year;constant;0;local settings;fbUseSystem;1;January 1's week;fbFirstJan1;2;first weeks having 4 days in the year;fbFirstFourDays;3;first full week of year;fbFirstFullWeek"}} Notice if you do an arithmetical subtraction of two date serials you get the difference in days. The compiler will not recognize this function unless ##vbcompat.bi## or ##datetime.bi## is included. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/dates/datediff.bas"}}%%(freebasic) #include "vbcompat.bi" dim s as string, d1 as double, d2 as double line input "Enter your birthday: ", s if Isdate( s ) then d1 = DateValue( s ) d2 = now() print "You are " & DateDiff( "yyyy", d1, d2 ) & " years old." print "You are " & DateDiff( "d", d1, d2 ) & " days old." print "You are " & DateDiff( "s", d1, d2 ) & " seconds old." else print "Invalid date" end if %% {{fbdoc item="diff"}} - Did not exist in QB. This function appeared in Visual Basic. {{fbdoc item="see"}} - [[ProPgDates Date Serials]] {{fbdoc item="back" value="CatPgDate|Date and Time Functions"}}{{fbdoc item="title" value="DatePart"}}---- Gets an interval from a date {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""DatePart""** ( //interval// [[KeyPgAs as]] [[KeyPgString string]], [[KeyPgByval byval]] //date_serial// [[KeyPgAs as]] [[KeyPgDouble double]], [[KeyPgByval byval]] //firstdayofweek// [[KeyPgAs as]] [[KeyPgInteger integer]] = fbUseSystem, [[KeyPgByval byval]] //firstdayofyear// [[KeyPgAs as]] [[KeyPgInteger integer]] = fbUseSystem ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## #include "vbcompat.bi" //result// = **""DatePart""**( //interval//, //date_serial//, //first_dayofWeek// [, //first_week_of_year// ] ) ## {{fbdoc item="param"}} ##//interval//## string indicating which part of the date is required ##//date_serial//## the date serial to decode ##//firstdayofweek//## first day of the week ##//firstdayofyear//## first day of the year {{fbdoc item="ret"}} Return an integer representing the ##//interval//## in the [[ProPgDates Date Serial]]. {{fbdoc item="desc"}} ##//interval//## string indicating which part of the date is required is specified as follows: {{table columns="2" cellpadding="1" cells="value;interval;yyyy;years;q;quarter(three months);m;months; w; weekday; ww; week of the year;y;day of the year;d;day of the month;h;hours;n;minutes;s;seconds"}} ##//first_dayofweek//## Affects the output when 'w' interval is required. {{table columns="3" cellpadding="1" cells="value;first day of week;constant;omitted;sunday;###;0;local settings;fbUseSystem;1;sunday;fbSunday;2;monday;fbMonday;3;tuesday;fbTuesday;4;wednesday;fbWednesday;5;thursday;fbThursday;6;friday;fbFriday;7;saturday;fbSaturday"}} ##//first_weekofyear//## specifies which year (previous or next) that the week which spans the end of one year and the beginning of the next should included with. Affects the output when ##'ww'## interval is required. {{table columns="3" cellpadding="1" cells="value;first week of year;constant;0;local settings;fbUseSystem;1;January 1's week;fbFirstJan1;2;first weeks having 4 days in the year;fbFirstFourDays;3;first full week of year;fbFirstFullWeek"}} The compiler will not recognize this function unless ##vbcompat.bi## or ##datetime.bi## is included. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/dates/datepart.bas"}}%%(freebasic) #include "vbcompat.bi" dim d as double d = now() print "Today is day " & DatePart( "y", d ); print " in week " & DatePart( "ww", d ); print " of the year " & DatePart( "yyyy", d ) %% {{fbdoc item="diff"}} - Did not exist in QB. This function appeared in Visual Basic. {{fbdoc item="see"}} - [[ProPgDates Date Serials]] {{fbdoc item="back" value="CatPgDate|Date and Time Functions"}}{{fbdoc item="title" value="DATESERIAL"}}---- Creates a [[ProPgDates date serial]] {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""DateSerial""** ( [[KeyPgByval byval]] //year// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByval byval]] //month// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByval byval]] //day// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## #include "vbcompat.bi" //result// = **""DateSerial""**( //year//, //month//, //day// ) ## {{fbdoc item="param"}} ##//year//## the year ##//month//## the month of the year ##//day//## the day of the month {{fbdoc item="ret"}} Returns a [[ProPgDates date serial]] containing the date formed by the values in the ##//year//##, ##//month//## and ##//day//## parameters.The date serial returned has no decimal part. {{fbdoc item="desc"}} The compiler will not recognize this function unless ##vbcompat.bi## or ##datetime.bi## is included. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/dates/dateserial.bas"}}%%(freebasic) #include "vbcompat.bi" dim a as double = dateserial(2005, 11, 28) print format(a, "yyyy/mm/dd hh:mm:ss") %% {{fbdoc item="diff"}} - Did not exist in QB. This function appeared in PDS and VBDOS {{fbdoc item="see"}} - [[ProPgDates Date Serials]] - ##[[KeyPgDateSerial DateSerial]]## - ##[[KeyPgTimeValue TimeValue]]## - ##[[KeyPgDateValue DateValue]]## {{fbdoc item="back" value="CatPgDate|Date and Time Functions"}}{{fbdoc item="title" value="DATEVALUE"}}---- Returns a [[ProPgDates Date Serial]] from a string {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""DateValue""** ( [[KeyPgByref byref]] //date_string// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgDouble double]] ## {{fbdoc item="usage"}}## #include "vbcompat.bi" //result// = **""DateValue""**( //date_string// ) ## {{fbdoc item="param"}} ##//date_string//## the string to convert to a date serial {{fbdoc item="ret"}} Returns a [[ProPgDates Date Serial]] from a date string. {{fbdoc item="desc"}} The date string must be in the format set in the regional settings of the Operating System. ##**""DateValue""**( Date() )## will work correctly only if the regional settings specify the same short date format QB used (##mm-dd-yyyy##). Consider using the ##[[KeyPgNow Now]]## function in the expression ##Fix(Now())## to obtain the current date as a date serial. The compiler will not recognize this function unless ##vbcompat.bi## or ##datetime.bi## is included. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/dates/datevalue.bas"}}%%(freebasic) #include "vbcompat.bi" dim as integer v1, v2 dim as string s1, s2 print "Enter first date: "; line input s1 if IsDate( s1 ) = 0 then print "not a date" end end if print "Enter second date: "; line input s2 if IsDate( s2 ) = 0 then print "not a date" end end if '' convert the strings to date serials v1 = DateValue( s1 ) v2 = DateValue( s2 ) print "Number of days between dates is " & abs( v2 - v1 ) %% {{fbdoc item="diff"}} - Did not exist in QB. This function appeared in PDS and VBDOS {{fbdoc item="see"}} - [[ProPgDates Date Serials]] - ##[[KeyPgDateSerial DateSerial]]## - ##[[KeyPgTimeValue TimeValue]]## {{fbdoc item="back" value="CatPgDate|Date and Time Functions"}}{{fbdoc item="title" value="DAY"}}---- Gets the day of the month from a [[ProPgDates Date Serial]] {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Day** ( [[KeyPgByval byval]] //date_serial// [[KeyPgAs as]] [[KeyPgDouble double]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## #include "vbcompat.bi" //result// = **Day**( //date_serial// ) ## {{fbdoc item="param"}} ##//date_serial//## the date {{fbdoc item="ret"}} Returns the day of the month from a variable containing a date in [[ProPgDates Date Serial]] format. {{fbdoc item="desc"}} The compiler will not recognize this function unless ##vbcompat.bi## is included. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/dates/day.bas"}}%%(freebasic) #include "vbcompat.bi" dim ds as double = dateserial(2005, 11, 28) print format(ds, "yyyy/mm/dd "); day(ds) %% {{fbdoc item="diff"}} - Did not exist in QB. This function appeared in PDS and VBDOS {{fbdoc item="see"}} - [[ProPgDates Date Serials]] {{fbdoc item="back" value="CatPgDate|Date and Time Functions"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:50:58 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 4601d7b20fc19cd379404c673a9319df Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 556 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="__DATE__"}}---- Intrinsic define (macro value) set by the compiler {{fbdoc item="syntax"}}## ""__DATE__"" ## {{fbdoc item="desc"}} Substitutes the compiler date (##yyyy-mm-dd## format) were used. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/date.bas"}}%%(freebasic) Print "Compile Date: ";__DATE__ %% %% Compile Date: 2005-05-31 %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDdtime __TIME__]]## {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}} {{fbdoc item="title" value="__FB_ARGC__"}}---- Intrinsic define (macro value) set by the compiler {{fbdoc item="syntax"}}## ""__FB_ARGC__"" ## {{fbdoc item="desc"}} Substituted with the number of arguments passed in on the command line. **""__FB_ARGC__""** is the name of a parameter passed to the program's implicit main function, and therefore is only defined in the module level code of the main module for an application. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/fbargc.bas"}}%%(freebasic) dim i as integer for i = 0 to __FB_ARGC__ - 1 print "arg "; i; " = '"; command(i); "'" next i %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDdfbargv __FB_ARGV__]]## {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}} {{fbdoc item="title" value="__FB_ARGV__"}}---- Intrinsic define (macro value) set by the compiler {{fbdoc item="syntax"}}## ""__FB_ARGV__"" ## {{fbdoc item="desc"}} Substituted with a pointer to a list of pointers to the zero terminated command line arguments passed in on the command line. **""__FB_ARGV__""** is the name of a parameter passed to the program's implicit main function, and therefore is only defined in the module level code of the main module for an application. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/fbargv.bas"}}%%(freebasic) declare function main _ ( _ byval argc as integer, _ byval argv as zstring ptr ptr _ ) as integer end main( __FB_ARGC__, __FB_ARGV__ ) private function main _ ( _ byval argc as integer, _ byval argv as zstring ptr ptr _ ) as integer dim i as integer for i = 0 to argc - 1 print "arg "; i; " = '"; *argv[i]; "'" next i return 0 end function %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDdfbargc __FB_ARGC__]]## {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}} {{fbdoc item="title" value="__FB_BIGENDIAN__"}}---- Intrinsic define set by the compiler {{fbdoc item="syntax"}}## ""__FB_BIGENDIAN__"" ## {{fbdoc item="desc"}} Define without a value created at compile time if compiling for a big endian target. It can be used to compile parts of the program only if the target is big endian. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/fbbigendian.bas"}}%%(freebasic) #IFDEF __FB_BIGENDIAN__ '...instructions only for big endian machines #ELSE '...instructions only for little endian machines #ENDIF %% {{fbdoc item="diff"}} - Did not exist in QB {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:51:07 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: b87f59dea0794c0ea628d1c21a0fd3e0 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 585 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="__FB_BUILD_DATE__"}}---- Intrinsic define (macro string) set by the compiler {{fbdoc item="syntax"}}## ""__FB_BUILD_DATE__"" ## {{fbdoc item="desc"}} Substituted with the quoted string containing the date (##MM-DD-YYYY##) the compiler was built on. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/fbbuilddate.bas"}}%%(freebasic) Print "This program compiled with a compiler built on this date:" & __FB_BUILD_DATE__ %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}} {{fbdoc item="title" value="__FB_CYGWIN__"}}---- Intrinsic define set by the compiler {{fbdoc item="syntax"}}## ""__FB_CYGWIN__"" ## {{fbdoc item="desc"}} Define without a value created at compile time in the Cygwin version of the compiler, or when the //[[CompilerOpttarget -target cygwin]]// command line option is used. It can be used to compile parts of the program only if the target is Cygwin. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/fbcygwin.bas"}}%%(freebasic) #IFDEF __FB_CYGWIN__ '...instructions only for Cygwin... #ELSE '...instructions not for Cygwin... #ENDIF %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDdfblinux __FB_LINUX__]]## - ##[[KeyPgDdfbwin32 __FB_WIN32_]]## - [[CompilerOpttarget Compiler Option: -target]] {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}}{{fbdoc item="title" value="__FB_DEBUG__"}}---- Intrinsic define (macro value) set by the compiler {{fbdoc item="syntax"}}## ""__FB_DEBUG__"" ## {{fbdoc item="desc"}} ##""__FB_DEBUG__""## indicates if the the generate debug information option '-g' was specified on the command line at the time of compilation. Returns non-zero (-1) if the option was specified. Returns zero (0) otherwise. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/fbdebug.bas"}}%%(freebasic) #if __FB_DEBUG__ <> 0 #print Debug mode #else #print Release mode #endif %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDdfberr __FB_ERR__]]## - ##[[KeyPgDdfbmt __FB_MT__]]## - [[CompilerOptg Compiler Option: -g]] {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}}{{fbdoc item="title" value="__FB_DOS__"}}---- Intrinsic define set by the compiler {{fbdoc item="syntax"}}## ""__FB_DOS__"" ## {{fbdoc item="desc"}} Define without a value created at compile time if compiling for the DOS target. Default in the DOS hosted version, or active when the //[[CompilerOpttarget -target dos]]// command line option is used. It can be used to compile parts of the program only if the target is DOS. Note: the DOS hosted version cannot compile to other targets than DOS by now. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/fbdos.bas"}}%%(freebasic) #IFDEF __FB_DOS__ ' ... instructions only for DOS ... ' ... INT 0x31 #ELSE ' ... instructions not for DOS ... #ENDIF %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDdfblinux __FB_LINUX__]]## - ##[[KeyPgDdfbwin32 __FB_WIN32__]]## - ##[[FaqDOS DOS related FAQ]]## - [[CompilerOpttarget Compiler Option: -target]] {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}} {{fbdoc item="title" value="__FB_ERR__"}}---- Intrinsic define (macro value) set by the compiler {{fbdoc item="syntax"}}## ""__FB_ERR__"" ## {{fbdoc item="desc"}} ##""__FB_ERR__""## indicates if //[[CompilerOpte -e]]//, //[[CompilerOptex -ex]]//, or //[[CompilerOptexx -exx]]// was specified on the compiler command line at the time of compilation of a module. Returns one of the following values: {{table columns="2" cellpadding="1" cells="value;description;0;'-e', '-ex', '-exx' not specified;1;'-e' was specified;3;'-ex' was specified;7;'-exx' was specified"}} ##""__FB_ERR__""## is always defined. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/fberr.bas"}}%%(freebasic) 'Example code to demonstrate a use of __FB_ERR__ dim err_command_line as ubyte err_command_line = __FB_ERR__ select case err_command_line case 0 print "No Error Checking enabled on the Command Line!" case 1 print "Some Error Checking enabled on the Command Line!" case 3 print "QBasic style Error Checking enabled on the Command Line!" case 7 print "Extreme Error Checking enabled on the Command Line!" case else print "Some Unknown Error level has been set!" end select %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDdfbmt __FB_MT__]]## - ##[[KeyPgDdfbdebug __FB_DEBUG__]]## - [[CompilerOpte Compiler Option: -e]] - [[CompilerOptex Compiler Option: -ex]] - [[CompilerOptexx Compiler Option: -exx]] - [[ProPgErrorHandling Error Handling]] {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}}{{fbdoc item="title" value="__FB_FREEBSD__"}}---- Intrinsic define set by the compiler {{fbdoc item="syntax"}}## ""__FB_FREEBSD__"" ## {{fbdoc item="desc"}} Define without a value created at compile time in the FreeBSD version of the compiler, or when the //[[CompilerOpttarget -target freebsd]]// command line option is used. It can be used to compile parts of the program only if the target is FreeBSD. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/fbfreebsd.bas"}}%%(freebasic) #IFDEF __FB_FREEBSD__ '...instructions only for FreeBSD... #ELSE '...instructions not for FreeBSD... #ENDIF %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDdfblinux __FB_LINUX__]]## - ##[[KeyPgDdfbwin32 __FB_WIN32__]]## - [[CompilerOpttarget Compiler Option: -target]] {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}}{{fbdoc item="title" value="__FB_LANG__"}}---- Intrinsic define (macro value) set by the compiler {{fbdoc item="syntax"}}## ""__FB_LANG__"" ## {{fbdoc item="desc"}} ##""__FB_LANG__""## indicates which language compatibility option was set using the //[[CompilerOptlang -lang]]// option as specified on the compiler command line at the time of compilation of a module. Returns a lower case string with one of the following values: {{table columns="2" cellpadding="1" cells="value;description;''fb'';FreeBASIC compatibility (default);''qb'';qbasic compatibility;''fblite'';FreeBASIC language compatibility, with a more QBASIC-compatible coding style;''deprecated'';previous fbc version compatibility"}} ##""__FB_LANG__""## is always defined. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/fblang.bas"}}%%(freebasic) '' Set option explicit always on #ifdef __FB_LANG__ #if __FB_LANG__ <> "fb" Option Explicit #endif #else '' Older version - before lang fb Option Explicit #endif %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDdfbversion __FB_VERSION__]]## - [[CompilerOptlang Compiler Option: -lang]] - [[CompilerDialects Compiler Dialects]] {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:51:17 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 72a14b0f7c98c6b1863b5f7cd2bc4cf5 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 961 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="__FB_LINUX__"}}---- Intrinsic define set by the compiler {{fbdoc item="syntax"}}## ""__FB_LINUX__"" ## {{fbdoc item="desc"}} Define without a value created at compile time when compiling to the Linux target. Default in the Linux hosted version of the compiler, or active when the //[[CompilerOpttarget -target linux]]// command line option is used. It can be used to compile parts of the program only if the target is Linux. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/fblinux.bas"}}%%(freebasic) #IFDEF __FB_LINUX__ ' ... instructions only for Linux ... ' ... #libpath "/usr/X11/lib" #ELSE ' ... instructions not for Linux ... #ENDIF %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDdfbdos __FB_DOS__]]## - ##[[KeyPgDdfbwin32 __FB_WIN32__]]## - [[CompilerOpttarget Compiler Option: -target]] {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}} {{fbdoc item="title" value="__FB_MAIN__"}}---- Intrinsic define set by the compiler {{fbdoc item="syntax"}}## ""__FB_MAIN__"" ## {{fbdoc item="desc"}} ##""__FB_MAIN__""## is defined in the main module and not defined in other modules. The main module is determined by the compiler as either the first source file listed on the command line or explicitly named using the -m option on the command line. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/fbmain.bas"}}%%(freebasic) #ifdef __FB_MAIN__ #print Compiling the main module #else #print Compiling an additional module #endif %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - [[CompilerOptm Compiler Option: -m]] - ##[[KeyPgPpifdef #ifdef]]## - ##[[KeyPgPpifndef #ifndef]]## {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:51:26 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: d16fb2aecf1d9fbf206cbbad8e110125 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 1501 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="__FB_MIN_VERSION__"}}---- Macro function to test minimum compiler version {{fbdoc item="syntax"}}## [[KeyPgPpdefine #define]] **""__FB_MIN_VERSION__""**( //major//, //minor//, //patch//) _ (([[KeyPgDdFBVerMajor __FB_VER_MAJOR__]] > major) or _ (([[KeyPgDdFBVerMajor __FB_VER_MAJOR__]] = major) and (([[KeyPgDdFBVerMinor __FB_VER_MINOR__]] > minor) or _ ([[KeyPgDdFBVerMinor __FB_VER_MINOR__]] = minor and [[KeyPgDdFBVerPatch __FB_VER_PATCH__]] >= patch_level)))) ## {{fbdoc item="usage"}}## **""__FB_MIN_VERSION__""**( //major//, //minor//, //patch//) ## {{fbdoc item="param"}} ##//major//## minimum major version to test ##//minor//## minimum minor version to test ##//patch//## minimum patch version to test {{fbdoc item="ret"}} Returns zero (0) if the compiler version is less than the specified version, or non-zero (-1) if the compiler version is greater than or equal to specified version {{fbdoc item="desc"}} ##""__FB_MIN_VERSION__""## tests for a minimum version of the compiler. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/fbminversion.bas"}}%%(freebasic) #if Not __FB_MIN_VERSION__(0, 18, 2) #error fbc must be at least version 0.18.2 to compile this module #endif %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - [[KeyPgPpif #IF]] {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}} {{fbdoc item="title" value="__FB_MT__"}}---- Intrinsic define (macro value) set by the compiler {{fbdoc item="syntax"}}## ""__FB_MT__"" ## {{fbdoc item="desc"}} ##""__FB_MT__""## indicates if the the multithreaded option //[[CompilerOptmt -mt]]// was specified on the command line at the time of compilation. Returns non-zero (-1) if the option was specified. Returns zero (0) otherwise. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/fbmt.bas"}}%%(freebasic) #if __FB_MT__ #print using multi-threaded library #else #print using single-threaded library #endif %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDdfbdebug __FB_DEBUG__]]## - [[CompilerOptmt Compiler Option: -mt]] {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}}{{fbdoc item="title" value="__FB_OPTION_BYVAL__"}}---- Intrinsic define (macro value) set by the compiler {{fbdoc item="syntax"}}## ""__FB_OPTION_BYVAL__"" ## {{fbdoc item="desc"}} Indicates if parameters to a ##[[KeyPgFunction Function]]## or ##[[KeyPgSub Sub]]## are passed by reference as with ##[[KeyPgByref Byref]]##, or by value as with ##[[KeyPgByval Byval]]## by default when the by value / by reference specifier is not explicitly stated. ##""__FB_OPTION_BYVAL__""## is set to non-zero (-1) if by default parameters are passed value, and zero (0) if by default parameters are passed by reference. The default for passing parameters by reference or by value is determined by the //[[CompilerOptlang -lang]]// command line option used during compilation or usage of ##[[KeyPgOptionbyval Option Byval]]## in the source file. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/fboptionbyval.bas"}}%%(freebasic) #if( __FB_OPTION_BYVAL__ <> 0 ) #error Option ByVal must not be used With This source #endif %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgByval Byval]]## - ##[[KeyPgByref Byref]]## - ##[[KeyPgOptionbyval Option Byval]]## {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:51:34 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 890a9c7fb67e40d433501fe989bfb522 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 839 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="__FB_OPTION_DYNAMIC__"}}---- Intrinsic define (macro value) set by the compiler {{fbdoc item="syntax"}}## ""__FB_OPTION_DYNAMIC__"" ## {{fbdoc item="desc"}} ##""__FB_OPTION_DYNAMIC__""## is defined as true (negative one (-1)) if a recent ##[[KeyPgOptiondynamic Option Dynamic]]## statement or ##[[KeyPgMetaDynamic '$Dynamic]]## meta-command was issued. Otherwise, it is defined as zero (0). {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/fboptiondynamic.bas"}}%%(freebasic) #if __FB_OPTION_DYNAMIC__ <> 0 #error This module must not use Option Dynamic #endif %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgOptiondynamic Option Dynamic]]## - ##[[KeyPgOptionstatic Option Static]]## {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}} {{fbdoc item="title" value="__FB_OPTION_ESCAPE__"}}---- Intrinsic define (macro value) set by the compiler {{fbdoc item="syntax"}}## ""__FB_OPTION_ESCAPE__"" ## {{fbdoc item="desc"}} Indicates if by default, string literals are processed for escape characters when not explicitly prefixed with the [[KeyPgOpPpNoescape $ operator]] for non-escaped strings, or the [[KeyPgOpPpEscape ! operator]] for escaped strings. The default method for processing string literals is set by usage of the //[[CompilerOptlang -lang]]// command line option during compilation or usage of ##[[KeyPgOptionescape Option Escape]]## in the source file. ##""__FB_OPTION_ESCAPE__""## returns zero (0) if the option has not been set. Returns non-zero (-1) if the option has been set. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/fboptionescape.bas"}}%%(freebasic) #if( __FB_OPTION_ESCAPE__ <> 0 ) #error Option Escape must not be used with this include file #endif %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgOptionescape Option Escape]]## {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}}{{fbdoc item="title" value="__FB_OPTION_EXPLICIT__"}}---- Intrinsic define (macro value) set by the compiler {{fbdoc item="syntax"}}## ""__FB_OPTION_EXPLICIT__"" ## {{fbdoc item="desc"}} ##""__FB_OPTION_EXPLICIT__""## indicates if ##[[KeyPgOptionexplicit Option Explicit]]## has been used previously in the source. Returns zero (0) if the option has not been set. Returns non-zero (-1) if the option has been set. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/fboptionexplicit.bas"}}%%(freebasic) #if( __FB_OPTION_EXPLICIT__ = 0 ) #error Option Explicit must used with this module #endif %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDim Dim]]## - ##[[KeyPgOptionexplicit Option Explicit]]## {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}} {{fbdoc item="title" value="__FB_OPTION_GOSUB__"}}---- Intrinsic define (macro value) set by the compiler {{fbdoc item="syntax"}}## ""__FB_OPTION_GOSUB__"" ## {{fbdoc item="desc"}} Indicates how ##[[KeyPgGosub Gosub]]## and ##[[KeyPgReturn Return]]## will be handled at compile time. If the option is set (-1) then ##[[KeyPgGosub Gosub]]## is allowed and ##[[KeyPgReturn Return]]## is recognized as return-from-gosub only. If the option is not set (0) then ##[[KeyPgGosub Gosub]]## is not allowed and ##[[KeyPgReturn Return]]## is recognized as return-from-procedure only. This macro value can be changed at compile time. ##[[KeyPgOptiongosub Option Gosub]]## will set the option (enable gosub support) and ##[[KeyPgOptionnogosub Option Nogosub]]## will clear the option (disable gosub support). ##""__FB_OPTION_GOSUB__""## returns zero (0) if the option has not been set. Returns non-zero (-1) if the option has been set. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/fboptiongosub.bas"}}%%(freebasic) #if( __FB_OPTION_GOSUB__ <> 0 ) '' turn off gosub support option nogosub #endif %% {{fbdoc item="lang"}} - Defaults to ##-1## in the //[[CompilerOptlang -lang qb]]// dialect and ##0## in all other dialects. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgOptiongosub Option Gosub]]## - ##[[KeyPgOptionnogosub Option Noosub]]## {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}}{{fbdoc item="title" value="__FB_OPTION_PRIVATE__"}}---- Intrinsic define (macro value) set by the compiler {{fbdoc item="syntax"}}## ""__FB_OPTION_PRIVATE__"" ## {{fbdoc item="desc"}} Indicates if by default ##[[KeyPgFunction Function]]##'s and ##[[KeyPgSub Sub]]##'s have module scope or global scope when not explicitly specified with ##[[KeyPgPrivate Private]]## or ##[[KeyPgPublic Public]]##. The default scope specifier for functions and subs is set by usage of the //[[CompilerOptlang -lang]]// command line option during compilation or usage of ##[[KeyPgOptionprivate Option Private]]## in the source file. ##""__FB_OPTION_PRIVATE__""## returns zero (0) if the option has not been set. Returns non-zero (-1) if the option has been set. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/fboptionprivate.bas"}}%%(freebasic) #if( __FB_OPTION_PRIVATE__ <> 0 ) #error Option Private must not be used with this module #endif %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgOptionprivate Option Private]]## - ##[[KeyPgPrivate Private]]## - ##[[KeyPgPublic Public]]## {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}} {{fbdoc item="title" value="__FB_OUT_DLL__"}}---- Intrinsic define (macro value) set by the compiler {{fbdoc item="syntax"}}## ""__FB_OUT_DLL__"" ## {{fbdoc item="desc"}} ##""__FB_OUT_DLL__""## indicates that the specified output file type on the compiler command line at the time of compilation is a shared library. Returns non-zero (-1) if the output is a shared library. Returns zero (0) otherwise. Only one of ##""__FB_OUT_DLL__""##, ##[[KeyPgDdfboutexe __FB_OUT_EXE__]]##, ##[[KeyPgDdfboutlib __FB_OUT_LIB__]]##, or ##[[KeyPgDdfboutobj __FB_OUT_OBJ__]]## will evaluate to non-zero (-1). All others will evaluate to zero (0). {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/fboutdll.bas"}}%%(freebasic) #if __FB_OUT_DLL__ '... specific instructions when making a shared library (DLL) #else '... specific instructions when not making a shared library (DLL) #endif %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDdfboutexe __FB_OUT_EXE__]]## - ##[[KeyPgDdfboutlib __FB_OUT_LIB__]]## - ##[[KeyPgDdfboutobj __FB_OUT_OBJ__]]## - [[CompilerOptdll Compiler Option: -dll]] {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}} {{fbdoc item="title" value="__FB_OUT_EXE__"}}---- Intrinsic define (macro value) set by the compiler {{fbdoc item="syntax"}}## ""__FB_OUT_EXE__"" ## {{fbdoc item="desc"}} ##""__FB_OUT_EXE__""## indicates that the specified output file type on the compiler command line at the time of compilation is an executable. Returns non-zero (-1) if the output is an executable. Returns zero (0) otherwise. Only one of ##[[KeyPgDdfboutdll __FB_OUT_DLL__]]##, ##""__FB_OUT_EXE__""##, ##[[KeyPgDdfboutlib __FB_OUT_LIB__]]##, or ##[[KeyPgDdfboutobj __FB_OUT_OBJ__]]## will evaluate to non-zero (-1). All others will evaluate to zero (0). {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/fboutexe.bas"}}%%(freebasic) #if __FB_OUT_EXE__ '... specific instructions when making an executable #else '... specific instructions when not making an executable #endif %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDdfboutdll __FB_OUT_DLL__]]## - ##[[KeyPgDdfboutlib __FB_OUT_LIB__]]## - ##[[KeyPgDdfboutobj __FB_OUT_OBJ__]]## {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}} {{fbdoc item="title" value="__FB_OUT_LIB__"}}---- Intrinsic define (macro value) set by the compiler {{fbdoc item="syntax"}}## ""__FB_OUT_LIB__"" ## {{fbdoc item="desc"}} ##""__FB_OUT_LIB__""## indicates that the specified output file type on the compiler command line at the time of compilation is a static library. Returns non-zero (-1) if the output is a static library. Returns zero (0) otherwise. Only one of ##[[KeyPgDdfboutdll __FB_OUT_DLL__]]##, ##[[KeyPgDdfboutexe __FB_OUT_EXE__]]##, ##""__FB_OUT_LIB__""##, or ##[[KeyPgDdfboutobj __FB_OUT_OBJ__]]## will evaluate to non-zero (-1). All others will evaluate to zero (0). {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/fboutlib.bas"}}%%(freebasic) #if __FB_OUT_LIB__ '... specific instructions when making a static library #else '... specific instructions when not making a static library #endif %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDdfboutexe __FB_OUT_EXE__]]## - ##[[KeyPgDdfboutdll __FB_OUT_DLL__]]## - ##[[KeyPgDdfboutobj __FB_OUT_OBJ__]]## - [[CompilerOptlib Compiler Option: -lib]] {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:51:45 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: a80f0821ad9598f463454779129ce560 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 1181 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="__FB_OUT_OBJ__"}}---- Intrinsic define (macro value) set by the compiler {{fbdoc item="syntax"}}## ""__FB_OUT_OBJ__"" ## {{fbdoc item="desc"}} ##""__FB_OUT_OBJ__""## indicates that the specified output file type on the compiler command line at the time of compilation is an object module. Returns non-zero (-1) if the output is an object module. Returns zero (0) otherwise. Only one of ##[[KeyPgDdfboutdll __FB_OUT_DLL__]]##, ##[[KeyPgDdfboutexe __FB_OUT_EXE__]]##, ##[[KeyPgDdfboutlib __FB_OUT_LIB__]]##, or ##""__FB_OUT_OBJ__""##, will evaluate to non-zero (-1). All others will evaluate to zero (0). {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/fboutobj.bas"}}%%(freebasic) #if __FB_OUT_OBJ__ '... specific instructions when compiling to an object file only #else '... specific instructions when not compiling to an object file only #endif %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDdfboutexe __FB_OUT_EXE__]]## - ##[[KeyPgDdfboutdll __FB_OUT_DLL__]]## - ##[[KeyPgDdfboutlib __FB_OUT_LIB__]]## {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}} {{fbdoc item="title" value="__FB_SIGNATURE__"}}---- Intrinsic define (macro string) set by the compiler {{fbdoc item="syntax"}}## ""__FB_SIGNATURE__"" ## {{fbdoc item="desc"}} Substituted by a signature of the compiler where used. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/fbsignature.bas"}}%%(freebasic) PRINT __FB_SIGNATURE__ %% %% FreeBASIC v0.18.2b %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDdfbversion __FB_VERSION__]]## - ##[[KeyPgDdfbwin32 __FB_WIN32__]]## - ##[[KeyPgDdfblinux __FB_LINUX__]]## - ##[[KeyPgDdfbdos __FB_DOS__]]## {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}}{{fbdoc item="title" value="__FB_VER_MAJOR__"}}---- Intrinsic define (macro value) set by the compiler {{fbdoc item="syntax"}}## ""__FB_VER_MAJOR__"" ## {{fbdoc item="desc"}} ##""__FB_VER_MAJOR__""## will return the major version of FreeBASIC currently being used. For example, the major version is 0 for Freebasic 0.18, and will remain 0 until FreeBASIC 1.0 is released. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/fbvermajor.bas"}}%%(freebasic) Dim fbMajorVersion As Integer Dim fbMinorVersion As Integer fbMajorVersion = __FB_VER_MAJOR__ fbMinorVersion = __FB_VER_MINOR__ Print "Welcome to freebasic ";fbMajorVersion;".";fbMinorVersion %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDdFBVerMinor __FB_VER_MINOR__]]## - ##[[KeyPgDdFBVerPatch __FB_VER_PATCH__]]## {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}} {{fbdoc item="title" value="__FB_VER_MINOR__"}}---- Intrinsic define (macro value) set by the compiler {{fbdoc item="syntax"}}## ""__FB_VER_MINOR__"" ## {{fbdoc item="desc"}} ""__FB_VER_MINOR__"" will return the minor version of FreeBASIC currently being used. For Freebasic 0.15, for example, the minor version is 15. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/fbverminor.bas"}}%%(freebasic) Dim fbMajorVersion As Integer Dim fbMinorVersion As Integer fbMajorVersion = __FB_VER_MAJOR__ fbMinorVersion = __FB_VER_MINOR__ Print "Welcome to freebasic ";fbMajorVersion;".";fbMinorVersion %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDdFBVerMajor __FB_VER_MAJOR__]]## - ##[[KeyPgDdFBVerPatch __FB_VER_PATCH__]]## {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}} {{fbdoc item="title" value="__FB_VER_PATCH__"}}---- Intrinsic define (macro value) set by the compiler {{fbdoc item="syntax"}}## ""__FB_VER_PATCH__"" ## {{fbdoc item="desc"}} ""__FB_VER_PATCH__"" will return the patch/subversion/revision number the version of FreeBASIC currently being used. For FreeBASIC 0.18, for example, the are subversions 0, 1 and 2. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/fbverpatch.bas"}}%%(freebasic) Dim fbMajorVersion As Integer Dim fbMinorVersion As Integer Dim fbPatchVersion As Integer fbMajorVersion = __FB_VER_MAJOR__ fbMinorVersion = __FB_VER_MINOR__ fbPatchVersion = __FB_VER_PATCH__ Print "Welcome to FreeBASIC ";fbMajorVersion;".";fbMinorVersion;" , Revision ";fbPatchVersion %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDdFBVerMajor __FB_VER_MAJOR__]]## - ##[[KeyPgDdFBVerMinor __FB_VER_MINOR__]]## {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:51:55 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: d2093de5d105eeef4052132777350f5b Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 801 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="__FB_VERSION__"}}---- Intrinsic define (macro string) set by the compiler {{fbdoc item="syntax"}}## ""__FB_VERSION__"" ## {{fbdoc item="desc"}} Substituted by the version number of the compiler where used. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/fbversion.bas"}}%%(freebasic) #if __FB_VERSION__ < "0.18" #error Please compile with FB version 0.18 or above #endif %% This will stop the compilation if the compiler version is below 0.18 {{fbdoc item="diff"}} - Did not exist in QB {{fbdoc item="see"}} - ##[[KeyPgDdfbsignature __FB_SIGNATURE__]]## - ##[[KeyPgDdfbwin32 __FB_WIN32__]]## - ##[[KeyPgDdfblinux __FB_LINUX__]]## - ##[[KeyPgDdfbdos __FB_DOS__]]## {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}} {{fbdoc item="title" value="__FB_WIN32__"}}---- Intrinsic define set by the compiler {{fbdoc item="syntax"}}## ""__FB_WIN32__"" ## {{fbdoc item="desc"}} Define without a value created at compile time if compiling to the Win32 target. Default in Win32 hosted version, or active if the //[[CompilerOpttarget -target win32]]// command line option is used. It can be used to compile parts of the program only if the target is Win32. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/fbwin32.bas"}}%%(freebasic) #IFDEF __FB_WIN32__ ' ... instructions only for Win32 ... ' ... GetProcAddress ... #ELSE ' ... instructions not for Win32 ... #ENDIF %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDdfbdos __FB_DOS__]]## - ##[[KeyPgDdfblinux __FB_LINUX__]]## - [[CompilerOpttarget Compiler Option: -target]] {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}}{{fbdoc item="title" value="__FB_XBOX__"}}---- Intrinsic define set by the compiler {{fbdoc item="syntax"}}## ""__FB_XBOX__"" ## {{fbdoc item="desc"}} Define without a value created at compile time when the //[[CompilerOpttarget -target xbox]]// command line option is used. It can be used to compile parts of the program only if the target is Xbox. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/fbxbox.bas"}}%%(freebasic) #IFDEF __FB_XBOX__ '...instructions only for Xbox... #ELSE '...instructions not for Xbox... #ENDIF %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDdfblinux __FB_LINUX__]]## - ##[[KeyPgDdfbwin32 __FB_WIN32__]]## - [[CompilerOpttarget Compiler Option: -target]] {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}}{{fbdoc item="title" value="__FILE__"}}---- Intrinsic define (macro string) set by the compiler {{fbdoc item="syntax"}}## ""__FILE__"" ## {{fbdoc item="desc"}} Substituted with the quoted source file name where used. An example of normal use is to report wrong values in debugging. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/file.bas"}}%%(freebasic) dim a as integer if a<0 then Print "Error: a = " & a & " in " & __FILE__ & " (" & __FUNCTION__ & ") line " & __LINE__ end if %% %% Error: a = -32767 in test.bas (MAIN) line 47 %% {{fbdoc item="diff"}} - Did not exist in QB {{fbdoc item="see"}} - ##[[KeyPgDdfilenq __FILE_NQ__]]## - ##[[KeyPgDdfunction __FUNCTION__]]## - ##[[KeyPgDdline __LINE__]]## {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}} {{fbdoc item="title" value="__FILE_NQ__"}}---- Intrinsic define (macro string) set by the compiler {{fbdoc item="syntax"}}## ""__FILE_NQ__"" ## {{fbdoc item="desc"}} Substituted with the non-quoted source file name where used. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/filenq.bas"}}%%(freebasic) #print __FILE_NQ__ %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDdfile __FILE__]]## - ##[[KeyPgDdfunctionnq __FUNCTION_NQ__]]## - ##[[KeyPgDdline __LINE__]]## {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}} {{fbdoc item="title" value="__FUNCTION__"}}---- Intrinsic define (macro string) set by the compiler {{fbdoc item="syntax"}}## ""__FUNCTION__"" ## {{fbdoc item="desc"}} Substituted with the quoted name of the current function block where used. Its normal use is to report wrong values in debugging. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/function.bas"}}%%(freebasic) dim a as integer If a<0 Then Print "Error: a = " & a & " in " & __FILE__ & " (" & __FUNCTION__ & ") line " & __LINE__ end if %% %% Error: a = -32767 in test.bas (MAIN) line 47 %% {{fbdoc item="diff"}} - Did not exist in QB {{fbdoc item="see"}} - ##[[KeyPgDdfile __FILE__]]## - ##[[KeyPgDdfunctionnq __FUNCTION_NQ__]]## - ##[[KeyPgDdline __LINE__]]## {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}} {{fbdoc item="title" value="__FUNCTION_NQ__"}}---- Intrinsic define (macro string) set by the compiler {{fbdoc item="syntax"}}## ""__FUNCTION_NQ__"" ## {{fbdoc item="desc"}} Substituted with the non-quoted name of the current function block where used. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/functionnq.bas"}}%%(freebasic) sub MySub print "Address of " + __FUNCTION__ + " is "; print hex( @__FUNCTION_NQ__ ) end sub MySub %% %% Address of MYSUB is 4012D0 %% {{fbdoc item="diff"}} - Did not exist in QB {{fbdoc item="see"}} - ##[[KeyPgDdfilenq __FILE_NQ__]]## - ##[[KeyPgDdfunction __FUNCTION__]]## - ##[[KeyPgDdline __LINE__]]## {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}} {{fbdoc item="title" value="__LINE__"}}---- Intrinsic define (macro value) set by the compiler {{fbdoc item="syntax"}}## ""__LINE__"" ## {{fbdoc item="desc"}} Substituted with the current line number of the source file where used. Its normal use is to report wrong values in debugging. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/line.bas"}}%%(freebasic) dim a as integer If a < 0 Then Print "Error: a = " & a & " in " & __FILE__ & " (" & __FUNCTION__ & ") line " & __LINE__ end if %% %% Error: a = -32767 in test.bas (MAIN) line 47 %% {{fbdoc item="diff"}} - Did not exist in QB {{fbdoc item="see"}} - ##[[KeyPgDdfile __FILE__]]## - ##[[KeyPgDdfunction __FUNCTION__]]## {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}} {{fbdoc item="title" value="__PATH__"}}---- Intrinsic define (macro string) set by the compiler {{fbdoc item="syntax"}}## ""__PATH__"" ## {{fbdoc item="desc"}} Set to the quoted absolute path of the source file at the time of compilation. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/path.bas"}}%%(freebasic) ' Tell the compiler to seach the source file's ' directory for libraries #libpath __PATH__ %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDdfile __FILE__]]## {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}} {{fbdoc item="title" value="__TIME__"}}---- Intrinsic define (macro value) set by the compiler {{fbdoc item="syntax"}}## ""__TIME__"" ## {{fbdoc item="desc"}} Substitutes the compiler time in 24 hour format were used. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/defines/time.bas"}}%%(freebasic) PRINT "CompileTime: ";__TIME__ %% %% Compile Time: 11:42:57 %% {{fbdoc item="diff"}} - New to Freebasic {{fbdoc item="see"}} - ##[[KeyPgDddate __DATE__]]## {{fbdoc item="back" value="CatPgDddefines|Intrinsic Defines"}} {{fbdoc item="title" value="DEALLOCATE"}}---- Frees previously allocated memory {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Deallocate**( //pointer// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] ) ## {{fbdoc item="usage"}}## **Deallocate**( //pointer// ) ## {{fbdoc item="param"}} ##//pointer//## the address of the previously allocated buffer. {{fbdoc item="desc"}} This procedure frees memory that was previously allocated with ##[[KeyPgAllocate Allocate]]##. ##//pointer//## must be a valid pointer. After the procedure returns, ##//pointer//## will be rendered invalid (pointing to an invalid memory address), and its use will result in undefined behavior. ~&**##Deallocate##** is an alias for the C runtime library's **##free##**, so it's not guaranteed to be thread safe in all platforms. {{fbdoc item="ex"}} The following example shows how to free previously allocated memory. Note that the pointer is set to null following the deallocation: {{fbdoc item="filename" value="examples/manual/memory/deallocate.bas"}}%%(freebasic) sub DeallocateExample1() dim as integer ptr integerPtr = allocate( len( integer ) ) '' initialize pointer to '' new memory address *integerPtr = 420 '' use pointer print *integerPtr deallocate( integerPtr ) '' free memory back to system integerPtr = 0 '' and zero the pointer end sub DeallocateExample1() end 0 %% Although in this case it is unnecessary - since 1. the pointer is not a reference to another pointer, 2. no other pointers point to the deallocated memory and 3. the function immediately exits afterward - setting the pointer to null is a good habit to get into. If the function deallocated memory from a pointer that was passed in by reference, for instance, the pointer that was used in the function call will be rendered invalid, and it is up to the caller to either reassign the pointer or set it to null. Example 3 shows how to correctly handle this kind of situation, and the next example shows the effects of deallocating memory with multiple references. In the following example, a different pointer is used to free previously allocated memory. {{fbdoc item="filename" value="examples/manual/memory/deallocate2.bas"}}%%(freebasic) sub DeallocateExample2() dim as integer ptr integerPtr = allocate( len( integer ) ) '' initialize pointer to '' new memory dim as integer ptr anotherIntegerPtr = integerPtr '' initialize another pointer to '' the same memory *anotherIntegerPtr = 69 '' use other pointer print *anotherIntegerPtr deallocate( anotherIntegerPtr ) '' free memory back to system anotherIntegerPtr = 0 '' and zero other pointer '' *integerPtr = 420 '' undefined bahavior; original '' pointer is invalid end sub DeallocateExample2() end 0 %% Note that after the deallocation, //both// pointers are rendered invalid. This illustrates another one of the ways that bugs can arise when working with pointers. As a general rule, only deallocate memory previously allocated when you know that there is only one (1) pointer currently pointing at it. {{fbdoc item="filename" value="examples/manual/memory/deallocate3.bas"}}%%(freebasic) function createInteger() as integer ptr return allocate( len( integer ) ) '' return pointer to newly end function '' allocated memory sub destroyInteger( byref someIntegerPtr as integer ptr ) deallocate( someIntegerPtr ) '' free memory back to system someIntegerPtr = 0 '' null original pointer end sub sub DeallocateExample3() dim as integer ptr integerPtr = createInteger() '' initialize pointer to '' new memory address *integerPtr = 420 '' use pointer print *integerPtr destroyInteger( integerPtr ) '' pass pointer by reference assert( integerPtr = 0 ) '' pointer should now be null end sub DeallocateExample3() end 0 %% In the program above, a reference pointer in a function is set to null after deallocating the memory it points to. An [[KeyPgAssert ASSERT]] macro is used to test if the original pointer is in fact null after the function call. This example implies the correct way to pass pointers to functions that deallocate the memory they point to is by reference. {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Deallocate""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgAllocate Allocate]]## - ##[[KeyPgReallocate Reallocate]]## {{fbdoc item="back" value="CatPgMemory|Memory Functions"}}{{fbdoc item="title" value="DECLARE"}}---- Declares a module-level or member procedure {{fbdoc item="syntax"}}## **Declare** [[KeyPgSub Sub]] //name// [ //param_list// ] [ [[KeyPgModuleConstructor Constructor]] | [[KeyPgModuleDestructor Destructor]] ] **Declare** [[KeyPgFunction Function]] //name// [ //param_list// ] [[KeyPgAs As]] //return_type// **Declare** [[KeyPgOperator Operator]] //op_symbol// //param_list// [ [[KeyPgAs As]] //return_type// ] Type //T// **Declare** [[KeyPgConstructor Constructor]] [ //param_list// ] **Declare** [[KeyPgDestructor Destructor]] **Declare** [[KeyPgSub Sub]] //name// [ //param_list// ] **Declare** [[KeyPgFunction Function]] //name// [ //param_list// ] [[KeyPgAs As]] //return_type// **Declare** [[KeyPgOperator Operator]] //name// [ //param_list// ] [ [[KeyPgAs As]] //return_type// ] **Declare** [[KeyPgProperty Property]] //name// [ ( [ //param_list// ] ) ] [ [[KeyPgAs As]] //return_type// ] End Type ## {{fbdoc item="param"}} ##//param_list//## Parenthesized comma-separated list of parameters. ##//return_type//## The return type of a ##[[KeyPgFunction Function]]##, ##[[KeyPgOperator Operator]]##, or ##[[KeyPgProperty Property]]## procedure. ##//name//## The name or symbol of the routine. ##//op_symbol//## The name or symbol of an operator. ##//T//## The name of a new user-defined type. {{fbdoc item="desc"}} The ##**Declare**## statement declares a ##[[KeyPgSub Sub]]##, ##[[KeyPgFunction Function]]##, ##[[KeyPgOperator Operator]]##, ##[[KeyPgConstructor Constructor]]##, or ##[[KeyPgDestructor Destructor]]##. We will refer to one of these as a routine. The routine can be referred to in code without seeing its definition, although it must be defined somewhere. Essentially, the ##**Declare**## statement introduces a routine, and states that its definition is elsewhere. For example, a function can be declared at the top of a source module, called, then defined at the bottom of the source file, as shown below the example. A routine's declaration is almost identical to the first line of its definition, except the declaration is preceded by the ##**Declare**## keyword and has no body. Also, attributes such as [[KeyPgExport Export]] are left off the declaration. FreeBASIC, as QB, does not require the declaration of the functions unless they are defined in a different source file or in the same file past the point where they are called. This is no longer true for routines declared inside a [[KeyPgType Type]] body, which must **always** be declared first in the [[KeyPgType Type]]'s body before use. If you do not declare [[KeyPgType Type]] routines you will receive an error. As every file using a function must have its declaration, declarations are usually kept in one or more //include files// to allow usage of the function by any module that needs it using the ##[[KeyPgInclude #include]]## statement. {{fbdoc item="ex"}} Module-level Function: {{fbdoc item="filename" value="examples/manual/procs/declare.bas"}}%%(freebasic) '' declare the function sum which takes two integers and returns an integer declare function sum( as integer, as integer ) as integer print "the sum of 420 and 69 is: " & sum( 420, 69 ) '' call the function sum '' define the function sum which takes two integers and returns an integer function sum( a as integer, b as integer ) as integer return a + b end function %% Type-level Sub: {{fbdoc item="filename" value="examples/manual/procs/declare2.bas"}}%%(freebasic) type my_type my_data as integer declare sub increment_data( ) end type sub my_type.increment_data( ) my_data += 1 end sub dim as my_type an_instance an_instance.my_data = 68 an_instance.increment_data( ) Print an_instance.my_data %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang fb]]// dialect, ##**Byval**## is the default parameter passing convention. - In the //[[CompilerOptlang -lang qb]]// and //[[CompilerOptlang -lang deprecated]]// dialects, ##**Byref**## is the default parameter passing convention. - Type-level ##[[KeyPgSub Sub]]##/##[[KeyPgFunction Function]]##/##[[KeyPgOperator Operator]]##/##[[KeyPgConstructor Constructor]]##/##[[KeyPgDestructor Destructor]]##'s are only allowed in //[[CompilerOptlang -lang fb]]// {{fbdoc item="diff"}} - In FreeBASIC, the parameter names are optional. {{fbdoc item="see"}} - ##[[KeyPgSub Sub]]## - ##[[KeyPgFunction Function]]## - ##[[KeyPgOperator Operator]]## - ##[[KeyPgProperty Property]]## - ##[[KeyPgConstructor Constructor]]## - ##[[KeyPgDestructor Destructor]]## - ##[[KeyPgModuleConstructor Constructor (module)]]## - ##[[KeyPgModuleDestructor Destructor (module)]]## - ##[[KeyPgType Type]]## - ##[[KeyPgDim Dim]]## - ##[[KeyPgAlias Alias]]## {{fbdoc item="back" value="CatPgProcedures|Procedures"}} {{fbdoc item="title" value="DEFBYTE"}}---- Specifies a default data type for a range of variable names {{fbdoc item="syntax"}}## **Defbyte** //start_letter//[**-**//end_letter// ][, ...] ## {{fbdoc item="param"}} ##//start_letter//## the first letter in the range ##//end_letter//## the last letter in the range {{fbdoc item="desc"}} ##**Defbyte**## specifies that variables and arrays which aren't declared with a data type - or not declared at all - are implicitly declared of type ##[[KeyPgByte Byte]]## if the first letter of their names matches a certain letter or lies within an inclusive range of letters. {{fbdoc item="ex"}} This will make ##bNumber## a ##[[KeyPgByte Byte]]## number since it's first letter starts with b: {{fbdoc item="filename" value="examples/manual/switches/defbyte.bas"}}%%(freebasic) '' Compile with -lang fblite or qb defbyte b dim bNumber %% {{fbdoc item="lang"}} - Available in the //[[CompilerOptlang -lang fblite]]// dialect. - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Defbyte""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgByte Byte]]## - ##[[KeyPgDefint Defint]]## - ##[[KeyPgDefubyte Defubyte]]## - ##[[KeyPgDim Dim]]## {{fbdoc item="back" value="CatPgCompilerSwitches|Compiler Switches"}}{{fbdoc item="title" value="DEFDBL"}}---- Specifies a default data type for a range of variable names {{fbdoc item="syntax"}}## **Defdbl** //start_letter//[**-**//end_letter// ][, ...] ## {{fbdoc item="param"}} ##//start_letter//## the first letter in the range ##//end_letter//## the last letter in the range {{fbdoc item="desc"}} ##**Defdbl**## specifies that variables and arrays which aren't declared with a data type - or not declared at all - are implicitly declared of type ##[[KeyPgDouble Double]]## if the first letter of their names matches a certain letter or lies within an inclusive range of letters. {{fbdoc item="ex"}} This will make ##aNum## a ##[[KeyPgDouble Double]]##-precision decimal number since it is in the range of a-d: {{fbdoc item="filename" value="examples/manual/switches/defdbl.bas"}}%%(freebasic) '' Compile with -lang fblite or qb defdbl a-d dim aNum 'implicit: As Double print len(aNum) ' Prints 8, the number of bytes in a double. %% {{fbdoc item="lang"}} - Only available in the //[[CompilerOptlang -lang qb]]// and //[[CompilerOptlang -lang fblite]]// dialects. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgDefint Defint]]## - ##[[KeyPgDefsng Defsng]]## - ##[[KeyPgDim Dim]]## - ##[[KeyPgDouble Double]]## {{fbdoc item="back" value="CatPgCompilerSwitches|Compiler Switches"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:52:09 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 17803b2c3085052c2c543c7fda6ae933 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 1466 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="DEFINED"}}---- Preprocessor function to test if a symbol has been defined {{fbdoc item="syntax"}}## **defined** (//symbol_name//) ## {{fbdoc item="param"}} ##//symbol_name//## Name of the symbol to test {{fbdoc item="ret"}} Returns non-zero (-1) if the symbol has been defined, otherwise returns zero (0). {{fbdoc item="desc"}} Given the symbol name, the **defined()** preprocessor function returns true if the symbol has been defined - or false if the symbol is unknown of. This is used mainly with ##[[KeyPgPpif #if]]##. Similar to ##[[KeyPgPpifdef #ifdef]]## except it allows more than one check to occur because of its flexibility. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/prepro/defined.bas"}}%%(freebasic) 'e.g. - which symbols are defined out of a, b, c, and d ? const a = 300 #define b 12 dim c as single #if defined(a) print "a is defined" #endif #if defined(b) print "b is defined" #endif #if defined(c) print "c is defined" #endif #if defined(d) print "d is defined" #endif %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgPpdefine #define]]## - ##[[KeyPgPpmacro #macro]]## - ##[[KeyPgPpif #if]]## - ##[[KeyPgPpelse #else]]## - ##[[KeyPgPpelseif #elseif]]## - ##[[KeyPgPpendif #endif]]## - ##[[KeyPgPpifdef #ifdef]]## - ##[[KeyPgPpifndef #ifndef]]## - ##[[KeyPgPpundef #undef]]## {{fbdoc item="back" value="CatPgPreProcess|Preprocessor"}} {{fbdoc item="title" value="DEFINT"}}---- Specifies a default data type for a range of variable names {{fbdoc item="syntax"}}## **Defint** //start_letter//[**-**//end_letter// ][, ...] ## {{fbdoc item="param"}} ##//start_letter//## the first letter in the range ##//end_letter//## the last letter in the range {{fbdoc item="desc"}} ##**Defint**## specifies that variables and arrays which aren't declared with a data type - or not declared at all - are implicitly declared of type ##[[KeyPgInteger Integer]]## if the first letter of their names matches a certain letter or lies within an inclusive range of letters. {{fbdoc item="ex"}} This will make ##iNumber## an ##[[KeyPgInteger Integer]]## number since it's first letter starts with i. {{fbdoc item="filename" value="examples/manual/switches/defint.bas"}}%%(freebasic) '' Compile with -lang fblite or qb defint i dim iNumber %% {{fbdoc item="lang"}} - Only available in the //[[CompilerOptlang -lang qb]]// and //[[CompilerOptlang -lang fblite]]// dialects. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgDefbyte Defbyte]]## - ##[[KeyPgDefdbl Defdbl]]## - ##[[KeyPgDeflng Deflng]]## - ##[[KeyPgDeflongint Deflongint]]## - ##[[KeyPgDefshort Defshort]]## - ##[[KeyPgDefsng Defsng]]## - ##[[KeyPgDefstr Defstr]]## - ##[[KeyPgInteger Integer]]## {{fbdoc item="back" value="CatPgCompilerSwitches|Compiler Switches"}}{{fbdoc item="title" value="DEFLNG"}}---- Specifies a default data type for a range of variable names {{fbdoc item="syntax"}}## **Deflng** //start_letter//[**-**//end_letter// ][, ...] ## {{fbdoc item="param"}} ##//start_letter//## the first letter in the range ##//end_letter//## the last letter in the range {{fbdoc item="desc"}} ##**Deflng**## specifies that variables and arrays which aren't declared with a data type - or not declared at all - are implicitly declared of type ##[[KeyPgLong Long]]## if the first letter of their names matches a certain letter or lies within an inclusive range of letters. {{fbdoc item="ex"}} This will make ##lNumber## a ##[[KeyPgLong Long]]## integer number since it starts with l. {{fbdoc item="filename" value="examples/manual/switches/deflng.bas"}}%%(freebasic) '' Compile with -lang fblite or qb deflng l dim lNumber ' implicit: As Long print len(lNumber) ' Displays 4, the number of bytes in a long. %% {{fbdoc item="lang"}} - Only available in the //[[CompilerOptlang -lang qb]]// and //[[CompilerOptlang -lang fblite]]// dialects. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgDefint Defint]]## - ##[[KeyPgDefulongint Defulongint]]## - ##[[KeyPgDim Dim]]## - ##[[KeyPgLongint Longint]]## {{fbdoc item="back" value="CatPgCompilerSwitches|Compiler Switches"}}{{fbdoc item="title" value="DEFLONGINT"}}---- Specifies a default data type for a range of variable names {{fbdoc item="syntax"}}## **Deflongint** //start_letter//[**-**//end_letter// ][, ...] ## {{fbdoc item="param"}} ##//start_letter//## the first letter in the range ##//end_letter//## the last letter in the range {{fbdoc item="desc"}} ##**Deflongint**## specifies that variables and arrays which aren't declared with a data type - or not declared at all - are implicitly declared of type ##[[KeyPgLongint Longint]]## if the first letter of their names matches a certain letter or lies within an inclusive range of letters. {{fbdoc item="ex"}} This will make ##lNumber## a ##[[KeyPgLongint Longint]]## number since it's first letter starts with l. {{fbdoc item="filename" value="examples/manual/switches/deflongint.bas"}}%%(freebasic) '' Compile with -lang fblite deflongint l dim lNumber %% {{fbdoc item="lang"}} - Available in the //[[CompilerOptlang -lang fblite]]// dialect. - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Deflongint""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDefint Defint]]## - ##[[KeyPgDefulongint Defulongint]]## - ##[[KeyPgDim Dim]]## - ##[[KeyPgLongint Longint]]## {{fbdoc item="back" value="CatPgCompilerSwitches|Compiler Switches"}}{{fbdoc item="title" value="DEFSHORT"}}---- Specifies a default data type for a range of variable names {{fbdoc item="syntax"}}## **Defshort** //start_letter//[**-**//end_letter// ][, ...] ## {{fbdoc item="param"}} ##//start_letter//## the first letter in the range ##//end_letter//## the last letter in the range {{fbdoc item="desc"}} ##**Defshort**## specifies that variables and arrays which aren't declared with a data type - or not declared at all - are implicitly declared of type ##[[KeyPgShort Short]]## if the first letter of their names matches a certain letter or lies within an inclusive range of letters. {{fbdoc item="ex"}} This will make ##sNumber## a ##[[KeyPgShort Short]]## number since it's first letter starts with s. {{fbdoc item="filename" value="examples/manual/switches/defshort.bas"}}%%(freebasic) '' Compile with -lang fblite or qb defshort s dim sNumber %% {{fbdoc item="lang"}} - Available in the //[[CompilerOptlang -lang fblite]]// dialect. - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Defshort""**##. {{fbdoc item="diff"}} - New to FreeBASIC - In QBasic, to make variables default to a 2 byte integer, DEFINT is used. {{fbdoc item="see"}} - ##[[KeyPgDefint Defint]]## - ##[[KeyPgDefushort Defushort]]## - ##[[KeyPgDim Dim]]## - ##[[KeyPgInteger Integer]]## - ##[[KeyPgShort Short]]## {{fbdoc item="back" value="CatPgCompilerSwitches|Compiler Switches"}}{{fbdoc item="title" value="DEFSNG"}}---- Specifies a default data type for a range of variable names {{fbdoc item="syntax"}}## **Defsng** //start_letter//[**-**//end_letter// ][, ...] ## {{fbdoc item="param"}} ##//start_letter//## the first letter in the range ##//end_letter//## the last letter in the range {{fbdoc item="desc"}} ##**Defsng**## specifies that variables and arrays which aren't declared with a data type - or not declared at all - are implicitly declared of type ##[[KeyPgSingle Single]]## if the first letter of their names matches a certain letter or lies within an inclusive range of letters. {{fbdoc item="ex"}} This will make ##sNumber## and ##yNumber## a ##[[KeyPgSingle Single]]##-precision decimal number since it is in the range of s-z. {{fbdoc item="filename" value="examples/manual/switches/defsng.bas"}}%%(freebasic) '' Compile with -lang fblite or qb defsng s-z dim sNumber, yNumber %% {{fbdoc item="lang"}} - Only available in the //[[CompilerOptlang -lang qb]]// and //[[CompilerOptlang -lang fblite]]// dialects. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgDefint Defint]]## - ##[[KeyPgDefdbl Defdbl]]## - ##[[KeyPgSingle Single]]## {{fbdoc item="back" value="CatPgCompilerSwitches|Compiler Switches"}}{{fbdoc item="title" value="DEFSTR"}}---- Specifies a default data type for a range of variable names {{fbdoc item="syntax"}}## **Defstr** //start_letter//[**-**//end_letter// ][, ...] ## {{fbdoc item="param"}} ##//start_letter//## the first letter in the range ##//end_letter//## the last letter in the range {{fbdoc item="desc"}} ##**Defstr**## specifies that variables and arrays which aren't declared with a data type - or not declared at all - are implicitly declared of type ##[[KeyPgString String]]## if the first letter of their names matches a certain letter or lies within an inclusive range of letters. {{fbdoc item="ex"}} This will make ##sMessage## a ##[[KeyPgString String]]## since it starts with s. {{fbdoc item="filename" value="examples/manual/switches/defstr.bas"}}%%(freebasic) '' Compile with -lang fblite or qb defstr s dim sMessage %% {{fbdoc item="lang"}} - Only available in the //[[CompilerOptlang -lang qb]]// and //[[CompilerOptlang -lang fblite]]// dialects. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgDefint Defint]]## - ##[[KeyPgDefsng Defsng]]## - ##[[KeyPgDeflng Deflng]]## - ##[[KeyPgDefdbl Defdbl]]## - ##[[KeyPgDim Dim]]## - ##[[KeyPgString String]]## {{fbdoc item="back" value="CatPgCompilerSwitches|Compiler Switches"}}{{fbdoc item="title" value="DEFUBYTE"}}---- Specifies a default data type for a range of variable names {{fbdoc item="syntax"}}## **Defubyte** //start_letter//[**-**//end_letter// ][, ...] ## {{fbdoc item="param"}} ##//start_letter//## the first letter in the range ##//end_letter//## the last letter in the range {{fbdoc item="desc"}} ##**Defubyte**## specifies that variables and arrays which aren't declared with a data type - or not declared at all - are implicitly declared of type ##[[KeyPgUbyte Ubyte]]## if the first letter of their names matches a certain letter or lies within an inclusive range of letters. {{fbdoc item="ex"}} This will make ##uNumber## a ##[[KeyPgUbyte Ubyte]]## number since it's first letter starts with u. {{fbdoc item="filename" value="examples/manual/switches/defubyte.bas"}}%%(freebasic) '' Compile with -lang fblite defubyte u dim uNumber %% {{fbdoc item="lang"}} - Available in the //[[CompilerOptlang -lang fblite]]// dialect. - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Defubyte""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDefbyte Defbyte]]## - ##[[KeyPgDefint Defint]]## - ##[[KeyPgDim Dim]]## - ##[[KeyPgUbyte Ubyte]]## {{fbdoc item="back" value="CatPgCompilerSwitches|Compiler Switches"}}{{fbdoc item="title" value="DEFUINT"}}---- Specifies a default data type for a range of variable names {{fbdoc item="syntax"}}## **Defuint** //start_letter//[**-**//end_letter// ][, ...] ## {{fbdoc item="param"}} ##//start_letter//## the first letter in the range ##//end_letter//## the last letter in the range {{fbdoc item="desc"}} ##**Defuint**## specifies that variables and arrays which aren't declared with a data type - or not declared at all - are implicitly declared of type ##[[KeyPgUinteger Uinteger]]## if the first letter of their names matches a certain letter or lies within an inclusive range of letters. {{fbdoc item="ex"}} This will make ##uNumber## a ##[[KeyPgUinteger Uinteger]]## number since it's first letter starts with u. {{fbdoc item="filename" value="examples/manual/switches/defuint.bas"}}%%(freebasic) '' Compile with -lang fblite defint u dim uNumber %% {{fbdoc item="lang"}} - Available in the //[[CompilerOptlang -lang fblite]]// dialect. - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Defuint""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDefint Defint]]## - ##[[KeyPgDim Dim]]## - ##[[KeyPgUinteger Uinteger]]## {{fbdoc item="back" value="CatPgCompilerSwitches|Compiler Switches"}}{{fbdoc item="title" value="DEFULONGINT"}}---- Specifies a default data type for a range of variable names {{fbdoc item="syntax"}}## **Defulongint** //start_letter//[**-**//end_letter// ][, ...] ## {{fbdoc item="param"}} ##//start_letter//## the first letter in the range ##//end_letter//## the last letter in the range {{fbdoc item="desc"}} ##**Defulongint**## specifies that variables and arrays which aren't declared with a data type - or not declared at all - are implicitly declared of type ##[[KeyPgUlongint Ulongint]]## if the first letter of their names matches a certain letter or lies within an inclusive range of letters. {{fbdoc item="ex"}} This will make ##lNumber## a ##[[KeyPgUlongint Ulongint]]## number since it's first letter starts with l. {{fbdoc item="filename" value="examples/manual/switches/defulongint.bas"}}%%(freebasic) '' Compile with -lang fblite defulongint l dim lNumber %% {{fbdoc item="lang"}} - Available in the //[[CompilerOptlang -lang fblite]]// dialect. - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Defulongint""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDefint Defint]]## - ##[[KeyPgDeflongint Deflongint]]## - ##[[KeyPgDim Dim]]## - ##[[KeyPgUlongint Ulongint]]## {{fbdoc item="back" value="CatPgCompilerSwitches|Compiler Switches"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:52:20 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 88624175e11fd196b4b49f7beb940696 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 1362 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="DEFUSHORT"}}---- Specifies a default data type for a range of variable names {{fbdoc item="syntax"}}## **Defushort** //start_letter//[**-**//end_letter// ][, ...] ## {{fbdoc item="param"}} ##//start_letter//## the first letter in the range ##//end_letter//## the last letter in the range {{fbdoc item="desc"}} ##**Defushort**## specifies that variables and arrays which aren't declared with a data type - or not declared at all - are implicitly declared of type ##[[KeyPgUshort Ushort]]## if the first letter of their names matches a certain letter or lies within an inclusive range of letters. {{fbdoc item="ex"}} This will make ##uNumber## a ##[[KeyPgUshort Ushort]]## number since it's first letter starts with u. {{fbdoc item="filename" value="examples/manual/switches/defushort.bas"}}%%(freebasic) '' Compile with -lang fblite defushort u dim uNumber %% {{fbdoc item="lang"}} - Available in the //[[CompilerOptlang -lang fblite]]// dialect. - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Defushort""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDefint Defint]]## - ##[[KeyPgDefint Defshort]]## - ##[[KeyPgDim Dim]]## - ##[[KeyPgUshort Ushort]]## {{fbdoc item="back" value="CatPgCompilerSwitches|Compiler Switches"}} {{fbdoc item="title" value="DESTRUCTOR"}}---- Called automatically when a class or user defined type goes out of scope or is destroyed {{fbdoc item="syntax"}}## [[KeyPgType Type]] //typename// //field declarations// [[KeyPgDeclare Declare]] **Destructor** ( ) End Type **Destructor** //typename// ( ) //statements// **End Destructor** ## {{fbdoc item="param"}} ##//typename//## name of the ##[[KeyPgType Type]]## of ##[[KeyPgClass Class]]## {{fbdoc item="desc"}} The destructor method is called when a user defined ##[[KeyPgType Type]]## or ##[[KeyPgClass Class]]## variable goes out of scope or is destroyed explicitly with the ##[[KeyPgOpDelete Delete]]## operator. The ##**Destructor**## method is passed a hidden ##[[KeyPgThis this]]## parameter having the same type as ##//typename//##. The destructor in a type is called before the destructors on any of its fields. Therefore, all fields are accessible with the hidden ##[[KeyPgThis this]]## parameter in the destructor body. Only one destructor may be declared and defined per type. Since the ##[[KeyPgEnd End]]## statement does not close any scope, object destructors will not automatically be called if the ##[[KeyPgEnd End]]## statement is used to terminate the program. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/udt/destructor.bas"}}%%(freebasic) type T value as zstring * 32 declare constructor ( init_value as string ) declare destructor () end type constructor T ( init_value as string ) value = init_value print "Creating: "; value end constructor destructor T () print "Destroying: "; value end destructor sub MySub dim x as T = ("A.x") end sub dim x as T = ("main.x") scope dim x as T = ("main.scope.x") end scope MySub %% Output: %% Creating: main.x Creating: main.scope.x Destroying: main.scope.x Creating: A.x Destroying: A.x Destroying: main.x %% {{fbdoc item="lang"}} - Object-related features are supported only in the //[[CompilerOptlang -lang fb]]// dialect. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgClass Class]]## - ##[[KeyPgConstructor Constructor]]## - ##[[KeyPgOpDelete Delete]]## - ##[[KeyPgModuleDestructor Destructor (Module)]]## - ##[[KeyPgType Type]]## {{fbdoc item="back" value="CatPgUserDefTypes|User Defined Types"}}{{fbdoc item="title" value="DIM"}}---- Declares a variable {{fbdoc item="syntax"}} Declaring a Single Variable: ##**Dim** [[[KeyPgShared Shared]]] //symbolname// [As [[DataType DataType]]] [, ...]## ##**Dim** [[[KeyPgShared Shared]]] As [[DataType DataType]] //symbolname// [, ...]## Declaring Arrays: ##**Dim** [[[KeyPgShared Shared]]] //symbolname// ( [//lbound// To] //ubound// [, ...] ) [As [[DataType DataType]]] [,...]## ##**Dim** [[[KeyPgShared Shared]]] As [[DataType DataType]] //symbolname// ( [//lbound// To] //ubound// [, ...] ) [,...]## Initializing Values: ##**Dim** //scalar_symbol// As [[DataType DataType]]] = //expression// | [[KeyPgAny Any]]## ##**Dim** //array_symbol// ([//lbound// To] //ubound//) [AS [[DataType DataType]]] => { //expression// [, ...] } | [[KeyPgAny Any]]## ##**Dim** //udt_symbol// As [[DataType DataType]] = ( //expression// [, ...] ) | [[KeyPgAny Any]]## {{fbdoc item="desc"}} Declares a variable by name and reserves memory to accommodate it. Variables must be declared before they can be used in the //[[CompilerOptlang -lang fb]]// dialect or when using ##[[KeyPgOptionexplicit Option Explicit]]## in the other dialects. Only in the //[[CompilerOptlang -lang qb]]// and //[[CompilerOptlang -lang fblite]]// dialects may variables be used without first declaring them. Variables that are used without first declaring them are called implicit variables. ##**Dim**## can be used to declare and assign variables of any of the supported data types, user defined types, or enumerations. Depending on where and how a variable or array is declared can change how it is allocated in memory. See //[[ProPgStorageClasses Storage Classes]]//. {{fbdoc item="section" value="Explicit Variables with Explicit Data Types"}} In the default dialect //[[CompilerOptlang -lang fb]]//, each variable must be explicitly declared with a desired data type. Type suffixes are not allowed. More than one variable may be declared in a single ##**Dim**## statement by separating each variable declaration with a comma. {{fbdoc item="filename" value="examples/manual/check/KeyPgDim_1.bas"}}%%(freebasic) '' Variable declaration examples '' One variable per DIM statement dim text as string dim x as double '' More than one variable declared, different data types dim k as single, factor as double, s as string '' More than one variable declared, all same data types dim as integer mx, my, mz ,mb '' Variable having an initializer dim px as double ptr = @x %% {{fbdoc item="section" value="Explicit Variables with Implicit Data Types"}} In the //[[CompilerOptlang -lang qb]]// and //[[CompilerOptlang -lang fblite]]// dialects, even if the variable is declared explicitly, it will be given a default data type if the data type is not explicitly given either by name or by type suffix. The default data type is ##[[KeyPgSingle Single]]## in the //[[CompilerOptlang -lang qb]]// dialect and ##[[KeyPgInteger Integer]]## in the //[[CompilerOptlang -lang fblite]]// dialect. The default data type can be changed throughout a source listing by use of the ##**Def""###""**## statements. (for example, ##[[KeyPgDefint DefInt]]##, ##[[KeyPgDefstr DefStr]]##, ##[[KeyPgDefsng DefSng]]##) {{fbdoc item="filename" value="examples/manual/check/KeyPgDim_2.bas"}}%%(freebasic) '' Compile with -lang qb '' All variables beginning with A through N default to the INTEGER data type '' All other variables will default to the SINGLE data type DEFINT I-N '' I and J are INTEGERs '' X and Y are SINGLEs '' T$ is STRING '' D is DOUBLE DIM I, J, X, Y, T$, D AS DOUBLE %% {{fbdoc item="section" value="Arrays"}} As with most BASIC dialects, FreeBASIC supports arrays with indexes ranging from a lower bound to an upper bound. In the syntaxes shown, ##//lbound//## refers to the lower bound, or the smallest index. And ##//Ubound//## refers to the upper bound, or the largest index. If a lower bound is not specified, it is assumed to be zero by default, unless ##[[KeyPgOptionbase Option Base]]## is used. {{fbdoc item="filename" value="examples/manual/check/KeyPgDim_3.bas"}}%%(freebasic) Const upperbound = 10 '' Declare an array with indexes ranging from 0 to upperbound, '' for a total of (upperbound + 1) indexes. Dim array(upperbound) As Single %% Multidimensional arrays can be declared as well. and are stored in row-major order: values with the same last index are contiguous. (This is different from QB's default). The maximum number of dimensions of a multidimensional array is 8. {{fbdoc item="filename" value="examples/manual/check/KeyPgDim_4.bas"}}%%(freebasic) '' declare a three-dimensional array of single '' precision floating-point numbers. Dim array(1 To 2, 6, 3 To 5) As Single '' The first dimension of the declared array '' has indices from 1 to 2, the second, 0 to 6, '' and the third, 3 to 5. %% For more information on arrays see [[ProPgArrays Arrays Overview]]. If the values used with ##**Dim**## to declare the dimensions of an array are all constants, the array will be created ##[[KeyPgOptionstatic Static]]## (unless ##[[KeyPgOptiondynamic Option Dynamic]]## is specified), while using one or more variables to declare the dimensions of an array makes it variable length, even if ##[[KeyPgOptionstatic Option Static]]## is in effect. Arrays can be declared as variable length in several ways: Using ##**Dim**## with an empty set of indexes (##**Dim** x()##), using ##**Dim**## with indexes that are variables or using the keyword ##[[KeyPgRedim Redim]]##, or declaring it past the metacommand ##[[KeyPgMetaDynamic $Dynamic]]##. Variable length arrays can't use initializers. Arrays declared with ##**Dim**## having constant indexes and not preceeded by ##[[KeyPgOptiondynamic Option Dynamic]]## are fixed length (not resizable at runtime) and can use initializers. See also //[[ProPgFixLenArrays Fixed-Length Arrays]]// and //[[ProPgVarLenArrays Variable-Length Arrays]]//. {{fbdoc item="section" value="Initializers"}} Arrays, variables, strings, and user defined types (UDTs) are initialized to zero or null strings by default when they are created. To avoid the overhead of initializing the variables the ##**Any**## initializer can be used with ##**Dim**## to tell the compiler to only reserve the place for the variable in memory but don't initialize it, so the variable will contain garbage. In this case the programmer should not make assumptions about the initial values. Fixed-length arrays, variables, zstrings and UDTs may be given a value at the time of their declaration by following the variable declaration with an initializer. Note the difference between initializing different types. Arrays, variables and UDTs are initialized as they would in a normal assignment, using an equal ( ##=## ) sign. The ##=>## sign can be used with fixed length strings to avoid the declaration resembling an expression. Array values are given in comma-delimited values enclosed by curly brackets, and UDT values are given in comma delimited values enclosed by parenthesis. These methods of initializing variables can be nested within one another for complex assignments. Nesting allows for arrays of any dimension to be initialized. {{fbdoc item="filename" value="examples/manual/check/KeyPgDim_5.bas"}}%%(freebasic) '' Declare an array of 2 by 5 elements '' and initialize Dim array(1 To 2, 1 To 5) As Integer => {{1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}} %% {{fbdoc item="filename" value="examples/manual/check/KeyPgDim_6.bas"}}%%(freebasic) '' declare a simple UDT Type mytype var1 As Double var2 As Integer End Type '' declare a 3 element array and initialize the first '' 2 mytype elements Dim myvar(0 To 2) As mytype => {(1.0, 1), (2.0, 2)} %% For module-level, fixed-length, or global variables, initialized values must be constant expressions. FreeBASIC will report a compile-time error if otherwise. Note: Initializing UDT's with strings is not supported at this time. {{fbdoc item="section" value="Explicit Variables with Type Suffixes"}} In the //[[CompilerOptlang -lang qb]]// and //[[CompilerOptlang -lang fblite]]// dialects, the data type of a variable may be indicated with a type suffix ( $ % # ! & ). {{fbdoc item="filename" value="examples/manual/check/KeyPgDim_7.bas"}}%%(freebasic) '' Compile with -lang qb or fblite '' A string variable using the $ type suffix Dim strVariable$ '' An integer variable using the % type suffix Dim intVariable% '' A long variable using the & type suffix Dim lngVariable& '' A single precision floating point variable using the ! type suffix Dim sngVariable! '' A double precision floating point variable using the # type suffix Dim dblVariable# %% {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/variable/dim.bas"}}%%(freebasic) Dim a As Byte Dim b As Short Dim c As Integer Dim d As LongInt Dim au As UByte Dim bu As UShort Dim cu As UInteger Dim du As ULongInt Dim e As Single Dim f As Double Dim g As Integer Ptr Dim h As Byte Ptr Dim s1 As String * 10 '' fixed length string Dim s2 As String '' variable length string Dim s3 As ZString Ptr '' zstring s1 = "Hello World!" s2 = "Hello World from FreeBasic!" s3 = Allocate( Len( s2 ) + 1 ) *s3 = s2 Print "Byte: "; Len(a) Print "Short: "; Len(b) Print "Integer: "; Len(c) Print "Longint: "; Len(d) Print "UByte: "; Len(au) Print "UShort: "; Len(bu) Print "UInteger: "; Len(cu) Print "ULongint: "; Len(du) Print "Single: "; Len(e) Print "Double: "; Len(f) Print "Integer Pointer: "; Len(g) Print "Byte Pointer: "; Len(h) Print "Fixed String: "; Len(s1) Print "Variable String: "; Len(s2) Print "ZString: "; Len(*s3) Deallocate(s3) %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// and //[[CompilerOptlang -lang fblite]]// dialects, variables have procedure scope if the variable is defined inside a procedure, and for the entire module if the variable is defined with ##**Dim Shared**##. - In the //[[CompilerOptlang -lang fb]]// and //[[CompilerOptlang -lang deprecated]]// dialects, variables defined inside compound block statements (##[[KeyPgFornext For..Next]]##, ##[[KeyPgWhilewend While..Wend]]##, ##[[KeyPgDoloop Do..Loop]]##, ##[[KeyPgScope Scope..End Scope]]##) have local [[ProPgVariableScope scopes]], and are visible only within these blocks. - In the //[[CompilerOptlang -lang fb]]// dialect, ##**Option**## statements (e.g. ##[[KeyPgOptionbase Option Base]]##, ##[[KeyPgOptiondynamic Option Dynamic]]##), metacommands(e.g. ##[[KeyPgMetaStatic $Static]]##) and ##**Def""###""**## statements (e.g. ##[[KeyPgDefint DefInt]]##) are not allowed. {{fbdoc item="diff"}} - Variable Initializers are new to FreeBASIC - The alternate syntax ##Dim As DataType //symbolname//, [...]## is new to FreeBASIC - Multidimensional arrays are stored in row-major order in FreeBASIC, they were stored in column-major order in QB by default. Row major order: values with the same last index are contiguous. Column-major order: values with the same first index are contiguous. - Variable length arrays up to 2GB in size are possible in FreeBASIC. In QB, $Static arrays were limited to 64KB and to the DOS memory available (several 100 KB at best) if made $Dynamic and ///AH// was used. {{fbdoc item="see"}} - ##[[KeyPgCommon Common]]## - ##[[KeyPgErase Erase]]## - ##[[KeyPgExtern Extern]]## - ##[[KeyPgLbound LBound]]## - ##[[KeyPgRedim Redim]]## - ##[[KeyPgPreserve Preserve]]## - ##[[KeyPgShared Shared]]## - ##[[KeyPgStatic Static]]## - ##[[KeyPgUbound UBound]]## - ##[[KeyPgVar Var]]## {{fbdoc item="back" value="CatPgVariables|Variable Declarations"}}{{fbdoc item="title" value="DIR"}}---- Returns a file or directory {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Dir** ( [[KeyPgByref byref]] //file_spec// [[KeyPgAs as]] [[KeyPgString string]] = "####", [[KeyPgByval byval]] //attrib_mask// [[KeyPgAs as]] [[KeyPgInteger integer]] = &h21, [[KeyPgByval byval]] //out_attrib// [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgPtr ptr]] = 0 ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Dir** ( [[KeyPgByval byval]] //out_attrib// [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgPtr ptr]] = 0 ) [[KeyPgAs as]] [[KeyPgString string]] ## {{fbdoc item="usage"}}## //result// = **Dir**( //file_spec//, //attrib_mask//, //out_attrib// ) ##//or//## //result// = **Dir**( //out_attrib// ) ## {{fbdoc item="param"}} ##//file_spec//## Optional ##[[KeyPgString string]]## argument specifying the name of the files or directories to be matched. ##//attrib_mask//## Optional ##[[KeyPgInteger integer]]## mask specifying the file attributes of the files or directories to be matched. ##//out_attrib//## Optional ##[[KeyPgInteger integer]] [[KeyPgPtr ptr]]## which is set to the attributes of the file or directory returned. {{fbdoc item="ret"}} A ##[[KeyPgString string]]## containing the name of the file or directory returned. {{fbdoc item="desc"}} Returns files and/or directories that match //file_spec// and //attrib_mask//. The //file_spec// parameter can include wildcards ("*" and/or "?") and paths. The //attrib_mask// optional parameter is a combination of the following flags (each file with any of them set will be matched): {{table columns="3" cellpadding="1" cells="Value;Description;Constant;&h01;Read Only;fbReadOnly;&h02;Hidden;fbHidden;&h04;System;fbSystem;&h10;Directory;fbDirectory;&h20;Archive;fbArchive;&h21;Normal;fbNormal"}} Constants can be used by including ##"dir.bi"## By default //attrib_mask// is set to &h21 (ie.: search for files with possibly the archive or read-only flags set). The value of 55 (63 usually works also, but 55 is safer) returns all files and directories, incl. "." and "..", but no Volume, the value 8 returns the Volume, even if current directory is not the main directory. The //out_attrib// optional parameter if passed will be loaded with the attributes of the file been returned. When //file_spec// is set to an empty string or no arguments are passed (or just //file_attrib//), then ##**Dir**## will return the next file found. The result will be an empty string when no files were found. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/system/dir.bas"}}%%(freebasic) #include "dir.bi" 'provides constants to use for the attrib_mask parameter Sub list_files (byref filespec as string, byval attrib as integer) Dim filename As String filename = dir( filespec, attrib ) Do Print filename filename = dir( ) Loop While len( filename ) > 0 End Sub Print "directories:" list_files "*", fbDirectory Print Print "archive files:" list_files "*", fbArchive %% {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/system/dirretat.bas"}}%%(freebasic) '' Example of using DIR function and retrieving attributes #include "dir.bi" '' provides constants to match the attributes against Dim As Integer out_attr '' integer to hold retrieved attributes (must currently be a signed int) Dim As String fname '' file/directory name returned with dim as integer filecount, dircount fname = Dir("*.*", 55, @out_attr) '' 55 - Input ATTR mask - all files and subdirs Print "File listing in " & curdir & ":" Do until len(fname) = 0 '' loop until Dir returns empty string If (fname <> ".") And (fname <> "..") Then '' ignore current and parent directory entries print fname, if out_attr and fbDirectory then print "- directory"; dircount += 1 else print "- file"; filecount += 1 end if if out_attr and fbReadOnly then print ", read-only"; if out_attr and fbHidden then print ", hidden"; if out_attr and fbSystem then print ", system"; if out_attr and fbArchive then print ", archived"; print End If fname = Dir(@out_attr) '' find next name Loop print print "Found " & filecount & " files and " & dircount & " subdirs" %% {{fbdoc item="target"}} - Linux requires the //filename// case matches the real name of the file. Windows and DOS are case insensitive. - Path separators in Linux are forward slashes / . Windows uses backward slashes \ but it allows for forward slashes . DOS uses backward \ slashes. {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Dir""**##. {{fbdoc item="diff"}} - The //attrib_mask// and //out_attrib// parameters are new to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgOpen Open]]## - ##[[KeyPgCurdir Curdir]]## - ##[[KeyPgMkdir Mkdir]]## - ##[[KeyPgRmdir Rmdir]]## {{fbdoc item="back" value="CatPgOpsys|Operating System Functions"}}{{fbdoc item="title" value="DO"}}---- Control flow statement for looping. {{fbdoc item="syntax"}}## **Do** [ { **Until** | **While** } //condition// ] [ //statement block// ] **Loop** **Do** [ //statement block// ] **Loop** [ { **Until** | **While** } //condition// ] ## {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgDoloop Do...Loop]]## {{fbdoc item="back" value="CatPgMisc|Miscellaneous"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:52:30 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 277729e9994ee5773c3447f1137f20f0 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 3735 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="DO...LOOP"}}---- Control flow statement for looping {{fbdoc item="syntax"}}## **Do** [ { **Until** | **While** } //condition// ] [ //statement block// ] **Loop** //or// **Do** [ //statement block// ] **Loop** [ { **Until** | **While** } //condition// ] ## {{fbdoc item="desc"}} The ##**Do**## statement executes the statements in the following //statement block// until/while the //condition//, if any, evaluates to true. If ##**Until**## is used, the ##**Do**## statement stops repetition of the //statement block// when //condition// evaluates to true. The ##**While**## keyword has opposite effect, stopping the loop if //condition// evaluates to false. If both //condition// and either ##**Until**## or ##**While**## are omitted, the ##**Do**## statement loops indefinitely. If an ##[[KeyPgExit Exit]]## ##**Do**## statement is encountered inside the //statement block//, the loop is terminated, and execution resumes immediately following the enclosing ##**Loop**## statement. If a ##[[KeyPgContinue Continue]]## ##**Do**## statement is encountered, the rest of the //statement block// is skipped and execution resumes at the ##**Do**## statement. In the first syntax, the //condition// is checked when the ##**Do**## statement is first encountered, and if the //condition// is met, the //statement block// will be skipped. In the second syntax, //condition// is initially checked //after// the //statement block// is executed. This means that the //statement block// is always guaranteed to execute //at least// once. //condition// may be any valid expression that evaluates to False (zero) or True (non-zero). {{fbdoc item="ex"}} In this example, a ##**Do**## loop is used to count the total number of odd numbers from 1 to 10. It will repeat //until// it's //n > 10// condition is met: {{fbdoc item="filename" value="examples/manual/control/do-loop.bas"}}%%(freebasic) dim as integer n = 1 '' number to check dim as integer total_odd = 0 '' running total of odd numbers do until( n > 10 ) if( ( n MOD 2 ) > 0 ) then total_odd += 1 '' add to total if n is odd (has remainder from division by 2) n += 1 loop print "total odd numbers: " ; total_odd '' prints '5' end 0 %% Here, an infinite DO loop is used to count the total number of evens. We place the conditional check inside the loop via an ##[[KeyPgIfthen If...Then]]## statement, which exits the loop if and when //n > 10// becomes true: {{fbdoc item="filename" value="examples/manual/control/do-loop2.bas"}}%%(freebasic) dim as integer n = 1 '' number to check dim as integer total_even = 0 '' running total of even numbers do if( n > 10 ) then exit do '' exit if we've scanned our 10 numbers if( ( n MOD 2 ) = 0 ) then total_even += 1 '' add to total if n is even (no remainder from division by 2) n += 1 loop print "total even numbers: " ; total_even '' prints '5' end 0 %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// and //[[CompilerOptlang -lang fblite]]// dialects, variables declared inside a DO..LOOP block have a function-wide [[ProPgVariableScope scope]] as in QB - In the //[[CompilerOptlang -lang fb]]// and //[[CompilerOptlang -lang deprecated]]// dialects, variables declared inside a FOR..NEXT block are visible only inside the block, and can't be accessed outside it. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgContinue Continue]]## - ##[[KeyPgExit Exit]]## - ##[[KeyPgFornext For...Next]]## - ##[[KeyPgWhilewend While...Wend]]## {{fbdoc item="back" value="CatPgControlFlow|Control Flow"}} {{fbdoc item="title" value="... (Ellipsis)"}}---- Used in place of procedure parameter to pass a variable number of arguments {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] { [[KeyPgSub sub]] | [[KeyPgFunction function]] } //proc_name// [[KeyPgCdecl cdecl]] ( //param// [[KeyPgAs as]] [[DataType datatype]], **...** ) ## {{fbdoc item="desc"}} The ellipsis (three dots "...") is used in procedure declarations and definitions to indicate a variable argument list. A first argument must always be specified and the function must be called with the C calling convention ##[[KeyPgCdecl cdecl]]##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/procs/ellipsis.bas"}}%%(freebasic) DECLARE FUNCTION FOO CDECL (X AS INTEGER, ...) AS INTEGER %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgCdecl cdecl]]## - ##[[KeyPgVaArg va_arg]]## - ##[[KeyPgVaFirst va_first]]## - ##[[KeyPgVaNext va_next]]## {{fbdoc item="back" value="CatPgProcedures|Procedures"}}{{fbdoc item="back" value="CatPgVarArg|Variable Argument list"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:52:39 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: e33e25419d99c582d02ddacf1f15f2f4 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 983 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="DOUBLE"}}---- Standard data type: 64 bit floating point {{fbdoc item="syntax"}}## [[KeyPgDim dim]] //variable// [[KeyPgAs as]] **Double** ## {{fbdoc item="desc"}} Double is a 64-bit, floating-point data type used to store precise decimal numbers. They can hold values in a range of -2.2E-308 to +1.7E+308. Its precision is of 15 decimal digits. They are similar to ##[[KeyPgSingle Single]]## data types but more precise and with an extended range. As precise as doubles are, they still have limited accuracy which can lead to significant inaccuracies if not used properly. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/datatype/double.bas"}}%%(freebasic) 'Example of using a double variable. dim a as double a = 1.985766472453666 print a sleep %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgSingle Single]]## - ##[[KeyPgCdbl Cdbl]]## {{fbdoc item="back" value="CatPgStdDataTypes|Standard Data Types"}} {{fbdoc item="title" value="DRAW"}}---- Statement for sequenced pixel plotting {{fbdoc item="syntax"}}## **Draw** [//target//,] //cmd// ## {{fbdoc item="param"}} ##//target//## the buffer to draw on ##//cmd//## a string containing the sequence of commands {{fbdoc item="desc"}} Drawing will take place onto the current work page set via ##[[KeyPgScreenset ScreenSet]]## or onto the ##//target//## ##[[KeyPgGetgraphics Get]]##/##[[KeyPgPutgraphics Put]]## buffer if specified. The ##**Draw**## statement can be used to issue several drawing commands all at once; it is useful to quickly draw figures. The command string accepts the following commands: Commands to plot pixels: {{table columns="2" cellpadding="1" cells="Command;Description;###;Commands to plot pixels:;B;Optional prefix: move but do not draw.;N;Optional prefix: draw but do not move.;Mx,y;Move to specified screen location. if + or - precedes x, movement is relative to current cursor position.;U[n];Move n units up. If n is omitted, 1 is assumed.;D[n];Move n units down. If n is omitted, 1 is assumed.;L[n];Move n units left. If n is omitted, 1 is assumed.;R[n];Move n units right. If n is omitted, 1 is assumed.;E[n];Move n units up and right. If n is omitted, 1 is assumed.;F[n];Move n units down and right. If n is omitted, 1 is assumed.;G[n];Move n units down and left. If n is omitted, 1 is assumed.;H[n];Move n units up and left. If n is omitted, 1 is assumed.;###;Commands to color:;Cn;Changes current foreground color to n.;Pp,b;Flood fills region with border color b with color p.;###;Commands to scale and rotate:;Sn;Sets the current unit length, default is 4. A unit length of 4 is equal to 1 pixel.;An;Rotate n*90 degrees (n ranges 0-3).;TAn;Rotate n degrees (n ranges 0-359);###;Extra commands:;Xp;Executes commands at address p."}} {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/draw.bas"}}%%(freebasic) '' set the screen mode to 320 * 200, 256 color Screen 13 '' start in the center of the screen Draw "BM160,100" '' Draw a box Draw "U10 R5 D10 L5" Sleep %% {{fbdoc item="filename" value="examples/manual/gfx/draw2.bas"}}%%(freebasic) Screen 13 Draw "BM160,100" '' Draw a box Dim As String drawbox = "U10R5D10L5" Draw "X" & Varptr(drawbox) Sleep %% {{fbdoc item="diff"}} - QB used the special pointer keyword VARPTR$ with the ##Xp## command. {{fbdoc item="see"}} - ##[[KeyPgDrawString Draw String]]## - ##[[KeyPgScreengraphics Screen (Graphics)]]## - ##[[KeyPgOpVarptr VarPtr]]## {{fbdoc item="back" value="CatPgGfx2D|2D Drawing Functions"}}{{fbdoc item="title" value="DRAW STRING"}}---- Graphics statement to render text to an image or screen. {{fbdoc item="syntax"}}## **Draw String** [//buffer//,] [STEP] (//x//, //y//), //text// [,//color// [, //font// [, //method// [, (//alpha//|//blender//) ] ] ] ] ## {{fbdoc item="param"}} ##//buffer//## the sprite to draw the string on. If this is not supplied, it will be drawn to the screen. ##STEP## use relative coordinates. If ##STEP## is added, the x and y coordinates are translated relative to the last drawn point. ##//x//##, ##//y//## the horizontal / vertical position to draw to, relative to the top left hand corner of the screen (unless ##STEP## is used - see above). The top left corner of the text will be drawn at this position. ##//text//## the string containing the text to draw ##//color//## if no font is supplied, this allows you to choose the color of the text. If font is supplied, the font itself specifies the color for each pixel. ##//font//## an image buffer containing a custom font. If no font is supplied, the standard font for the current mode is used. ##//method//## specifies how the font characters are drawn on top of the target surface. The same methods as found for the ##[[KeyPgPutgraphics Put]]## statement are allowed, with the only difference that the default method is ##TRANS## for this function. ##//alpha//## alpha value for the ##ALPHA## drawing method, ranging 0-255. ##//blender//## custom blender function for the ##CUSTOM## drawing method; see ##[[KeyPgPutgraphics Put (Graphics)]]## statement description for details. {{fbdoc item="desc"}} This graphics keyword prints a string to the screen with pixel positioning, transparent background, and can use an user-supplied font. **##Draw String##** does not update any text or graphics cursor. It doesn't wrap at the end of line. Tabs, carriage returns and other special characters have no special behavior in **##Draw String##**, and are treated as normal characters. In graphics mode, this function provides a flexible alternative to ##[[KeyPgPrint Print]]##. It has several key advantages: - ##**Draw String**## can print text to any coordinate on the screen, while ##[[KeyPgPrint Print]]## is constrained to the character grid accessible by ##[[KeyPgLocate Locate]]##. - ##[[KeyPgPrint Print]]## will override the background behind the text with the current background color. ##**Draw String**## does not do this: it leaves the pixels in the background untouched. - Like ##[[KeyPgPutgraphics Put]]##, ##**Draw String**## has several different methods for printing text, such as ##[[KeyPgAlphaGfx Alpha]]## and ##[[KeyPgCustomgfx Custom]]##. - ##**Draw String**## isn't limited to a single character set: it is possible to supply a custom font to be used instead. Note: If a custom font isn't supplied, **##Draw String##** will default to the standard font, as used by ##[[KeyPgPrint Print]]##, with character size dictated by ##[[KeyPgWidth Width]]##. ==The custom font format:== The font is stored in a standard ##[[KeyPgGetgraphics Get]]##/##[[KeyPgPutgraphics Put]]## buffer; the font has to be stored in a buffer using the same depth as the current color depth, otherwise **##Draw String##** will bump out with an illegal function call runtime error. First line of pixels in the font buffer holds the header of the font, on a byte (and NOT pixel) basis. The very first byte identifies the font header version; currently this must be ##0##. The second byte gives the ascii code of the first supported character in the font; the third byte gives the ascii code of the last supported character. So if the font supports the full range 0-255, ##0## and ##255## will be the contents of these two bytes. Next comes the width of each of the supported characters, each in a byte. Supposing the font holds 96 characters, ranging from 32 to 127 (inclusive), the header would have the first three bytes holding ##0##, ##32## and ##127##, followed by 96 bytes giving the widths of the corresponding chars. The font height is obtained by subtracting 1 from the buffer height, that is, while the first buffer line of pixels acts as a font header, the remaining lines define the glyphs' layout. The buffer must be as wide as necessary to hold all the supported character sprites in the same row, one after another. {{fbdoc item="ex"}} This gives an example of basic ##**Draw String**## usage: it uses it to print ##"Hello world"## in the center of the screen: {{fbdoc item="filename" value="examples/manual/gfx/drawstring.bas"}}%%(freebasic) const w = 320, h = 200 '' screen dimensions dim x as integer, y as integer, s as string '' Open a graphics window screenres w, h '' Draw a string in the centre of the screen: s = "Hello world" x = (w - len(s) * 8) \ 2 y = (h - 1 * 8) \ 2 draw string (x, y), s '' Wait for a keypress before ending the program sleep %% {{image class="center" title="Draw String Example 1" url="/images/drawstr1.png"}} This example shows you how to create and use your own custom font. For simplicity, it uses ##**Draw String**## with the default font to create the glyphs. {{fbdoc item="filename" value="examples/manual/gfx/drawstring-custom.bas"}}%%(freebasic) '' Define character range const FIRSTCHAR = 32, LASTCHAR = 127 const NUMCHARS = (LASTCHAR - FIRSTCHAR) + 1 dim as ubyte ptr p, myFont dim as integer i '' Open a 256 color graphics screen (320*200) screenres 320, 200, 8 '' Create custom font into PUT buffer myFont = imagecreate(NUMCHARS * 8, 9) '' Put font header at start of pixel data #ifndef ImageInfo '' older versions of FB don't have the ImageInfo feature p = myFont + IIf(myFont[0] = 7, 32, 4) #else ImageInfo( myFont, , , , , p ) #endif p[0] = 0 p[1] = FIRSTCHAR p[2] = LASTCHAR '' PUT each character into the font and update width information for i = FIRSTCHAR to LASTCHAR '' Here we could define a custom width for each letter, but for simplicity we use '' a fixed width of 8 since we are reusing the default font glyphs p[3 + i - FIRSTCHAR] = 8 '' Create character onto custom font buffer by drawing using default font draw string myFont, ((i - FIRSTCHAR) * 8, 1), chr(i), 32 + (i mod 24) + 24 next i '' Now the font buffer is ready; we could save it using BSAVE for later use rem bsave "myfont.bmp", myFont '' Here we draw a string using the custom font draw string (10, 10), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", , myFont draw string (10, 26), "abcdefghijklmnopqrstuvwxyz", , myFont draw string (66, 58), "Hello world!", , myFont '' Free the font from memory, now we are done with it imagedestroy myFont sleep %% {{image class="center" title="Draw String Example 2" url="/images/drawstr2.png"}} {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgPrint Print]]## - ##[[KeyPgDraw Draw]]## - ##[[KeyPgImagecreate ImageCreate]]## - ##[[KeyPgImageDestroy ImageDestroy]]## - ##[[KeyPgImageInfo ImageInfo]]## - ##[[KeyPgPutgraphics Put (Graphics)]]## - ##[[KeyPgWidth Width]]## {{fbdoc item="back" value="CatPgGfx2D|2D Drawing Functions"}}{{fbdoc item="title" value="DYLIBFREE"}}---- Unloads a dynamic link library from memory {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Dylibfree** ( [[KeyPgByval byval]] //library// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPointer pointer]] ) ## {{fbdoc item="usage"}}## **Dylibfree**( //library// ) ## {{fbdoc item="param"}} ##//library//## The handle of a library to unload. {{fbdoc item="desc"}} ##**Dylibfree**## is used to release at runtime libraries previously linked to your program with ##[[KeyPgDylibload Dylibload]]##. The argument is the handle to the library returned by ##[[KeyPgDylibload Dylibload]]##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/module/dylibfree.bas"}}%%(freebasic) Dim hndl As Any Ptr hndl=DyLibLoad("MYLIB.DLL") ' ... DyLibFree(hndl) %% {{fbdoc item="target"}} - Dynamic link libraries are not available in DOS, as the OS doesn't support them. {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Dylibfree""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDylibsymbol Dylibsymbol]]## - ##[[KeyPgDylibload Dylibload]]## - ##[[KeyPgExport Export]]## {{fbdoc item="back" value="CatPgModularizing|Modularizing"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:52:48 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: eade0c0cc484205e4be6086b43a8ab1a Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 1588 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="DYLIBLOAD"}}---- Loads to a Dynamic Link Library (DLL) into memory at runtime {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Dylibload** ( [[KeyPgByref byref]] //filename// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPointer Pointer]] ## {{fbdoc item="usage"}}## //result// = **Dylibload** ( //filename// ) ## {{fbdoc item="param"}} ##//filename//## A ##[[KeyPgString string]]## containing the filename of the library to load. {{fbdoc item="ret"}} The ##[[KeyPgPointer pointer]]## handle of the library loaded. {{fbdoc item="desc"}} ##[[KeyPgDylibload Dylibload]]## is used to link at runtime libraries to your program. This function does the link and returns a handle that must be used with ##[[KeyPgDylibsymbol Dylibsymbol]]## when calling a function in the library and with ##[[KeyPgDylibfree Dylibfree]]## when releasing the library. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/module/dylibload.bas"}}%%(freebasic) Dim hndl As Any Ptr hndl=DyLibLoad("MYLIB.DLL") %% {{fbdoc item="target"}} - Dynamic link libraries are not available in DOS, as the OS doesn't support them. {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Dylibload""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDylibsymbol Dylibsymbol]]## - ##[[KeyPgDylibfree Dylibfree]]## - ##[[KeyPgExport Export]]## {{fbdoc item="back" value="CatPgModularizing|Modularizing"}} {{fbdoc item="title" value="DYLIBSYMBOL"}}---- Returns the address of a function or variable in a dll {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Dylibsymbol** ( [[KeyPgByval byval]] //library// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]], [[KeyPgByref byref]] //symbol// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Dylibsymbol** ( [[KeyPgByval byval]] //library// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]], [[KeyPgByval byval]] //symbol// [[KeyPgAs as]] [[KeyPgShort short]] ) [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] ## {{fbdoc item="usage"}}## //result// = **Dylibsymbol** ( //library//, //symbol// ) ## {{fbdoc item="param"}} ##//library//## The [[KeyPgAny any]] [[KeyPgPtr ptr]] handle of a DLL returned by ##[[KeyPgDylibload Dylibload]]## ##//symbol//## A [[KeyPgString string]] containing name of the function, or variable in the library to return the address of. In Windows only, can also be a ##[[KeyPgShort short]]## containing the ordinal of the function/variable. {{fbdoc item="ret"}} A ##[[KeyPgPtr pointer]]## to the function or variable in the library. If the function fails, the return value is 0. {{fbdoc item="desc"}} ##**Dylibsymbol**## returns a pointer to the variable or function named ##//symbol//## , in the dll pointed by ##//libhandle//##. ##//libhandle//## is obtained by loading the dll with ##[[KeyPgDylibload Dylibload]]##. The symbol must have been ##[[KeyPgExport Export]]##ed in the dll. If ##//libhandle//## is 0, the symbol is searched in the current executable or dll. If using ##[[KeyPgCdecl Cdecl]]## functions, only the name of the procedure needs to be specified. If dynamically linking to a function created using STDCALL (default in windows), then the function must be decorated. To decorate a function, use its name, '@', then the number of bytes passed as arguments. For instance if the function ##FOO## takes 3 integer arguments, the decorated function would be 'FOO@12'. Remember, without an explicit ##[[KeyPgAlias alias]]##, the procedure name will be uppercase. If linking to a dll created in Visual C""++""(tm), decoration need not be used. For GCC, decoration is needed. **Note:** The dylibsymbol, if failing, will attempt to automatically decorate the procedure, from @0 to @256, in 4 byte increments. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/module/mydll2.bas"}}%%(freebasic) '' mydll.dll '' in the DLL the function must be declared as CDECL and export Function AddNumbers cdecl Alias "AddNumbers" _ ( _ ByVal operand1 As Integer, ByVal operand2 As Integer _ ) As Integer Export AddNumbers = operand1 + operand2 End Function %% {{fbdoc item="filename" value="examples/manual/module/dylibsymbol.bas"}}%%(freebasic) '' create a function pointer, arguments must be the same '' as in the original function Dim AddNumbers As Function ( ByVal operand1 As Integer, ByVal operand2 As Integer ) As Integer Dim hndl As Any Ptr hndl=DyLibLoad("mydll.dll") '' find the procedure address (case matters!) AddNumbers = DyLibSymbol( hndl, "AddNumbers" ) '' then call it.. Print "1 + 2 ="; AddNumbers( 1, 2 ) DyLibFree hndl Sleep %% {{fbdoc item="target"}} - Dynamic link libraries are not available in DOS ,as the OS doesn't support them. - Ordinals are not supported on Linux, 0 is always returned. {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Dylibsymbol""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDylibload Dylibload]]## - ##[[KeyPgExport Export]]## {{fbdoc item="back" value="CatPgModularizing|Modularizing"}}{{fbdoc item="title" value="ELSE"}}---- Control flow statement for conditional branching {{fbdoc item="syntax"}}## **If** //expression// **Then** //statement(s)// [**Else** //statement(s)//] //or// **If** //expression// **Then** : //statement(s)// [**Else** //statement(s)//] : **End If** //or// **If** //expression// **Then** //statement(s)// [ **Elseif** //expression// **Then** ] //statement(s)// [ **Else** ] //statement(s)// **End If** ## {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgIfthen If...Then]]## {{fbdoc item="back" value="CatPgControlFlow|Control Flow"}}{{fbdoc item="title" value="ELSEIF"}}---- Control flow statement for conditional branching {{fbdoc item="syntax"}}## **If** //expression// **Then** //statement(s)// [**Else** //statement(s)//] //or// **If** //expression// **Then** : //statement(s)// [**Else** //statement(s)//] : **End If** //or// **If** //expression// **Then** //statement(s)// [ **Elseif** //expression// **Then** ] //statement(s)// [ **Else** ] //statement(s)// **End If** ## {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgIfthen If...Then]]## {{fbdoc item="back" value="CatPgControlFlow|Control Flow"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:52:58 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 328dcac59025499f461d31f0264d679e Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 3052 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="ENCODING"}}---- Specifies character format of a text file {{fbdoc item="syntax"}}## [[KeyPgOpen open]] //filename// for {Input|Output|Append} **Encoding** "//utf-8//"|"//utf-16//"|"//utf-32//"|"//ascii//" as [#]//filenum// ## {{fbdoc item="param"}} ##//filename//## for {Input|Output|Append} file name to open for ##[[KeyPgInputfilemode Input]]##, ##[[KeyPgOutput Output]]##, or ##[[KeyPgAppend Append]]## ##**Encoding** "//utf-8//"|"//utf-16//"|"//utf-32//"|"//ascii//"## indicates encoding type for the file ##//filenum//## unused file number to associate with the open file {{fbdoc item="desc"}} ##**Encoding**## specifies the format for an Unicode text file, so ##[[KeyPgWinput Winput #]]## and ##[[KeyPgPrintPp Print #]]## use the correct encoding. If omitted from an ##[[KeyPgOpen Open]]## statement, "ascii" encoding is the default. Only little endian character encodings are supported at the moment. -"utf8", -"utf16" -"utf32" -"ascii" (the default) {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/fileio/encoding.bas"}}%%(freebasic) '' This example will: '' 1) Write a string to a text file with utf-16 encoding '' 2) Display the byte contents of the file '' 3) Read the text back from the file '' '' WSTRING's will work as well but STRING has been '' used in this example since not all consoles support '' printing WSTRING's. '' The name of the file to use in this example dim f as string f = "sample.txt" '' scope dim s as string s = "FreeBASIC" print "Text to write to " + f + ":" print s print '' open a file for output using utf-16 encoding '' and print a short message open f for output encoding "utf-16" as #1 '' The ascii string is converted to utf-16 print #1, s close #1 end scope '' scope dim s as string, n as integer '' open the same file for binary and read all the bytes open f for binary as #1 n = lof(1) s = space( n ) get #1,,s close #1 print "Binary contents of " + f + ":" for i as integer = 1 to n print hex( asc( mid( s, i, 1 )), 2); " "; next print print end scope '' scope dim s as string '' open a file for input using utf-16 encoding '' and read back the message open f for input encoding "utf-16" as #1 '' The ascii string is converted from utf-16 line input #1, s close #1 '' Display the text print "Text read from " + f + ":" print s print end scope %% Output: %% Text to write to sample.txt: FreeBASIC Binary contents of sample.txt: FF FE 46 00 72 00 65 00 65 00 42 00 41 00 53 00 49 00 43 00 0D 00 0A 00 Text read from sample.txt: FreeBASIC %% {{fbdoc item="target"}} - Unicode (w)strings are not supported in the DOS port of FreeBASIC {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Encoding""**##. {{fbdoc item="diff"}} - QB had no support for Unicode {{fbdoc item="see"}} - ##[[KeyPgOpen Open]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}} {{fbdoc item="title" value="END (Statement)"}}---- Control flow statement to end the program. {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **End** ( [[KeyPgByval byval]] //retval// [[KeyPgAs as]] [[KeyPgInteger integer]] = 0 ) ## {{fbdoc item="usage"}}## **End** [ //retval// ] ## {{fbdoc item="param"}} ##//retval//## Error code returned to system. {{fbdoc item="desc"}} Used to terminate the program, and return to the operating system. An optional integer return value can be specified to indicate an error code to the system. If no return value is given, a value of 0 is automatically returned. Usage of this statement does not cleanly close scope. Variables and memory are not destroyed automatically and object destructors are not called. Calling the required destructors and other clean-up should be explicitly performed before an ##**End**## statement. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/control/end.bas"}}%%(freebasic) '' This program stores input from the user in a string, checks the strings length, '' by calling valid_string, and either displays the string, or an error message function valid_string( s as string ) as integer return len( s ) end function '' assign input to text string (a string of spaces will input as an empty string) dim as string text print "Type in some text ( try ""abc"" ): " ; input text '' check if string is valid (not empty). If so, print an error message and return '' to the OS with error code -1 if( not valid_string( text ) ) then print "ERROR: you must enter a valid string" sleep : end -1 end if '' string is valid, so print the string and return to the OS with error code 0 print "You entered: " ; text sleep : end 0 %% {{fbdoc item="diff"}} - The END statement supports specifying a custom return value to be returned to the operating system. {{fbdoc item="see"}} - ##[[KeyPgEndblock End (Block)]]## {{fbdoc item="back" value="CatPgMisc|Miscellaneous"}}{{fbdoc item="title" value="END (Block)"}}---- Indicates the end of a compound statement block. {{fbdoc item="syntax"}}## **End** { [[KeyPgSub Sub]] | [[KeyPgFunction Function]] | [[KeyPgIfthen If]] | [[KeyPgSelectcase Select]] | [[KeyPgType Type]] | [[KeyPgEnum Enum]] | [[KeyPgScope Scope]] | [[KeyPgWith With]] | [[KeyPgNamespace Namespace]] | [[KeyPgExtern Extern]] | [[KeyPgConstructor Constructor]] | [[KeyPgDestructor Destructor]] | [[KeyPgOperator Operator]] | [[KeyPgProperty Property]] } ## {{fbdoc item="desc"}} Used to indicate the end of the most recent code block. The type of the block must be included in the command: one of ##[[KeyPgSub Sub]]##, ##[[KeyPgFunction Function]]##, ##[[KeyPgIfthen If]]##, ##[[KeyPgSelectcase Select]]##, ##[[KeyPgType Type]]##, ##[[KeyPgEnum Enum]]##, ##[[KeyPgScope Scope]]##, ##[[KeyPgWith With]]##, ##[[KeyPgNamespace Namespace]]##, ##[[KeyPgExternBlock Extern]]##, ##[[KeyPgConstructor Constructor]]##, ##[[KeyPgDestructor Destructor]]##, ##[[KeyPgOperator Operator]]##, or ##[[KeyPgProperty Property]]##. Ending a ##[[KeyPgSub Sub]]##, ##[[KeyPgFunction Function]]##, ##[[KeyPgIfthen If]]##, ##[[KeyPgSelectcase Select]]##, ##[[KeyPgScope Scope]]##, ##[[KeyPgConstructor Constructor]]##, ##[[KeyPgDestructor Destructor]]##, ##[[KeyPgOperator Operator]]##, or ##[[KeyPgProperty Property]]## block also closes the scope for variables defined inside that block. When the scope is closed, variables defined inside the scope are destroyed, calling their destructors as needed. To end a program, see ##[[KeyPgEnd End (Statement)]]##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/control/endblock.bas"}}%%(freebasic) Declare Sub checkvalue( n As Integer ) Dim variable As Integer Input "Give me a number: ", variable If variable = 1 Then Print "You gave me a 1" Else Print "You gave me a big number!" End If checkvalue(variable) Sub checkvalue( n As Integer ) Print "Value is: " & n End Sub %% {{fbdoc item="diff"}} - none {{fbdoc item="see"}} - ##[[KeyPgConstructor Constructor]]## - ##[[KeyPgDestructor Destructor]]## - ##[[KeyPgEnd End (Statement)]]## - ##[[KeyPgEnum Enum]]## - ##[[KeyPgExternBlock Extern]]## - ##[[KeyPgFunction Function]]## - ##[[KeyPgIfthen If...Then]]## - ##[[KeyPgNamespace Namespace]]## - ##[[KeyPgOperator Operator]]## - ##[[KeyPgProperty Property]]## - ##[[KeyPgScope Scope]]## - ##[[KeyPgSelectcase Select Case]]## - ##[[KeyPgSub Sub]]## - ##[[KeyPgType Type]]## - ##[[KeyPgWith With]]## {{fbdoc item="back" value="CatPgMisc|Miscellaneous"}}{{fbdoc item="title" value="END IF"}}---- Control flow statement for conditional branching. {{fbdoc item="syntax"}}## **If** //expression// **Then** : //statement(s)// [**Else** //statement(s)//] : **End If** //or// **If** //expression// **Then** //statement(s)// **End If** ## {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgIfthen If...Then]]## {{fbdoc item="back" value="CatPgMisc|Miscellaneous"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:53:07 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 25b2e5a902c8311d17ba438ba459175f Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 2041 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="ENUM"}}---- Declares an enumerated type. {{fbdoc item="syntax"}}## **Enum** [//typename// [ Explicit ] ] //symbolname// [= //expression//] [, ...] ... End Enum ## {{fbdoc item="param"}} ##//typename//## Name of the ##**Enum**## ##//symbolname//## Name of the constant ##//expression//## A constant expression ##Explicit## Requires that symbols must be explicitly referred to by ##//typename//.//symbolname//## {{fbdoc item="desc"}} ##**Enum**##, short for enumeration, declares a list of symbol names that correspond to discrete values. If no initial value is given, the first item will be set to 0. Each subsequent symbol has a value one more than the previous unless ##//expression//## is given. Symbols may be each on their own line, or separated on a single line by commas. An ##**Enum**## is a useful way of grouping together a set of related ##[[KeyPgConst const]]##ants. A symbol can be accessed like constant, e.g: ##a = //symbolname//##. But if the name clashes with another symbol, it must be resolved using ##//typename//.//symbolname//##. This resolution method is always required if you make the enum ##Explicit##. An ##**Enum**## can be passed as a user defined type to ##[[KeyPgOverload overload]]##ed operator functions. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/udt/enum.bas"}}%%(freebasic) enum MyEnum option1 = 1 option2 option3 end enum dim MyVar as MyEnum MyVar = option1 select case MyVar case option1 print "Option 1" case option2 print "Option 2" case option3 print "Option 3" end select %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Enum""**##. {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgConst Const]]## - ##[[KeyPgOperator Operator]]## {{fbdoc item="back" value="CatPgUserDefTypes|User Defined Types"}} {{fbdoc item="title" value="ENVIRON"}}---- Returns the value of a system environment variable {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Environ** ( [[KeyPgByref byref]] //varname// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgString string]] ## {{fbdoc item="usage"}}## //result// = **Environ**( //varname// ) ## {{fbdoc item="param"}} ##//varname//## The name of an environment variable. {{fbdoc item="ret"}} Returns the text value of the environmental variable, or the empty string (##"####"##) if the variable does not exist. {{fbdoc item="desc"}} ##**Environ**## returns the text value of a system environment variable. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/system/environ.bas"}}%%(freebasic) 'e.g. to show the system variable "path": print environ("path") %% {{fbdoc item="diff"}} - The ##**ENVIRON**## statement is now called ##[[KeyPgSetenviron Setenviron]]##. {{fbdoc item="see"}} - ##[[KeyPgSetenviron Setenviron]]## - ##[[KeyPgShell Shell]]## {{fbdoc item="back" value="CatPgOpsys|Operating System Functions"}}{{fbdoc item="title" value="EOF"}}---- Checks to see if the end of an open file has been reached {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Eof** ( [[KeyPgByval byval]] //filenum// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **Eof**( //filenum// ) ## {{fbdoc item="param"}} ##//filenum//## An ##[[KeyPgInteger integer]]## file number of an open file. {{fbdoc item="ret"}} Returns true (-1) if end-of-file has been reached, zero (0) otherwise. {{fbdoc item="desc"}} When reading from files opened for ##[[KeyPgInputfilemode Input (File Mode)]]##, it is useful to know when the end of the file has been reached, thus avoiding errors caused by reading past the ends of files. Use EOF to determine this. EOF expects a valid file number from an already opened file. Use ##[[KeyPgFreefile Freefile]]## to retrieve an available file file number. For file numbers bound to files opened for ##[[KeyPgOutput Output]]##, EOF always returns 0. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/fileio/eof.bas"}}%%(freebasic) '' This code finds a free file number to use and attempts to open the file '' "file.ext" and if successful, binds our file number to the opened file. It '' reads the file line by line, outputting it to the screen. We loop until eof() '' returns true, in this case we ignore the loop if file is empty. dim as string file_name dim as integer file_num file_name = "file.ext" file_num = freefile( ) '' retrieve an available file number '' open our file and bind our file number to it, exit on error if( open( file_name for input as #file_num ) ) then print "ERROR: opening file " ; file_name end -1 end if do until eof( file_num ) '' loop until we have reached the end of the file dim as string text line input #file_num, text '' read a line of text ... print text '' ... and output it to the screen loop close #file_num '' close file via our file number end 0 %% {{fbdoc item="diff"}} - In QB the comm port signaled an EOF when there were no chars waiting to be read. - In QB, for files opened in RANDOM or BINARY mode, EOF returned non-zero only after a read past the end of file has been attempted. In FreeBASIC, EOF returns true after the last item is read. {{fbdoc item="see"}} - ##[[KeyPgLof Lof]]## - ##[[KeyPgLoc Loc]]## - ##[[KeyPgFreefile Freefile]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}}{{fbdoc item="title" value="ERASE"}}---- Statement to erase arrays {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Erase** ( array [[KeyPgAs as]] [[KeyPgAny any]] [, ... ] ) ## {{fbdoc item="usage"}}## **Erase**( //array0// [, //array1// ... //arrayN// ] ) ## {{fbdoc item="param"}} ##//array//## An array to be erase. {{fbdoc item="desc"}} Erases the element data of one or more variable-length arrays from memory, or clears (initializes) all elements in a fixed-length array. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/array/erase.bas"}}%%(freebasic) dim MyArray1(1 to 10) as integer redim MyArray2(1 to 10) as integer erase MyArray1, MyArray2 %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgCommon Common]]## - ##[[KeyPgDim Dim]]## - ##[[KeyPgExtern Extern]]## - ##[[KeyPgLbound Lbound]]## - ##[[KeyPgRedim Redim]]## - ##[[KeyPgStatic Static]]## - ##[[KeyPgUbound UBound]]## - ##[[KeyPgVar Var]]## {{fbdoc item="back" value="CatPgArray|Array Functions"}}{{fbdoc item="title" value="ERFN"}}---- Error reporting function {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Erfn** ( ) [[KeyPgAs as]] [[KeyPgZstring zstring]] [[KeyPgPtr ptr]] ## {{fbdoc item="usage"}}## //result// = **Erfn** ( ) ## {{fbdoc item="ret"}} Returns a pointer to the string identifying the function where the error occurred. Returns NULL if the source is not compiled with the //[[CompilerOptexx -exx]]// compiler option. {{fbdoc item="desc"}} An error reporting function returning a pointer to the name of the function. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/error/erfn.bas"}}%%(freebasic) '' test.bas '' compile with fbc -exx -lang fblite test.bas sub Generate_Error on error goto Handler error 1000 exit sub Handler: print "Error Function: "; *ERFN() print "Error Module : "; *ERMN() resume Next end sub Generate_Error %% **Output:** %%Error Function: GENERATE_ERROR Error Module : test.bas %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Erfn""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgErl Erl]]## - ##[[KeyPgErmn Ermn]]## - ##[[KeyPgOnerror On...Error]]## {{fbdoc item="back" value="CatPgError|Error Handling Functions"}}{{fbdoc item="title" value="ERL"}}---- Error handling function to return the line where the error occurred {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Erl** ( ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **Erl** ## {{fbdoc item="ret"}} An [[KeyPgInteger integer]] return value containing the line number where the last error occurred. {{fbdoc item="desc"}} ##**Erl**## will return the line number where the last error occurred. If no error has occurred, ##**Erl**## will return 0. ##**Erl**## cannot always be used effectively -- QB-like error handling must be enabled. ##**Erl**## is reset by RESUME and RESUME NEXT {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/error/erl.bas"}}%%(freebasic) ' compile with -lang fblite or qb ' note: compilation with '-ex' option is required on error goto ErrorHandler ' Generate an explicit error error 100 end ErrorHandler: dim num as integer = ERR print "Error "; num; " on line "; ERL resume next ' Expected output is ' Error 100 on line 6 %% {{fbdoc item="diff"}} - FreeBASIC returns the source code line number and ignores the values of all explicit line numbers, where as QB returns the last encountered explicit line number, and will return zero (0) when explicit line numbers are not used. {{fbdoc item="see"}} - {{fbdoc item="keyword" value="ProPgErrorHandling|Error Handling"}} - ##{{fbdoc item="keyword" value="KeyPgErr|Err"}}## {{fbdoc item="back" value="CatPgError|Error Handling Functions"}}{{fbdoc item="title" value="ERMN"}}---- Error reporting function {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Ermn** ( ) [[KeyPgAs as]] [[KeyPgZstring zstring]] [[KeyPgPtr ptr]] ## {{fbdoc item="usage"}}## //result// = **Ermn** ( ) ## {{fbdoc item="ret"}} Returns a pointer to the string identifying the module where the error occurred. Returns NULL if the source is not compiled with the //[[CompilerOptexx -exx]]// compiler option. {{fbdoc item="desc"}} An error reporting function returning a pointer to the name of the module. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/error/ermn.bas"}}%%(freebasic) '' test.bas '' compile with fbc -exx -lang fblite test.bas sub Generate_Error on error goto Handler error 1000 exit sub Handler: print "Error Function: "; *ERFN() print "Error Module : "; *ERMN() resume Next end sub Generate_Error %% **Output:** %%Error Function: GENERATE_ERROR Error Module : test.bas %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Ermn""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgErfn Erfn]]## - ##[[KeyPgErl Erl]]## - ##[[KeyPgOnerror On...Error]]## {{fbdoc item="back" value="CatPgError|Error Handling Functions"}}{{fbdoc item="title" value="ERR"}}---- Error handling function to return the error number of the last error {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Err** ( ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **Err** ## {{fbdoc item="ret"}} After an error, returns the error code that occurred. {{fbdoc item="desc"}} ##**Err**## can always be used, even if QB-like error handling is not enabled. ##**Err**## is reset by ##[[KeyPgResume Resume]]## and ##[[KeyPgResumenext Resume Next]]##. NOTE: PRINT ERR after an error occurred is likely to print 0, because PRINT sets a new ERR value when executed. To print an ERR value it must be first copied to an auxiliary variable and print that one. See [[TblRuntimeErrors Runtime Error Codes]] for a listing of runtime error numbers and their associated meaning. {{fbdoc item="ex"}} An example using QBasic style error handling (compile with -ex option) {{fbdoc item="filename" value="examples/manual/error/err1.bas"}}%%(freebasic) '' Compile with -lang fblite or qb on error goto Error_Handler error 150 end Error_Handler: n = Err print "Error #"; n resume next %% An example using inline error handling {{fbdoc item="filename" value="examples/manual/error/err2.bas"}}%%(freebasic) dim a as string do input "Input filename ";a if a="" then exit do open a for input as #1 loop until err=0 %% {{fbdoc item="diff"}} - Error numbers are not the same as in QB. {{fbdoc item="see"}} - ##[[KeyPgOnerror On Error]]## - {{fbdoc item="keyword" value="ProPgErrorHandling|Error Handling"}} - [[TblRuntimeErrors Runtime Error Codes]] {{fbdoc item="back" value="CatPgError|Error Handling Functions"}}{{fbdoc item="title" value="ERROR"}}---- Error handling statement to force an error to be generated {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Error** ( //errno// [[KeyPgAs as]] [[KeyPgInteger integer]] ) ## {{fbdoc item="usage"}}## **Error** //errno// ## {{fbdoc item="param"}} ##//errno//## The error number to generate {{fbdoc item="desc"}} Generates a run-time error using the specified ##//errno//##. This can be used to simulate custom error numbers. No user error code range is defined, so if ##[[KeyPgError Error]]## is used to set an user-defined error code it is wise to use high values, to avoid collisions in case the list of built-in errors list is enhanced. See [[TblRuntimeErrors Runtime Error Codes]] for a listing of runtime error numbers and their associated meaning. {{fbdoc item="ex"}} To send an error alert of error 150 (just some arbitrary error code) one would do the following: {{fbdoc item="filename" value="examples/manual/error/error.bas"}}%%(freebasic) error 150 %% {{fbdoc item="diff"}} - Error numbers are not the same as in QB. {{fbdoc item="see"}} - ##[[KeyPgErr Err]]## - {{fbdoc item="keyword" value="ProPgErrorHandling|Error Handling"}} - [[TblRuntimeErrors Runtime Error Codes]] {{fbdoc item="back" value="CatPgError|Error Handling Functions"}}{{fbdoc item="title" value="EXEC"}}---- Temporarily transfers execution to an external program {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub function]] **Exec** ( [[KeyPgByref byref]] //program// [[KeyPgAs as]] [[KeyPgString string]], [[KeyPgByref byref]] //arguments// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **Exec**( //program//, //arguments// ) ## {{fbdoc item="param"}} ##//program//## The file name (including file path) of the program (executable) to transfer control to. ##//arguments//## The command-line arguments to be passed to the program. {{fbdoc item="ret"}} The exit status of the program, or negative one (-1) if the program could not be executed. {{fbdoc item="desc"}} Transfers control over to an external program. When the program exits, execution resumes immediately after the call to ##**Exec**##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/system/exec.bas"}}%%(freebasic) 'A Windows based example but the same idea applies to Linux CONST exename = "NoSuchProgram.exe" CONST cmdline = "arg1 arg2 arg3" DIM result AS INTEGER result = EXEC( exename, cmdline ) IF result = -1 THEN PRINT "Error running "; exename ELSE PRINT "Exit code:"; result END IF %% {{fbdoc item="target"}} - Linux requires the //program// case matches the real name of the file. Windows and DOS are case insensitive. The program being executed may be case sensitive for its command line parameters. - Path separators in Linux are forward slashes / . Windows uses backward slashes \ but it allows for forward slashes . DOS uses backward \ slashes. {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Exec""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgChain Chain]]## - ##[[KeyPgRun Run]]## - ##[[KeyPgCommand Command]]## {{fbdoc item="back" value="CatPgOpsys|Operating System Functions"}}{{fbdoc item="title" value="EXEPATH"}}---- Returns the path of the running program {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Exepath** ( ) [[KeyPgAs as]] [[KeyPgString string]] ## {{fbdoc item="usage"}}## //result// = **Exepath** ## {{fbdoc item="ret"}} A ##[[KeyPgString string]]## variable set to the path of the running program. {{fbdoc item="desc"}} Returns the path (the location) of the calling program. This is not necessarily the same as ##[[KeyPgCurdir Curdir]]##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/system/exepath.bas"}}%%(freebasic) Dim pathname As String = ExePath Print "This program's initial directory is: " & pathname %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Exepath""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgCurdir Curdir]]## {{fbdoc item="back" value="CatPgOpsys|Operating System Functions"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:53:19 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 8662a1948c8a1ec61f6fc4a692d47553 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 2165 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="EXIT"}}---- Control flow statement to exit a compound statement block {{fbdoc item="syntax"}}## **Exit** {[[KeyPgDoloop Do]] | [[KeyPgFornext For]] | [[KeyPgWhilewend While]] | [[KeyPgSelectcase Select]] } **Exit** {[[KeyPgSub Sub]] | [[KeyPgFunction Function]] | [[KeyPgOperator Operator]] | [[KeyPgProperty Property]] } **Exit** {[[KeyPgDoloop Do]] [, [[KeyPgDoloop Do]] [ , ...] ] | [[KeyPgFornext For]] [, [[KeyPgFornext For]] [ , ...] ] | [[KeyPgWhilewend While]] [, [[KeyPgWhilewend While]], [...] ] | [[KeyPgSelectcase Select]] [, [[KeyPgSelectcase Select]] [ , ...] ] } ## {{fbdoc item="desc"}} Leaves a code block such as a ##[[KeyPgSub Sub]]##, ##[[KeyPgFunction Function]]##, ##[[KeyPgDoloop Do...Loop]]##, ##[[KeyPgFornext For...Next]]##, ##[[KeyPgWhilewend While...Wend]]##, or a ##[[KeyPgSelectcase Select Case]]## block. The execution skips the rest of the block and goes to the line after its end. Where there are multiple ##[[KeyPgDoloop Do]]## / ##[[KeyPgFornext For]]## / ##[[KeyPgWhilewend While]]## / ##[[KeyPgSelectcase Select]]## blocks nested, it will skip to the end of the innermost block of that type. You can skip to the end of multiple blocks of that type by giving the word multiple times, separated by commas. For example: ##**Exit While, While**## {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/control/exit.bas"}}%%(freebasic) 'e.g. the print command will not be seen Do Exit Do ' Exit the Do...Loop and continues to run the code after Loop Print "I will never be shown" Loop %% {{fbdoc item="filename" value="examples/manual/control/exit2.bas"}}%%(freebasic) Dim As Integer i, j For i = 1 to 10 For j = 1 to 10 Exit For, For Next j Print "I will never be shown" Next i %% {{fbdoc item="diff"}} - EXIT WHILE and EXIT SELECT are New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgSub Sub]]## - ##[[KeyPgFunction Function]]## - ##[[KeyPgDoloop Do...Loop]]## - ##[[KeyPgFornext For...Next]]## - ##[[KeyPgWhilewend While...Wend]]## - ##[[KeyPgContinue Continue]]## {{fbdoc item="back" value="CatPgControlFlow|Control Flow"}} {{fbdoc item="title" value="EXP"}}---- Returns //**e**// raised to the power of a given number {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Exp** [[KeyPgCdecl cdecl]] ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgDouble double]] ) [[KeyPgAs as]] [[KeyPgDouble double]] ## {{fbdoc item="usage"}}## //result// = **Exp** ( //number// ) ## {{fbdoc item="param"}} ##//number//## The ##[[KeyPgDouble double]]## ##//number//## that e is raised to the power of. {{fbdoc item="ret"}} Returns the [[KeyPgDouble Double]] value of //e// raised to power of ##//number//##. {{fbdoc item="desc"}} The mathematical constant //e//, also called Euler's constant, is the base of the ##Exp## and ##[[KeyPgLog Log]]## and is an irrational and transcendental number. The value of //e// to twenty places is: 2.7182818284590452354. The required ##//number//## argument can be any valid numeric expression within range of the function. If ##//number//## is too large, FreeBASIC returns infinity. If ##//number//## is too small, FreeBASIC returns zero. The exact limit on ##//number//## is based on the math processor. If ##//number//## is an uninitialized variable, 1 is returned. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/math/exp.bas"}}%%(freebasic) 'Compute Continuous Compound Interest DIM r AS DOUBLE DIM p AS DOUBLE DIM t AS DOUBLE DIM a AS DOUBLE INPUT "Please enter the initial investment (principal amount): "; p INPUT "Please enter the annual interest rate (as a decimal): "; r INPUT "Please enter the number of years to invest: "; t a = p * EXP ( r * t ) PRINT "" PRINT "After";t;" years, at an interest rate of"; r * 100; "%, your initial investment of"; p; " would be worth";a %% The output would look like: %% Please enter the initial investment (principal amount): 100 Please enter the annual interest rate (As a decimal): .08 Please enter the number of years To invest: 20 After 20 years, at an interest rate of 8%, your initial investment of 100 would be worth 495.3032424395115 %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgLog Log]]## {{fbdoc item="back" value="CatPgMath|Math"}}{{fbdoc item="title" value="EXPORT"}}---- Declaration specifier to indicate that a procedure in a DLL should be visible from other programs {{fbdoc item="syntax"}}## { [[KeyPgSub sub]] | [[KeyPgFunction function]] } //proc_name// ( //argumentlist// ) [ [[KeyPgAs as]] [[DataType datatype]] ] **Export** ## {{fbdoc item="desc"}} If a function is declared with this clause in a DLL, it is added to the public export table, so external programs can dynamically link to it using [[KeyPgDylibsymbol Dylibsymbol]]. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/module/mydll.bas"}}%%(freebasic) '' mydll.dll '' in the DLL the function must be declared as CDECL and export Function AddNumbers cdecl Alias "AddNumbers" _ ( _ ByVal operand1 As Integer, ByVal operand2 As Integer _ ) As Integer Export AddNumbers = operand1 + operand2 End Function %% {{fbdoc item="filename" value="examples/manual/module/export.bas"}}%%(freebasic) '' create a function pointer, arguments must be the same type '' as in the original function Dim AddNumbers As Function ( ByVal As Integer, ByVal As Integer ) As Integer Dim hndl As Any Ptr hndl=DyLibLoad("mydll.dll") '' find the proc address (case matters!) AddNumbers = DyLibSymbol( hndl, "AddNumbers" ) '' then call it ... Print "1 + 2 = " & AddNumbers( 1, 2 ) Sleep %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Export""**##. {{fbdoc item="target"}} - Dynamic link libraries are not available in DOS, as the OS doesn't support them. {{fbdoc item="diff"}} - New to Freebasic {{fbdoc item="see"}} - ##[[KeyPgDylibload Dylibload]]## - ##[[KeyPgDylibsymbol Dylibsymbol]]## - ##[[KeyPgAlias Alias]]## {{fbdoc item="back" value="CatPgModularizing|Modularizing"}}{{fbdoc item="back" value="CatPgProcedures|Procedures"}}{{fbdoc item="title" value="EXTERN"}}---- Declares a variable, array or object having external linkage {{fbdoc item="syntax"}}## **Extern** [ [[KeyPgImport Import]] ] //symbolname//[ (//subscripts//) ] [ [[KeyPgAlias Alias]] "//aliasname//" ] [[KeyPgAs as]] //[[DataType DataType]]// [, ...] ## {{fbdoc item="param"}} ##//symbolname//## The name of the variable, array or object. ##//aliasname//## An alternate external name for the variable, array or object. {{fbdoc item="desc"}} Declares ##//symbolname//## as an external name, meaning it is global to external modules. ##**Extern**## only declares variables, arrays and objects, and does not define them (different from ##[[KeyPgCommon Common]]## or ##[[KeyPgDim Dim]]##). It also has the effect of making ##//symbolname//## a //shared// name, meaning it is visible within procedures (see ##[[KeyPgShared Shared]]##). If ##[[KeyPgAlias Alias]]## is used, ##//aliasname//## will be used as the external name rather than ##//symbolname//##, and its case will be preserved. If ##[[KeyPgImport Import]]## is used, the name will be added to the dynamic library import list so its address can be fixed at run-time. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/module/extern1.bas"}}%%(freebasic) '' extern1.bas Extern Foo Alias "foo" As Integer Sub SetFoo foo = 1234 End Sub %% {{fbdoc item="filename" value="examples/manual/module/extern2.bas"}}%%(freebasic) '' extern2.bas Declare Sub SetFoo Extern Foo Alias "foo" As Integer Dim foo As Integer = 0 SetFoo Print Foo %% Output: %% 1234 %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgExternBlock Extern...End Extern]]## - ##[[KeyPgCommon Common]]## - ##[[KeyPgDim Dim]]## - ##[[KeyPgShared Shared]]## {{fbdoc item="back" value="CatPgModularizing|Modularizing"}}{{fbdoc item="title" value="EXTERN...END EXTERN"}}---- Statement block to give external linkage to declarative statements {{fbdoc item="syntax"}}## **Extern { """C""" | """C++""" | """Windows""" | """Windows-MS"""** } //declarative statements// **End Extern** ## {{fbdoc item="desc"}} ##**Extern**## blocks give external linkage to the names declared within them. They also provide default calling conventions for procedures and mandate a certain name decoration. ##**Extern """C"""**## blocks provide a default ##[[KeyPgCdecl Cdecl]]## calling convention to procedures, and also preserve the case of all names declared within them. ##**Extern """C++"""**## blocks are exactly like ##**Extern """C"""**## blocks but they also mangle the names declared within them in a way compatible to that of //g""++""-4.x//. ##**Extern """Windows"""**## blocks provide a default ##[[KeyPgStdcall Stdcall]]## calling convention to procedures, preserve the case of all names declared within them and on DOS/Windows platforms, append a ##"@//N//"## suffix to procedure names, where ##//N//## is the total size in bytes of any procedure parameters. ##**Extern """Windows-MS"""**## blocks are exactly like ##**Extern """Windows"""**## blocks but do not append the ##"@//N//"## suffix to procedure names in DOS/Windows platforms. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/module/extern-block.bas"}}%%(freebasic) extern "C" '' This procedure uses the CDECL convention and is seen externally '' as "SomeProcedure". declare sub SomeProcedure ( byval as integer ) end extern extern "C++" '' This procedure uses the CDECL convention and its name is mangled '' compatible to that of g++-4.x. declare function AnotherProcedure ( byval as integer ) as integer End Extern extern "Windows" '' This procedure uses the STDCALL convention and is seen externally '' as "YetAnotherProcedure@4" on DOS/Windows platforms, and '' "YetAnotherProcedure" on Linux platforms. declare function YetAnotherProcedure ( byval as integer ) as integer end extern %% {{fbdoc item="lang"}} - ##**Extern**## blocks are only available in the //[[CompilerOptlang -lang fb]]// dialect. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="target"}} - In Linux platforms, ##**Extern "Windows"**## blocks never append a ##"@//N//"## suffix to procedure names. {{fbdoc item="see"}} - ##[[KeyPgCdecl Cdecl]]## - ##[[KeyPgStdcall Stdcall]]## - ##[[KeyPgExtern Extern]]## {{fbdoc item="back" value="CatPgModularizing|Modularizing"}} {{fbdoc item="title" value="FIELD"}}---- Specifies alignment. {{fbdoc item="syntax"}}## [[KeyPgType Type]] //typename// **Field** = { 1 | 2 | 4 } ... End [[KeyPgType Type]] ## {{fbdoc item="desc"}} A ##[[KeyPgType Type]]## variable has its fields aligned to the word length of the system, 4 bytes presently. ##**Field**## modifies the default alignment to one byte (##**Field**## 1) or two bytes (##**Field**## 2). This helps ""FreeBASIC"" maintain compatibility with structures created in other languages. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/udt/field.bas"}}%%(freebasic) type bitmap_header field = 1 bfType as ushort bfsize as uinteger bfReserved1 as ushort bfReserved2 as ushort bfOffBits as uinteger biSize as uinteger biWidth as uinteger biHeight as uinteger biPlanes as ushort biBitCount as ushort biCompression as uinteger biSizeImage as uinteger biXPelsPerMeter as uinteger biYPelsPerMeter as uinteger biClrUsed as uinteger biClrImportant as uinteger end type dim bmp_header as bitmap_header 'Open up bmp.bmp and get its header data: 'Note: Will not work without a bmp.bmp to load . . . open "bmp.bmp" for binary as #1 get #1, , bmp_header close #1 print bmp_header.biWidth, bmp_header.biHeight sleep %% {{fbdoc item="lang"}} -In the //[[CompilerOptlang -lang qb]]// dialect, the ##**Field**## alignment is always one, no padding is ever done, as in QB. {{fbdoc item="diff"}} - In QB ##**Field**## was used to define fields in a file buffer at run time. This feature is not implemented in FB, so the keyword has been redefined. To define fields in a file buffer, ##**[[KeyPgType Type]]s**## must be used. {{fbdoc item="see"}} - ##[[KeyPgType Type]]## {{fbdoc item="back" value="CatPgUserDefTypes|User Defined Types"}}{{fbdoc item="title" value="FILEATTR"}}---- Returns information about an open file number {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""FileAttr""** ( [[KeyPgByval byval]] //filenum// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByval byval]] //returntype// [[KeyPgAs as]] [[KeyPgInteger integer]] = 1 ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## #include "file.bi" //result// = **""FileAttr""** ( //filenum//, [ //returntype// ] ) ## //or// ## #include "vbcompat.bi" //result// = **""FileAttr""** ( //filenum//, [ //returntype// ] ) ## {{fbdoc item="param"}} ##//filenum//## The file number of a file or device opened with ##[[KeyPgOpen Open]]## ##//returntype//## An ##[[KeyPgInteger integer]]## indicating the type of information to return. {{fbdoc item="ret"}} A value associated with the return type, otherwise 0 on error. {{fbdoc item="desc"}} Information about the file number is returned based on the supplied ##//returntype//## {{table columns="3" cellpadding="1" cells="Value;Description;constant;1;File Mode;fbFileAttrMode;2;File Handle;fbFileAttrHandle;3;Encoding;fbFileAttrEncoding"}} For File Mode, ##//returntype//## = 1 (##fbFileAttrMode##) the return value is the sum of one or more of the following values: {{table columns="3" cellpadding="1" cells="Value;File Mode;Constant;1;Input;fbFileModeInput;2;Output;fbFileModeOutput;4;Random;fbFileModeRandom;8;Append;fbFileModeAppend;32;Binary;fbFileModeBinary"}} For File Handle, ##//returntype//## = 2 (##fbFileAttrHandle##), the return value is the file handle as supplied by the C Runtime for file-type devices. On Windows only: For File Handle, ##//returntype//## = 2 (##fbFileAttrHandle##), the value returned for COM devices is the handle returned by ##""CreateFile""()## when the device was first opened. The value returned for LPT devices is the handle returned by ##""OpenPrinter""()## when the device was first opened. This handle value can be passed to other Windows API functions. On Linux only: For File Handle, ##//returntype//## = 2 (##fbFileAttrHandle##), the value returned for COM devices is the file descriptor returned by open() when the device was first opened. For Encoding, ##//returntype//## = 3 (##fbFileAttrEncoding##), the return value is one of the following values: {{table columns="3" cellpadding="1" cells="Value;Encoding;Constant;0;Ascii;fbFileEncodASCII;1;UTF-8;fbFileEncodUTF8;2;UTF-16;fbFileEncodUTF16;3;UTF-32;fbFileEncodUTF32"}} {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/system/fileattr.bas"}}%%(freebasic) #include "vbcompat.bi" #include "crt.bi" dim f as FILE ptr, i as integer '' Open a file and write some text to it open "test.txt" for output as #1 f = cast( FILE ptr, FileAttr( 1, fbFileAttrHandle )) for i = 1 to 10 fprintf( f, !"Line %i\n", i ) next i close #1 '' re-open the file and read the text back open "test.txt" for input as #1 f = cast( FILE ptr, FileAttr( 1, fbFileAttrHandle )) while feof(f) = 0 i = fgetc(f) print chr(i); wend close #1 %% {{fbdoc item="diff"}} - None for ##//returntype//## = 1 - QBasic and 16-bit Visual Basic returned DOS file handle for ##//returntype//## = 2 - ##//returntype//## = 3 is new to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgOpen Open]]## {{fbdoc item="back" value="CatPgOpsys|Operating System Functions"}}{{fbdoc item="title" value="FILECOPY"}}---- Copies a file {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""FileCopy""** ( //source// [[KeyPgAs as]] [[KeyPgString string]], //destination// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## #include "file.bi" **""FileCopy""** //source//, //destination// ## //or// ## #include "vbcompat.bi" **""FileCopy""** //source//, //destination// ## {{fbdoc item="param"}} ##//source//## A ##[[KeyPgString string]]## argument specifying the filename of the file to copy from. This file must exist. ##//destination//## A ##[[KeyPgString string]]## argument specifying the filename of the file to copy to. This file will be overwritten if it exists. This file should not be currently referenced by any open file handles. {{fbdoc item="desc"}} Copies the contents of the source file into the destination file, overwriting the destination file if it already exists. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/system/filecopy.bas"}}%%(freebasic) #include "file.bi" FILECOPY "source.txt", "destination.txt" %% {{fbdoc item="target"}} - Linux requires the //filename// case matches the real name of the file. Windows and DOS are case insensitive. - Path separators in Linux are forward slashes / . Windows uses backward slashes \ but it allows for forward slashes . DOS uses backward \ slashes. {{fbdoc item="diff"}} - New to FreeBASIC. Existed in Visual Basic. {{fbdoc item="see"}} {{fbdoc item="back" value="CatPgOpsys|Operating System Functions"}}{{fbdoc item="title" value="FILEDATETIME"}}---- Returns the last modified date and time of a file as [[ProPgDates Date Serial]] {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""FileDateTime""**( [[KeyPgByval byval]] //filename// [[KeyPgAs as]] [[KeyPgZstring zstring]] [[KeyPgPtr ptr]] ) [[KeyPgAs as]] [[KeyPgDouble double]] ## {{fbdoc item="usage"}}## #include "file.bi" //result// = **""FileDateTime""** ( //filename// ) ## //or// ## #include "vbcompat.bi" //result// = **""FileDateTime""** ( //filename// ) ## {{fbdoc item="param"}} ##//filename//## Filename to retrieve date and time for. {{fbdoc item="ret"}} Returns a [[ProPgDates Date Serial]]. {{fbdoc item="desc"}} Returns the file's last modified date and time as [[ProPgDates Date Serial]]. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/system/filedatetime.bas"}}%%(freebasic) #include "vbcompat.bi" dim filename as string, d as double print "Enter a filename: " line input filename if fileexists( filename ) then print "File last modified: "; d = Filedatetime( filename ) print Format( d, "yyyy-mm-dd h:MM AM/PM" ) else print "File not found" end if %% {{fbdoc item="target"}} - Linux requires the //filename// case matches the real name of the file. Windows and DOS are case insensitive. - Path separators in Linux are forward slashes / . Windows uses backward slashes \ but it allows for forward slashes . DOS uses backward \ slashes. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - [[ProPgDates Date Serials]] {{fbdoc item="back" value="CatPgOpsys|Operating System Functions"}}{{fbdoc item="title" value="FILEEXISTS"}}---- Tests the existence of a file {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""FileExists""**( [[KeyPgByval byval]] //filename// [[KeyPgAs as]] [[KeyPgZstring zstring]] [[KeyPgPtr ptr]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## #include "file.bi" //result// = **""FileExists""** ( //filename// ) ## //or// ## #include "vbcompat.bi" //result// = **""FileExists""** ( //filename// ) ## {{fbdoc item="param"}} ##//filename//## Filename to test for existence. {{fbdoc item="ret"}} Returns non-zero (-1) if the file exists, otherwise returns zero (0). {{fbdoc item="desc"}} ##**""FileExists""**## tests for the existence of a file. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/system/fileexists.bas"}}%%(freebasic) #include "vbcompat.bi" dim filename as string print "Enter a filename: " line input filename if fileexists( filename ) then print "File found: " & filename else print "File not found: " & filename end if %% {{fbdoc item="target"}} - Linux requires the //filename// case matches the real name of the file. Windows and DOS are case insensitive. - Path separators in Linux are forward slashes / . Windows uses backward slashes \ but it allows for forward slashes . DOS uses backward \ slashes. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDir Dir]]## {{fbdoc item="back" value="CatPgOpsys|Operating System Functions"}}{{fbdoc item="title" value="FILELEN"}}---- Finds the length of a file given its filename {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""FileLen""** ( //filename// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgLongint longint]] ## {{fbdoc item="usage"}}## #include "file.bi" //result// = **""FileLen""**(//filename//) ## //or// ## #include "vbcompat.bi" //result// = **""FileLen""**(//filename//) ## {{fbdoc item="param"}} ##//filename//## A ##[[KeyPgString string]]## argument specifying the filename of the file whose length to return. {{fbdoc item="desc"}} Returns the size in bytes of the file specified by //filename//. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/system/filelen.bas"}}%%(freebasic) #include "file.bi" dim length as integer length = FILELEN("file.txt") %% {{fbdoc item="target"}} - Linux requires the //filename// case matches the real name of the file. Windows and DOS are case insensitive. - Path separators in Linux are forward slashes / . Windows uses backward slashes \ but it allows for forward slashes . DOS uses backward \ slashes. {{fbdoc item="diff"}} - New to FreeBASIC. Existed in Visual Basic. {{fbdoc item="see"}} - ##[[KeyPgLof Lof]]## {{fbdoc item="back" value="CatPgOpsys|Operating System Functions"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:53:31 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 3615707168d073e3bdeb4d5e90738cfd Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 1157 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="FIX"}}---- Returns the integer part of a number {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Fix** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgDouble double]] ) [[KeyPgAs as]] [[KeyPgDouble double]] ## {{fbdoc item="usage"}}## //result// = **Fix** ( //number// ) ## {{fbdoc item="param"}} ##//number//## the decimal number to truncate {{fbdoc item="ret"}} Returns the integer part of a number. {{fbdoc item="desc"}} Equivalent to: ##[[KeyPgSgn Sgn]](//number//) * [[KeyPgInt Int]]([[KeyPgAbs Abs]](//number//))##. The ##**Fix**## unary ##[[KeyPgOperator operator]]## can be overloaded with user defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/math/fix.bas"}}%%(freebasic) Print fix(1.9) '' will print 1 Print fix(-1.9) '' will print -1 %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgInt Int]]## - ##[[KeyPgCint Cint]]## - ##[[KeyPgOperator Operator]]## {{fbdoc item="back" value="CatPgMath|Math"}} {{fbdoc item="title" value="FLIP"}}---- Changes the current video display page {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Flip** ( [[KeyPgByval byval]] //frompage// [[KeyPgAs as]] [[KeyPgInteger integer]] = -1, [[KeyPgByval byval]] //topage// [[KeyPgAs as]] [[KeyPgInteger integer]] = -1 ) ## {{fbdoc item="usage"}}## **Flip** [ //frompage// ] [, //topage// ] ## {{fbdoc item="param"}} ##//frompage//## previous page ##//topage//## new page to display {{fbdoc item="desc"}} In normal graphics mode, ##**Flip**## is an alias for ##[[KeyPgPcopy PCopy]]## and ##[[KeyPgScreencopy ScreenCopy]]##. See ##[[KeyPgScreencopy ScreenCopy]]## for details. In OpenGL mode, ##**Flip**## does a hardware page flip and displays the contents of the backbuffer. It is recommended that you call ##**Flip**## regularly while in OpenGL mode, otherwise your app may also become unresponsive. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/flip.bas"}}%%(freebasic) ScreenRes 320, 240, 32, 2 'Sets up the screen to be 320x240 in 32-bit color with 2 video pages. for n as integer = 50 to 270 ScreenSet 2,1 'Sets the working page to 2 and the displayed page to 1 Cls Circle (n, 50),50 ,rgb(255,255,0) 'Draws a circle with a 50 pixel radius in yellow on page 2 ScreenSet 1,1 'Sets the working page to 1 and the displayed page to 1 ScreenSync 'Waits for vertical refresh flip 2,1 'Copies our circle from page 2 to page 1 Sleep 25 next print "Now wasn't that neat!" print "Push any key." Sleep %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Flip""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="back" value="CatPgGfxScreen|Screen Functions"}}{{fbdoc item="title" value="FOR"}}---- Control flow statement, open statement clause, or operator depending on context. {{fbdoc item="syntax"}}## **For** //iterator// = //startvalue// To //endvalue// [ Step //increment// ] //or// Open [ //device// ] "//filename//" **For** //filemode// As #handle //or// declare operator **For** ( byref stp as [[DataType datatype]] ) ## {{fbdoc item="see"}} - ##[[KeyPgFornext For...Next]]## - ##[[KeyPgOpen Open]]## - ##[[KeyPgOperator Operator]]## {{fbdoc item="back" value="CatPgMisc|Miscellaneous"}} {{fbdoc item="title" value="FORMAT"}}---- Formats a number in a specified format {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Format** ( [[KeyPgByval byval]] //numerical_expression// [[KeyPgAs as]] [[KeyPgDouble double]], //formatting_expression// [[KeyPgAs as]] [[KeyPgString string]] = "" ) [[KeyPgAs as]] [[KeyPgString string]] ## {{fbdoc item="usage"}}## #include "vbcompat.bi" //result// = **Format**[$]( //numerical_expression//, //formatting_expression// ) ## {{fbdoc item="param"}} ##//numerical_expression//## number to format ##//formatting_expression//## formatting pattern pattern {{fbdoc item="ret"}} ##**Format**## returns a string with the result of the numerical expression formatted as indicated in the formatting expression. The formatting expression is a string that can yield numeric or date-time values. {{fbdoc item="desc"}} To recover meaningful date-time values the numerical expression must be a date serial obtained from the appropriate functions. This function is part of FreeBASIC, however it is not recognized by the compiler unless ##vbcompat.bi## is included. "Numeric Formats" {{table columns="2" cellpadding="1" cells="Symbol ; Description; Null string; General format (no formatting);0; Digit placeholder: If the number has fewer digits than there are zeros (on either side of the decimal) in the format expression, leading or trailing zeros are displayed. If there are more digits to the right of the decimal than zeros in the format, the number is rounded. If there are more digits to the left of the decimal than zeros in the format the digits are all displayed ; #; Digit placeholder: Follows the same rules as for the 0 digit except the leading or trailing zeros are not displayed;.; Placeholder for decimal point.If the format contains only #'s to the left of . then numbers smaller than 1 are begun with a decimal point.; % ; Percentage :The expression is multiplied by 100 and the % character is inserted.;,; Thousands separator. Two adjacent commas, or a comma immediately to the left of the decimal point location (whether there is a decimal specified or not) means 'Omit the three digits that fall between these commas, or between the comma and the decimal point, rounding as needed.' ; E- E+ e- e+ ;Scientific format: If a format contains one digit placeholder (0 or #) to the right of an E-, E+, e-, or e+, the number is displayed in scientific format and an E or e is inserted between the number and its exponent.The number of 0's or #'s to the right determines the number of digits in the exponent. Use E- or e- to place a minus sign next to negative exponents. Use a E+ or e+ to place a minus sign next to negative exponents and a plus sign next to positive exponents.; : ? + $ () space; Display literal character To display a character other than one of these, precede the character with a backslash (\) or enclose the character(s) in double quotation marks;\; Display next character in format string as it is ;text between double quotes; Displays the text inside the double quotes.; :; Time separator is used to separate hours, minutes, and seconds when time values are formatted.; /; The date separator is used to separate day,month, and year when date values are formatted."}} "Date-Time formats:" {{table columns="2" cellpadding="1" cells="Symbol ; Description;d; Display the day as a number without leading zeros (1-31);dd; Display the day as a number with leading zeros (01-31);ddd; Display the day as an abbreviation (Sun-Sat);dddd; Display the day as a full name (Sunday-Saturday);ddddd; Display a serial date number as a complete date (including day, month, and year);m; Display the month as a number without leading zeros (1-12) if used immediately following h or hh, the minute rather than the month is displayed;mm ; Display the month as a number with leading zeros (01-12) if used immediately following h or hh, the minute rather than the month is displayed;mmm; Display the month as an abbreviation (Jan-Dec);mmmm; Display the month as a full name (January-December);y;Display the year as a two-digit number (00-99);yyyy; Display the year as a four-digit number (1900-2040);h; Display the hour as a number without leading zeros (0-23);hh;Display the hour as a number with leading zeros (00-23);m; Display the minute as a number without leading zeros (0-59) if not used immediately following h or hh, the month rather than the minute is displayed;mm; Display the minute as a number with leading zeros (00-59) if not used immediately following h or hh, the month rather than the minute is displayed.;s; Display the second as a number without leading zeros (0-59);ss; Display the second as a number with leading zeros (00-59);ttttt; Display a time serial number as a complete time, including hour, minute, and second;AM/PM (Default) am/pm; Use the 12-hour clock displaying AM or am with am/pm any hour before noon, PM or pm with any hour between noon and 11:59;A/P a/p; Use the 12-hour clock displaying A or a with any hour before noon, P or p with any hour between noon and 11:59 "}} {{fbdoc item="ex"}} %% Sample numeric formats Format (fmt) 5 -5 .5 Null String 5 -5 0.5 0 5 -5 1 0.00 5.00 -5.00 0.50 #,##0 5 -5 1 #,##0.00 5.00 -5.00 0.50 $#,##0;($#,##0) $5 ($5) $1 $#,##0.00;($#,##0.00) $5.00 ($5.00) $0.50 0% 500% -500% 50% 0.00% 500.00% -500.00% 50.00% 0.00E+00 5.00E+00 -5.00E+00 5.00E-01 0.00E-00 5.00E00 -5.00E00 5.00E-01 Sample Date And Time Formats The following are examples of Date And Time formats: Format Expression Display m/d/yy 12/7/58 d-mmmm-yy 7-December-58 d-mmmm 7-December mmmm-yy December-58 h:mm AM/PM 8:50 PM h:mm:ss AM/PM 8:50:35 PM h:mm 20:50 h:mm:ss 20:50:35 m/d/yy h:mm 12/7/58 20:50 %% {{fbdoc item="lang"}} - The string type suffix "$" is obligatory in the //[[CompilerOptlang -lang qb]]// dialect. - The string type suffix "$" is optional in the //[[CompilerOptlang -lang fblite]]// and //[[CompilerOptlang -lang fb]]// dialects. {{fbdoc item="diff"}} - Does not exist in QB 4.5. This function appeared first in PDS 7.1 {{fbdoc item="see"}} - ##[[KeyPgPrintusing Print Using]]## - ##[[KeyPgStr Str]]## {{fbdoc item="back" value="CatPgString|String Functions"}}{{fbdoc item="title" value="FOR...NEXT"}}---- Control flow statement for looping {{fbdoc item="syntax"}}## **For** //iterator// [ [[KeyPgAs as]] [[DataType datatype]] ] = //startvalue// **To** //endvalue// [ **Step** //stepvalue// ] [ //statement block// ] **Next** [ //iterator// ] ## {{fbdoc item="param"}} ##//iterator//## a variable identifier that is used to iterate from an initial value to an end value ##//datatype//## If specified, the variable ##//iterator//## will automatically be declared with the type ##//datatype//##. ##//startvalue//## an expression that denotes the starting value of the iterator ##//endvalue//## an expression used to compare with the value of the iterator ##//stepvalue//## an expression that is added to the iterator after every iteration {{fbdoc item="desc"}} A ##**For...Next**## loop initializes ##//iterator//## to ##//startvalue//##, then executes the ##//statement block//##'s, incrementing ##//iterator//## by ##//stepvalue//## until it reaches ##//endvalue//##. If ##//stepvalue//## is not explicitly given it will set to 1. The //iterator// may be defined having the same scope as the ##**For**## statement by using the ##[[KeyPgAs as]] [[DataType datatype]]## syntax. With this syntax, //iterator// is created and destroyed within the ##**For...Next**## scope. See dialect differences below. The ##**For**## statement causes the execution of the statements in the ##//statement block//## until ##//iterator//## compares **greater than** ##//endvalue//##. ##//iterator//## will be incremented the amount of ##//stepvalue//## following each execution of the ##//statement block//##. If an increment is not given, ##//iterator//## will be implicitly incremented by 1. If ##//endvalue//## is less than ##//startvalue//## then a negative ##//stepvalue//## must be specified or the ##//statement block//## will not execute at all, since ##//startvalue//## compares greater than ##//endvalue//##. If an ##[[KeyPgExit Exit]]## ##**For**## statement is encountered inside the ##//statement block//##, the loop is terminated, and execution resumes immediately following the enclosing ##**Next**## statement. If a ##[[KeyPgContinue Continue]]## ##**For**## statement is encountered, the rest of the ##//statement block//## is skipped and execution resumes at the FOR statement. Like all control flow statements, the ##**For**## statement can be nested, that is, it can be used in a statement block of another ##**For**## statement. After initial evaluation, the ##//increment//## is stored internally, and thus cannot be changed for subsequent executions. **note**: When a negative ##//increment//## is specified, the ##**For**## statement loops until ##//iterator//## compares //less than// ##//end_value//##. //For//, //Next//, and //Step// are operators that can be overloaded inside user defined types. See [[KeyPgOpFor Operator For]], [[KeyPgOpNext Operator Next]], [[KeyPgOpStep Operator Step]] {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/control/for-next.bas"}}%%(freebasic) Dim i As Single Print "counting from 3 to 0, with a step of -0.5" For i = 3 To 0 Step -0.5 Print "i is " & i Next i %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// and //[[CompilerOptlang -lang fblite]]// dialects, variables declared inside a FOR..NEXT loop have a function-wide [[ProPgVariableScope scope]] as in QB - In the //[[CompilerOptlang -lang fb]]// and //[[CompilerOptlang -lang deprecated]]// dialects, variables declared inside a ##**For**##..##**Next**## block are visible only inside the block, and can't be accessed outside it. {{fbdoc item="diff"}} - ##[[KeyPgByref Byref]]## arguments cannot be used as counters. {{fbdoc item="see"}} - ##[[KeyPgContinue Continue]]## - ##[[KeyPgDoloop Do...Loop]]## - ##[[KeyPgExit Exit]]## {{fbdoc item="back" value="CatPgControlFlow|Control Flow"}}{{fbdoc item="title" value="FRAC"}}---- Returns the decimal part of a number {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Frac** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgDouble double]] ) [[KeyPgAs as]] [[KeyPgDouble double]] ## {{fbdoc item="usage"}}## //result// = **Frac** ( //number// ) ## {{fbdoc item="param"}} ##//number//## the number or expression to get the fraction part of. {{fbdoc item="ret"}} Returns the fractional part of a number or expression. {{fbdoc item="desc"}} Equivalent to: ##(//number// - [[KeyPgFix Fix]](//number//))##. The ##**Frac**## unary ##[[KeyPgOperator operator]]## can be overloaded with user defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/math/frac.bas"}}%%(freebasic) Print frac(10.625) '' will print 0.625 Print frac(-10.625) '' will print -0.625 %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgFix Fix]]## - ##[[KeyPgOperator Operator]]## {{fbdoc item="back" value="CatPgMath|Math"}}{{fbdoc item="title" value="FRE"}}---- Returns the amount of free memory available {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Fre** ( [[KeyPgByval byval]] //value// [[KeyPgAs as]] [[KeyPgInteger integer]] = 0 ) [[KeyPgAs as]] [[KeyPgUinteger uinteger]] ## {{fbdoc item="usage"}}## //result// = **Fre**( [ //value// ] ) ## {{fbdoc item="param"}} ##//value//## Unused dummy parameter kept for backward compatibility; can be ignored. {{fbdoc item="ret"}} Returns the amount of free memory, in bytes. {{fbdoc item="desc"}} Returns the free memory (ram) available, in bytes. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/system/fre.bas"}}%%(freebasic) Dim mem As Integer = Fre Print "Free memory:" Print Print mem; " bytes" Print mem \ 1024; " kilobytes" Print mem \ (1024 * 1024); " megabytes" %% {{fbdoc item="diff"}} - The "value" argument is not checked, ##**Fre**## will always return the free physical memory available {{fbdoc item="see"}} - ##[[KeyPgDim Dim]]## - ##[[KeyPgRedim Redim]]## - ##[[KeyPgAllocate Allocate]]## {{fbdoc item="back" value="CatPgOpsys|Operating System Functions"}}{{fbdoc item="title" value="FREEFILE"}}---- Returns a free file number {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Freefile** ( ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **Freefile** ## {{fbdoc item="ret"}} The next available file number. {{fbdoc item="desc"}} Returns the number of the next free file number. This value is a required argument to ##[[KeyPgOpen Open]]## a file. ##**Freefile**## is useful when opening files in complex programs where the programmer can't keep track of the used file numbers. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/fileio/freefile.bas"}}%%(freebasic) ' Create a string and fill it. Dim buffer As String, f as integer buffer = "Hello World within a file." ' Find the first free file number. f = Freefile ' Open the file "file.ext" for binary usage, using the file number "f". Open "file.ext" For Binary As #f ' Place our string inside the file, using file number "f". Put #f, , buffer ' Close the file. Close ' End the program. (Check the file "file.ext" upon running to see the output.) End %% When using multiple ##**Freefile**## statements, ##**Freefile**## should be used immediately before the ##[[KeyPgOpen Open]]## statement: {{fbdoc item="filename" value="examples/manual/fileio/freefile-good.bas"}}%%(freebasic) dim fr as integer, fs as integer ' The CORRECT WAY: fr = FREEFILE OPEN "File1" FOR INPUT AS #fr fs = FREEFILE OPEN "file2" FOR INPUT AS #fs %% As opposed to: {{fbdoc item="filename" value="examples/manual/fileio/freefile-bad.bas"}}%%(freebasic) dim fr as integer, fs as integer ' The WRONG way: fr = FREEFILE fs = FREEFILE OPEN "file1" FOR INPUT AS #fr OPEN "file2" FOR INPUT AS #fs %% {{fbdoc item="target"}} - On Windows, a file number used in a dynamic link library is not the same as an identical file number used in the main program. File numbers can not be passed or returned and then used between a DLL and an executable. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgOpen Open]]## - ##[[KeyPgPutfileio Put (File I/O)]]## - ##[[KeyPgGetfileio Get (File I/O)]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}}{{fbdoc item="title" value="FUNCTION"}}---- Defines a procedure returning a value {{fbdoc item="syntax"}}## [[[KeyPgPublic Public]]|[[KeyPgPrivate Private]]] **Function** //identifier// [[[KeyPgCdecl CDecl]]|[[KeyPgPascal Pascal]]|[[KeyPgStdcall StdCall]]] [[[KeyPgOverload Overload]]] [[[KeyPgAlias Alias]] //external_identifier//] [([//parameter_list//])] [[[KeyPgAs As]] //return_type//] [[[KeyPgStatic Static]]] [[[KeyPgExport Export]]] //statements// ... { {[[KeyPgReturn Return]] [//return_value//]}|{Function = //return_value//}|{//identifier// = //return_value//} } ... [[KeyPgEndblock End]] Function ## {{fbdoc item="param"}} ##//identifier//##: the name of the function ##//external_identifier//##: externally visible (to the linker) name enclosed in quotes ##//parameter_list//##: ##//parameter//[, //parameter//[, ...]]## ##//parameter//##: ##[[[KeyPgByref ByRef]]|[[KeyPgByval ByVal]]] //identifier// [[[KeyPgAs As]] //type//] [= //default_value//]## ##//identifier//##: the name of the variable referenced in the function. If the argument is an array then the identifier must be followed by an empty parenthesis. ##//type//##: the type of variable ##//default_value//##: the value of the argument if none is specified in the call ##//return_type//##: the type of variable returned by the function ##//statements//##: one or more statements that make up the function body ##//return_value//##: the value returned from the function {{fbdoc item="desc"}} A function defines a block of code which can be executed with a single statement (a function call), and provide a value back to the caller when finished (a return value). There are several reasons to use functions: - Reduces redundancy in your program - Enables reuse of code in many programs - Improves readability of the program - Improves maintainability of the program - Makes it easy to extend your program //Access Rights// : The ##[[KeyPgPublic Public]]## and ##[[KeyPgPrivate Private]]## keywords specify public or private intra module-level access rights, respectively. If neither is given, the function defaults to public access (##[[KeyPgPublic Public]]##). //Calling Convention// : Calling convention, or the order in which arguments are pushed and popped from the stack during function calls, is specified with the ##[[KeyPgCdecl CDecl]]##, ##[[KeyPgPascal Pascal]]## and ##[[KeyPgStdcall StdCall]]## keywords. If none is given, the function uses the standard convention by default (##[[KeyPgStdcall StdCall]]##). //Passing Arguments// : Functions may receive one or more variables, or arguments, when called. These arguments are listed as ##//parameters//## in the ##//parameter_list//##. The ##[[KeyPgByref ByRef]]## and ##[[KeyPgByval ByVal]]## keywords specify whether the argument will be passed by reference or by value, respectively. The argument's type is given by "##[[KeyPgAs As]] //type//##" following the ##//parameter//##. If a parameter in the declaration is given a default value, the parameter is optional. Array parameters are specified by following an identifier with an empty parenthesis. Note that array parameters are always ##[[KeyPgByref ByRef]]## and the ##[[KeyPgByref ByRef]]## keyword is neither required nor allowed for array parameters. When calling a function with an array argument the parenthesis must be supplied there too; see the examples. //Overloaded Functions// : An overloaded function may share the same name (##//identifier//##) as another with a different signature. The ##[[KeyPgOverload Overload]]## keyword specifies that a function may be overloaded. A function must be defined - or declared - using the ##[[KeyPgOverload Overload]]## keyword prior to any functions that overload them. //Returning values// : ##//return_type//## specifies the ##[[DataType data type]]## returned by a function upon exit. If no data type is specified, then the function will return the default data type, which will be Integer unless set to another data type using ##[[KeyPgDefsng DefSng]]##, ##[[KeyPgDefdbl DefDbl]]##, ##[[KeyPgDefstr DefStr]]##, etc. Functions can return values //(and soon, references)// using three methods: the ##[[KeyPgReturn Return]]## keyword followed by a value exits the function immediately, and returns that value to the caller. Functions can also return values by assigning the Function keyword or the function's ##//identifier//## to the desired return value. The latter two methods do not cause the function to exit, however. Since functions return values, function calls evaluate to expressions. Thus, function calls can be made wherever an expression is expected, like in [[KeyPgOpAssignment assignments]] or ##[[KeyPgIfthen If]]## statements. //Local Variable Preservation// : The ##[[KeyPgStatic Static]]## keyword specifies that a function's locally declared variables are preserved between function calls. Upon entering a function defined with ##[[KeyPgStatic Static]]##, local variables have the same value as when the function was last called. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/procs/func-1.bas"}}%%(freebasic) 'This program demonstrates the declaration of a function and said function returning a value. Declare Function ReturnTen () as integer Print ReturnTen () 'ReturnTen returns an integer by default. Function ReturnTen() as integer Return 10 End Function %% {{fbdoc item="filename" value="examples/manual/procs/func-2.bas"}}%%(freebasic) 'This program demonstrates the declaration of a function and said function returning a value. Declare Function ReturnTen () as integer Print ReturnTen () 'ReturnTen returns an integer by default. Function ReturnTen() as integer ReturnTen = 10 End Function %% {{fbdoc item="filename" value="examples/manual/procs/func-3.bas"}}%%(freebasic) 'This program demonstrates function overloading. 'The overloaded functions must be FIRST. Declare Function ReturnTen Overload (a As Double) as integer Declare Function ReturnTen Overload (a As String) as integer Declare Function ReturnTen (a as integer) as integer Print ReturnTen (10.000!) 'ReturnTen will take a double and return an int. Print ReturnTen (10) 'ReturnTen will take an int and return an int. Print ReturnTen ("10") 'ReturnTen will take a string and return an int. Function ReturnTen Overload (a As Double) as integer Return Int(a) End Function Function ReturnTen Overload (a As String) as integer Return Val(a) End Function Function ReturnTen (a As Integer) as integer Return a End Function %% {{fbdoc item="filename" value="examples/manual/procs/func-4.bas"}}%%(freebasic) ' The following demonstrates optional parameters. Function TestFunc(P As String = "Default") As String Return P End Function Print TestFunc("Testing:") Print TestFunc %% This example shows how to declare and call functions that take array arguments. {{fbdoc item="filename" value="examples/manual/procs/func-5.bas"}}%%(freebasic) Function x(b() As Double) As Integer x = UBound(b)-LBound(b)+1 End Function Dim a(1 To 10) As Double Print x(a()) Dim c(10 To 20) As Double Print x(c()) %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang fb]]// dialect, ##**Byval**## is the default parameter passing convention for all built-in types except ##[[KeyPgString String]]##; String and user-defined ##[[KeyPgType Type]]##s are passed ##[[KeyPgByref Byref]]## by default. - In the //[[CompilerOptlang -lang qb]]// and //[[CompilerOptlang -lang fblite]]// dialects, ##**Byref**## is the default parameter passing convention. - In the //[[CompilerOptlang -lang qb]]//, the name of the function must be used in an assignment to specify the return value. Using ##function## or ##return## to specify the return value may not be used. - In the //[[CompilerOptlang -lang fb]]// dialect the parameters are passed ##[[KeyPgByval ByVal]]## by default. //[[CompilerOptlang -lang qb]]// and //[[CompilerOptlang -lang fblite]]// dialects keep the QB convention: parameters are ##[[KeyPgByref ByRef]]## by default. {{fbdoc item="diff"}} - Parameters can be optional in FreeBASIC. - Return value can now be specified by a ##[[KeyPgReturn Return]]## statement - Function overloading supported. - The return value can be ignored in the calling code. {{fbdoc item="see"}} - ##[[KeyPgDeclare Declare]]## - ##[[KeyPgSub Sub]]## - ##[[KeyPgExit Exit]]## - ##[[KeyPgPublic Public]]## - ##[[KeyPgPrivate Private]]## {{fbdoc item="back" value="CatPgProcedures|Procedures"}}{{fbdoc item="title" value="GET (File I/O)"}}---- Reads data from a file to a buffer {{fbdoc item="syntax"}}## **Get** #//filenum// [[KeyPgAs As]] [[KeyPgInteger Integer]], [//position// [[KeyPgAs As]] [[KeyPgLongint longint]]], //data// [[KeyPgAs As]] [[KeyPgAny Any]] [, //amount// [[KeyPgAs As]] [[KeyPgInteger Integer]]] **Get** #//filenum// [[KeyPgAs As]] [[KeyPgInteger Integer]], [//position// [[KeyPgAs As]] [[KeyPgLongint longint]]], //data()// [[KeyPgAs As]] [[KeyPgAny Any]] ## {{fbdoc item="usage"}}## **Get** #//filenum//, //position//, //data// [, //amount//] varres = **Get** (#//filenum//, //position//, //data// [, //amount//]) ## {{fbdoc item="param"}} ##//filenum//## The value passed to ##[[KeyPgOpen Open]]## when the file was opened ##//position//## The position where the read must start. If the file was opened ##For Random##, the position is in records; otherwise, it is in bytes. If omitted, read starts at the present file pointer position. The position is 1 based: the first record or byte of a file is at position 1. ##//data//## The buffer where data is written. It can be a numeric variable, a string, an array, a user defined type or a dereferenced pointer. The read operation will try to fill completely the variable, unless //amount// is given or the ##[[KeyPgEof EOF]]## is reached. Note: If you want to read values into a buffer, you should NOT pass a pointer to the buffer; instead you should pass the first variable in the buffer. (This can be done by dereferencing the pointer with ##[[KeyPgOpValueOf Operator * (Value of)]]##.) Get will automatically infer that the rest of the buffer continues after the first variable. If you pass a pointer, then ##**Get**## will overwrite the pointer, not the memory it points to. ##//amount//## Limits ##**Get**## to read read ##//amount// * [[KeyPgSizeof Sizeof]](//datatype//)## bytes of data. If ##//amount//## is omitted it defaults to 1, and ##Get## reads one variable of the buffer's data type. {{fbdoc item="ret"}} 0 on success; nonzero on error. {{fbdoc item="desc"}} Reads binary data from a file to a buffer variable ##**Get**## can be used as a function, and will return 0 on success or an error code on failure. For files opened in ##[[KeyPgRandom Random]]## mode, the size in bytes of the data to read must match the specified record size. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/fileio/get.bas"}}%%(freebasic) dim buffer as integer dim an_array(0 to 9) as integer dim pmem as integer ptr dim f as integer dim x as integer ' Find the first free file file number. f = freefile ' Open the file "file.ext" for binary usage, using the file number "f". open "file.ext" for binary as #f ' Read 4 bytes from the file into buffer, using file number "f". get #f, , buffer ' print out result print buffer ' Read 40 (10 * 4) bytes from the file into an_array, using file number "f". get #f, , an_array() ' print out result for x = 0 to 9 print an_array(x) next ' allocate memory for 5 integers pmem = allocate(5 * sizeof(integer)) ' Read 5 integers from the file into allocated memory get #f,, *pmem, 5 ' Note pmem must be dereferenced (*pmem) ' print out result using [] Pointer Indexing or pointer arithmic for x = 0 to 4 print pmem[x] ; *(pmem + x) next ' Close the file. close #f end %% {{fbdoc item="filename" value="examples/manual/fileio/get-file.bas"}}%%(freebasic) ' Load a small text file to a string Function LoadFile(f As string) As String Dim h As Integer Dim txt As String h = FreeFile Open f For Binary Access Read As #h If Lof(h) > 0 Then txt = String(Lof(h),0) Get #h,,txt End If Close #h Return txt End Function Dim ExampleStr As String ExampleStr = LoadFile("smallfile.txt") Print ExampleStr %% {{fbdoc item="diff"}} - GET can read full arrays as in VB or, alternatively, read a multiple of the data size into the memory. - GET can now be used as a function. {{fbdoc item="see"}} - ##[[KeyPgOpen Open]]## - ##[[KeyPgClose Close]]## - ##[[KeyPgPutfileio Put (File I/O)]]## - ##[[KeyPgFreefile Freefile]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}}{{fbdoc item="title" value="GET (GRAPHICS)"}}---- Gets a copy of a portion of the current work page or an image buffer {{fbdoc item="syntax"}}## **Get** [//source//,] [Step] (//x1//, //y1//) - [STEP] (//x2//, //y2//), //dest//] ## {{fbdoc item="param"}} ##//source//## the address of an image buffer. ##Step## indicates that the following co-ordinates are not absolute co-ordinates. ##//x1//##, ##//y1//## co-ordinates of the upper-left corner of the sub-image to copy. ##//x2//##, ##//y2//## co-ordinates of the lower-right corner of the sub-image to copy. ##//dest//## the address of a previously allocated buffer to store the image data. {{fbdoc item="desc"}} ##**Get**## copies a rectangular portion of the current work page specified by the co-ordinates (##//x1//##, ##//y1//##) and (##//x2//##, ##//y2//##), which represent the upper-left and lower-right corners of the rectangle, respectively. ##**Step**## specifies that the upper-left co-ordinates are relative to the current graphics pen location, and/or that the lower-right co-ordinates are relative to the upper-left co-ordinates. The new image buffer is formatted to match the current screen mode [[GfxInternalFormats pixel format]]. ##//dest//## can be an address, an [[ProPgArrays array]], or a reference to the first element in an [[ProPgArrays array]] that will receive the new image buffer. This memory must be sufficiently allocated to hold the image buffer; the number of bytes required varies with the [[CompilerOptlang -lang dialect]] used to compile the program. ##//source//## can be an address, an [[ProPgArrays array]], or a reference to the first element in an [[ProPgArrays array]] that holds an image buffer to retrieve a portion of. ##//x1//##, ##//y1//##, ##//x2//##, ##//y2//##, ##**Step**## and ##//dest//## have the same meaning in this case. The co-ordinates of the rectangle are affected by the most recent ##[[KeyPgWindow Window]]## and ##[[KeyPgViewgraphics View (Graphics)]]## statements, and must both be within the current clipping region set by ##[[KeyPgViewgraphics View (Graphics)]]##, otherwise an illegal function call runtime error will be triggered, and the function will have no effect. **Runtime errors:** ##**Get**## throws one of the following [[ProPgErrorHandling runtime errors]]: //(##1##) Illegal function call// - ##//dest//## is an array, but is not big enough to hold the image buffer. - The upper-left or lower-right co-ordinates of the rectangle are outside the current clipping region. See ##[[KeyPgViewgraphics View (Graphics)]]##. {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang fb]]// dialect, ##//dest//## receives a new-style image buffer, which consists of a 32-byte image header followed by pixel data which is row-padded to the next paragraph boundary (16 bytes). Use the following formula to calculate the total size, in bytes, required to store the image buffer, where ##w## and ##h## are the respective width and height of the rectangular portion of the current work page or source image buffer, and ##bpp## is the number of bytes per pixel of the current screen mode [[GfxInternalFormats pixel format]]: ##size = 32 + (((w * bpp + &hF) and not &hF) * h)## - In the //[[CompilerOptlang -lang qb]]// and //[[CompilerOptlang -lang fblite]]// dialects, ##//dest//## receives a QB-style image buffer, which consists of a 4-byte image header followed by pixel data which is not row-padded. Use the following formula to calculate the total size, in bytes, required to store the image buffer, where ##w## and ##h## are the respective width and height of the rectangular portion of the current work page or source image buffer, and ##bpp## is the number of bytes per pixel of the current screen mode [[GfxInternalFormats pixel format]]: ##size = 4 + (w * h * bpp)## {{fbdoc item="ex"}} For an example see ##[[KeyPgPutgraphics Put (Graphics)]]##. {{fbdoc item="see"}} - ##[[KeyPgPutgraphics Put (Graphics)]]## - ##[[KeyPgGetfileio Get (File I/O)]]## - ##[[KeyPgScreengraphics Screen (Graphics)]]## - ##[[KeyPgWindow Window]]## - ##[[KeyPgViewgraphics View (Graphics)]]## - [[GfxInternalFormats Internal pixel formats]] {{fbdoc item="back" value="CatPgGfx2D|2D Drawing Functions"}}{{fbdoc item="title" value="GETJOYSTICK"}}---- Reads buttons and axis information from attached gaming devices {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Getjoystick** ( [[KeyPgByval byval]] //id// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByref byref]] //buttons// [[KeyPgAs as]] [[KeyPgInteger integer]] = 0, [[KeyPgByref byref]] //a1// [[KeyPgAs as]] [[KeyPgSingle single]] = 0, [[KeyPgByref byref]] //a2// [[KeyPgAs as]] [[KeyPgSingle single]] = 0, [[KeyPgByref byref]] //a3// [[KeyPgAs as]] [[KeyPgSingle single]] = 0, [[KeyPgByref byref]] //a4// [[KeyPgAs as]] [[KeyPgSingle single]] = 0, [[KeyPgByref byref]] //a5// [[KeyPgAs as]] [[KeyPgSingle single]] = 0, [[KeyPgByref byref]] //a6// [[KeyPgAs as]] [[KeyPgSingle single]] = 0, [[KeyPgByref byref]] //a7// [[KeyPgAs as]] [[KeyPgSingle single]] = 0, [[KeyPgByref byref]] //a8// [[KeyPgAs as]] [[KeyPgSingle single]] = 0 ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **Getjoystick**( //id//[, //buttons//[, //a1//[, //a2//[, //a3//[, //a4//[, //a5//[, //a6//[, //a7//[, //a8//]]]]]]]]] ) ## {{fbdoc item="param"}} ##//id//## the device id number (0 - 15) ##//buttons//## the button status ##//a1//## first axis value ##//a2//## second axis value ##//a3//## third axis value ##//a4//## fourth axis value ##//a5//## fifth axis value ##//a6//## sixth axis value ##//a7//## seventh axis value ##//a8//## eighth axis value {{fbdoc item="ret"}} 0 on success or 1 on failure. All of the axis positions are returned in floating point format. {{fbdoc item="desc"}} ##**Getjoystick**## will retrieves the button state, and the axis positions for up to 8 axes, for the joystick determined by ##//id//##, a number between 0 and 15. Buttons are stored in a similar manner to ##[[KeyPgGetmouse Getmouse]]##, with each bit in ##//buttons//## representing a button. A single precision value between ##-1.0## and ##1.0## is returned for each valid axis. If the axis does not exist for the controller, a value of ##-1000.00## is returned. ##**Getjoystick**## will return 0 upon successful completion; It will return 1 upon failure. Failure can be caused by specifying an illegal joystick number, specifying a joystick which doesn't exist, or a failure in the joystick API. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/input/getjoystick.bas"}}%%(freebasic) screen 12 dim x as single dim y as single dim buttons as integer dim result as integer dim a as integer const JoystickID = 0 'This line checks to see if the joystick is ok. if GETJOYSTICK(JoystickID,buttons,x,y) then print "Joystick doesn't exist or joystick error." print print "Press any key to continue." sleep end end if do result = GETJOYSTICK(JoystickID,buttons,x,y) locate 1,1 print ;"result:";result;" x:" ;x;" y:";y;" Buttons:";buttons,"","","" 'This tests to see which buttons from 1 to 27 are pressed. for a = 0 to 26 if (buttons AND (1 shl a)) then print "Button ";a;" pressed. " else print "Button ";a;" not pressed." end if next a loop %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Getjoystick""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgScreengraphics Screen (Graphics)]]## - ##[[KeyPgSetmouse Setmouse]]## - ##[[KeyPgGetmouse Getmouse]]## - ##[[KeyPgMultikey Multikey]]## {{fbdoc item="back" value="CatPgGfxInput|User Input Functions"}}{{fbdoc item="title" value="GETKEY"}}---- Returns the ascii code of the first key in the keyboard buffer {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Getkey** ( ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **Getkey** ## {{fbdoc item="ret"}} The [[KeyPgInteger integer]] value of the ascii code returned. {{fbdoc item="desc"}} It returns the ascii code of the first key in the keyboard buffer. The key is removed from the buffer. If no key is present, ##**Getkey**## waits for it. For extended keys (returning two characters), the extended code is returned in the first byte, and the regular code is returned in the second byte. (see example below) The key read is not echoed to the screen. For a keyword not stopping the program if no key is at the buffer see ##[[KeyPgInkey Inkey]]## or ##[[KeyPgMultikey Multikey]]##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/input/getkey.bas"}}%%(freebasic) dim as integer foo do foo = getkey print "total return: " & foo if( foo > 255 ) then print "extended code: " & (foo and &hff) print "regular code: " & (foo shr 8) else print "regular code: " & (foo) end if print loop until foo = 27 %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Getkey""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgInkey Inkey]]## - ##[[KeyPgInputnum Input()]]## - ##[[KeyPgMultikey Multikey]]## {{fbdoc item="back" value="CatPgInput|User Input"}}{{fbdoc item="title" value="GETMOUSE"}}---- Retrieves the status of the mouse pointing device {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Getmouse** ( [[KeyPgByref byref]] //x// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByref byref]] //y// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByref byref]] //wheel// [[KeyPgAs as]] [[KeyPgInteger integer]] = 0, [[KeyPgByref byref]] //buttons// [[KeyPgAs as]] [[KeyPgInteger integer]] = 0, [[KeyPgByref byref]] //clip// [[KeyPgAs as]] [[KeyPgInteger integer]] = 0 ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **Getmouse** (//x//, //y// [, [ //wheel// ] [, [ //buttons// ] [, [ //clip// ]]]]) ## {{fbdoc item="param"}} ##//x//## x coordinate value ##//y//## y coordinate value ##//wheel//## scroll wheel value ##//buttons//## button status ##//clip//## clip status {{fbdoc item="ret"}} 0 on success or 1 on failure. {{fbdoc item="desc"}} ##**Getmouse**## retrieves the mouse position and buttons status; information is returned in the variables passed to this function by reference. If a mouse is not available, all variables will contain the -1 value. If in console mode, the ##//x//## and ##//y//## coordinates are the character cell coordinates the mouse is currently on; the upper left corner of the screen is at coordinates 0, 0. If the mouse moves out of the console window, ##**Getmouse**## returns the last coordinate on the window that the mouse was on. If in graphics mode, ##//x//## and ##//y//## will always be returned in pixel coordinates still relative to the upper left corner of the screen, which is at 0,0 in this case; custom coordinates system set via ##[[KeyPgViewgraphics View]]## or ##[[KeyPgWindow Window]]## do not affect the coordinates returned by ##**Getmouse**##. If the mouse runs off the window, all values are set to -1. ##//Wheel//## is the mouse wheel counter; rotating the wheel away from you makes the count to increase, rotating the wheel toward you makes it to decrease. At program startup or when a new graphics mode is set via ##[[KeyPgScreengraphics Screen]]##, wheel position is reset to 0. FreeBASIC may not always support mouse wheels for a given platform, in which case 0 is always returned. ##//Buttons//## stores the buttons status as a bitmask: bit 0 is set if left mouse button is down; bit 1 is set if right mouse button is down; bit 2 is set if middle mouse button is down. ##//Clip//## stores the mouse clipping status; if 1, the mouse is currently clipped to the graphics window; if 0, the mouse is not clipped. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/input/getmouse.bas"}}%%(freebasic) ' Set video mode and enter loop DIM x AS INTEGER, y AS INTEGER, buttons AS INTEGER DIM res AS INTEGER SCREEN 13 DO ' Get mouse x, y and buttons. Discard wheel position. res = GETMOUSE (x, y, , buttons) 'buttons LOCATE 1, 1 IF res <> 0 THEN PRINT "Mouse not available or not on window" ELSE PRINT USING "Mouse position: ###:### Buttons: "; x; y; IF buttons AND 1 THEN PRINT "L"; IF buttons AND 2 THEN PRINT "R"; IF buttons AND 4 THEN PRINT "M"; PRINT " " END IF LOOP WHILE INKEY = "" END %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgScreengraphics Screen (Graphics)]]## - ##[[KeyPgSetmouse Setmouse]]## - ##[[KeyPgMultikey Multikey]]## - ##[[KeyPgGetjoystick Getjoystick]]## {{fbdoc item="back" value="CatPgGfxInput|User Input Functions"}}{{fbdoc item="title" value="GOSUB"}}---- Control flow statement to use a section of code and return. {{fbdoc item="syntax"}}## **Gosub** //label// ## {{fbdoc item="desc"}} Execution jumps to a subroutine marked by a line label. Always use ##[[KeyPgReturn Return]]## to exit a ##**Gosub**##, execution will continue on next statement after ##**Gosub**##. The line label where ##**Gosub**## jumps must be in the same main/function/sub block as ##**Gosub**##. All the variables in the subroutine are shared with the block, no arguments can be used. For this reason Gosub is considered bad programming practice as it can generate unreadable and untraceable code. It is better to use ##[[KeyPgSub Sub]]## or ##[[KeyPgFunction Function]]## instead. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/control/gosub.bas"}}%%(freebasic) '' Compile with -lang qb gosub message end message: print "Welcome!" return %% {{fbdoc item="lang"}} - Only available in the //[[CompilerOptlang -lang qb]]// and //[[CompilerOptlang -lang fblite]]// dialects. - ##**Gosub**## support is disabled by default in the //[[CompilerOptlang -lang fblite]]// unless the ##[[KeyPgOptiongosub Option Gosub]]## statement is used. {{fbdoc item="diff"}} - None when using the //[[CompilerOptlang -lang qb]]// dialect. {{fbdoc item="see"}} - ##[[KeyPgGoto Goto]]## - ##[[KeyPgReturn Return]]## - ##[[KeyPgSub Sub]]## - ##[[KeyPgFunction Function]]## - ##[[KeyPgOptiongosub Option Gosub]]## {{fbdoc item="back" value="CatPgControlFlow|Control Flow"}}{{fbdoc item="title" value="GOTO"}}---- Control flow statement to jump to another part of the program {{fbdoc item="syntax"}}## **Goto** //label// ## {{fbdoc item="desc"}} Jumps code execution to a line label. For better source code readability, overuse of ##**Goto**## should be avoided in favor of more modern structures such as ##[[KeyPgDoloop Do...Loop]]##, ##[[KeyPgFornext For...Next]]##, ##[[KeyPgSub Sub]]##, and ##[[KeyPgFunction Function]]##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/control/goto.bas"}}%%(freebasic) goto there backagain: end there: print "Welcome!" goto backagain %% {{fbdoc item="filename" value="examples/manual/control/gotonum.bas"}}%%(freebasic) '' Compile with -lang qb or fblite 1 goto 3 2 end 3 print "Welcome!" 4 goto 2 %% {{fbdoc item="lang"}} - Line numbers are allowed only in the //[[CompilerOptlang -lang qb]]// and //[[CompilerOptlang -lang deprecated]]// dialects. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgGosub Gosub]]## - ##[[KeyPgSub Sub]]## - ##[[KeyPgFunction Function]]## {{fbdoc item="back" value="CatPgControlFlow|Control Flow"}}{{fbdoc item="title" value="HEX"}}---- Returns the hexadecimal of the given number {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Hex** [[KeyPgOverload overload]] ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgByte byte]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Hex** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgShort short]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Hex** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Hex** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByval byval]] //digits// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Hex** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgLongint longint]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Hex** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgLongint longint]], [[KeyPgByval byval]] //digits// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgString string]] ## {{fbdoc item="usage"}}## //result// = **Hex**[$]( //number// [, //digits// ] ) ## {{fbdoc item="param"}} ##//number//## A number or expression evaluating to a number. A floating-point number will be converted to a ##[[KeyPgLongint longint]]##. ##//digits//## Optional number of digits to return. {{fbdoc item="ret"}} A [[KeyPgString string]] containing the unsigned hexadecimal representation of ##//number//##. {{fbdoc item="desc"}} Returns the unsigned hexadecimal string representation of the integer ##//number//##. Hexadecimal digits range from 0-9, or A-F. If you specify ##//digits//## > 0, the result string will be exactly that length. It will be truncated or padded with zeros on the left, if necessary. The length of the string will not go longer than the maximum number of digits required for the type of ##//number//## (8 for an ##[[KeyPgInteger integer]]##, 16 for a ##[[KeyPgLongint longint]])##. If you want to do the opposite, i.e. convert a hexadecimal string back into a number, the easiest way to do it is to prepend the string with ##"&H"##, and convert it using ##[[KeyPgValint Valint]]## or ##[[KeyPgVallng Vallng]]##, similarly to a normal numeric string. E.g. ##[[KeyPgValint Valint]]("&HFF")## {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/hex.bas"}}%%(freebasic) '54321 is D431 in hex Print Hex(54321) Print Hex(54321, 2) Print Hex(54321, 5) %% will produce the output: %%D431 31 0D431 %% {{fbdoc item="lang"}} - The string type suffix ##"$"## is obligatory in the //[[CompilerOptlang -lang qb]]// dialect. - The string type suffix ##"$"## is optional in the //[[CompilerOptlang -lang fblite]]// and //[[CompilerOptlang -lang fb]]// dialects. {{fbdoc item="diff"}} - In QBASIC, there was no way to specify the number of digits returned. - The size of the string returned was limited to 32 bits, or 8 hexadecimal digits. {{fbdoc item="see"}} - ##[[KeyPgBin Bin]]## - ##[[KeyPgOct Oct]]## - ##[[KeyPgValint Valint]]## - ##[[KeyPgVallng Vallng]]## {{fbdoc item="back" value="CatPgString|String Functions"}}{{fbdoc item="title" value="HIBYTE"}}---- Macro to return the high byte of an expression {{fbdoc item="syntax"}}## [[KeyPgPpdefine #define]] **Hibyte**( //x// ) (([[KeyPgCuint CUint]](//x//) [[KeyPgOpAnd and]] &h0000FF00) [[KeyPgOpShiftRight shr]] 8) ## {{fbdoc item="usage"}}## //result// = **Hibyte**(//x//) ## {{fbdoc item="param"}} ##//x//## Number to retrieve high-byte from. {{fbdoc item="ret"}} The most significant byte of ##//x//##. {{fbdoc item="desc"}} A ##[[KeyPgByte Byte]]## is 8 bits. This is best understood by an example. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/bits/hibyte.bas"}}%%(freebasic) DIM N AS UINTEGER 'Note there are 16 bits N = &b1010101110000001 PRINT "N is "; N PRINT "The binary representation of N is "; BIN(N) PRINT "The most significant byte (MSB) of N is "; HIBYTE(N) PRINT "The least significant byte (LSB) of N is "; LOBYTE(N) PRINT "The binary representation of the MSB is "; BIN(HIBYTE(N)) PRINT "The binary representation of the LSB is "; BIN(LOBYTE(N)) SLEEP %% The output would look like: %% N Is 43905 The Binary representation of N Is 1010101110000001 The most significant Byte (MSB) of N Is 171 The least significant Byte (LSB) of N Is 129 The Binary representation of the MSB Is 10101011 The Binary representation of the LSB Is 10000001 %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__HIBYTE""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgLoByte Lobyte]]## {{fbdoc item="back" value="CatPgBits|Bit Manipulation"}}{{fbdoc item="title" value="HIWORD"}}---- Macro to return the high word of an expression {{fbdoc item="syntax"}}## [[KeyPgPpdefine #define]] **Hiword**( //x// ) ([[KeyPgCuint CUint]](//x//) [[KeyPgOpShiftRight shr]] 16) ## {{fbdoc item="usage"}}## //result// = **Hiword**(//x//) ## {{fbdoc item="param"}} ##//x//## Number to retrieve high-word from. {{fbdoc item="ret"}} The most significant word of ##//x//##. {{fbdoc item="desc"}} A word is 2 bytes and a byte is 8 bits. This is best understood by an example. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/bits/hiword.bas"}}%%(freebasic) DIM N AS UINTEGER 'Note there are 32 bits N = &b10000000000000011111111111111111 PRINT "N is "; N PRINT "The binary representation of N is "; BIN(N) PRINT "The most significant word (MSW) of N is "; HIWORD(N) PRINT "The least significant word (LSW) of N is "; LOWORD(N) PRINT "The binary representation of the MSW is "; BIN(HIWORD(N)) PRINT "The binary representation of the LSW is "; BIN(LOWORD(N)) SLEEP %% The output would look like: %% N Is 2147614719 The Binary representation of N Is 10000000000000011111111111111111 The most significant word (MSW) of N Is 32769 The least significant word (LSW) of N Is 65535 The Binary representation of the MSW Is 1000000000000001 The Binary representation of the LSW Is 1111111111111111 %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__HIWORD""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgLoWord Loword]]## - ##[[KeyPgHibyte Hibyte]]## - ##[[KeyPgLoByte Lobyte]]## {{fbdoc item="back" value="CatPgBits|Bit Manipulation"}}{{fbdoc item="title" value="HOUR"}}---- Gets the hour of day from a [[ProPgDates Date Serial]] {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Hour** ( [[KeyPgByval byval]] //date_serial// [[KeyPgAs as]] [[KeyPgDouble double]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## #include "vbcompat.bi" //result// = **Hour**( //dateserial// ) ## {{fbdoc item="param"}} ##//date_serial//## the date serial {{fbdoc item="ret"}} Returns the hour from a variable containing a date in [[ProPgDates Date Serial]] format. {{fbdoc item="desc"}} . The compiler will not recognize this function unless ##vbcompat.bi## is included. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/dates/hour.bas"}}%%(freebasic) #include "vbcompat.bi" dim ds as double = DateSerial(2005, 11, 28) + TimeSerial(7, 30, 50) print format(ds, "yyyy/mm/dd hh:mm:ss "); Hour(ds) %% {{fbdoc item="diff"}} - Did not exist in QB. This function appeared in PDS and VBDOS {{fbdoc item="see"}} - [[ProPgDates Date Serials]] {{fbdoc item="back" value="CatPgDate|Date and Time Functions"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:53:49 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 1e4cdf3a78fb9ddda2dd66053e7acc19 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 2874 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="IF...THEN"}}---- Control flow statement for conditional branching {{fbdoc item="syntax"}}## **If** //expression// **Then** [//statement(s)//] [**Else** [//statement(s)//]] [**End If**] //or// **If** //expression// **Then** : [//statement(s)//] [**Else** [//statement(s)//]] : **End If** //or// **If** //expression// **Then** [//statement(s)//] [ **Elseif** //expression// **Then** ] [//statement(s)//] [ **Else** ] [//statement(s)//] **End If** ## {{fbdoc item="desc"}} ##**If...Then**## is a way to make decisions. It is a mechanism to execute code only if a condition is true, and can provide alternative code to execute based on more conditions. The expression is always evaluated completely (no short-circuit evaluation), so it is necessary to separate potentially unsafe expressions with extra levels of ##**If**## blocks. Both multi-line and single-line ##**If**##s can be nested. In the latter case, the optional ##**End If**##s can be useful to control where nested ##**If**##s begin and end. In the //[[CompilerOptlang -lang fb]]// and //[[CompilerOptlang -lang fblite]]// dialects, colons (##:##) can be used instead of newlines to construct multi-line ##**If**## blocks on a single line. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/control/if-then.bas"}}%%(freebasic) 'e.g. here is a simple "guess the number" game using if...then for a decision. dim x as integer, y as integer RANDOMIZE TIMER x = RND * 11 'Create a random number between 0 and 10.999... PRINT "guess the number between 0 and 10" DO 'Start a loop INPUT "guess"; y 'Input a number from the user IF x = y THEN PRINT "right!" 'He/she guessed the right number! EXIT DO ELSEIF y > 10 THEN 'The number is higher then 10 PRINT "The number cant be greater then 10! Use the force!" ELSEIF x > y THEN PRINT "too low" 'The users guess is to low ELSEIF x < y THEN PRINT "too high" 'The users guess is to high END IF LOOP 'Go back to the start of the loop %% {{fbdoc item="lang"}} In the //[[CompilerOptlang -lang fb]]// and //[[CompilerOptlang -lang fblite]]// dialects, if there is a new line, a single-line comment (##'##), a colon (##:##), or a ##[[KeyPgRem Rem]]## statement directly after THEN, then the IF will be multi-line. Any other statement will result in a single-line IF. In the //[[CompilerOptlang -lang qb]]// dialect, if there is a new line or a single-line comment (##'##) directly after THEN, then the IF will be multi-line. A colon, a ##[[KeyPgRem Rem]]## or any other statement will result in a single-line IF. {{fbdoc item="diff"}} - END IF was not supported in single-line IFs in QBASIC. {{fbdoc item="see"}} - ##[[KeyPgDoloop Do...Loop]]## - ##[[KeyPgPpif #if]]## - ##[[KeyPgSelectcase Select Case]]## {{fbdoc item="back" value="CatPgControlFlow|Control Flow"}} {{fbdoc item="title" value="IIF"}}---- Conditional function that returns one of two values. {{fbdoc item="syntax"}}## **IIf** ( //condition//, //expr_if_true//, //expr_if_false// ) ## {{fbdoc item="param"}} ##//condition//## The condition to test. A non-zero value evaluates as true, while a value of zero evaluates as false. ##//expr_if_true//## An expression to evaluate and return if ##//condition//## is true. It must return a numeric value, which can be an integer, floating point number or a pointer. ##//expr_if_false//## An expression to evaluate and return if ##//condition//## is false. It must be the same type of number as ##//expr_if_true//##. {{fbdoc item="desc"}} ##**IIf**## returns a different numeric value depending of the result of a conditional expression. Its typical use is in the middle of an expression; it avoids splitting it to put a conditional in the middle. ##**IIf**## only evaluates the expression that it needs to return. This saves time, and can also be useful to prevent evaluating expressions that might be invalid depending on the ##//condition//##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/control/iif.bas"}}%%(freebasic) dim as integer a, b, x, y, z a = (x + y + iif(b > 0, 4, 7)) \ z %% is equivalent to: {{fbdoc item="filename" value="examples/manual/control/iif2.bas"}}%%(freebasic) dim as integer a, b, x, y, z, temp if b > 0 then temp = 4 else temp = 7 a = (x + y + temp) \ z %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Iif""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgIfthen If...Then]]## {{fbdoc item="back" value="CatPgMisc|Miscellaneous"}} {{fbdoc item="title" value="IMAGECONVERTROW"}}---- Converts a row of image data into another color depth {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **""ImageConvertRow""** ( [[KeyPgByval byval]] //src// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]], [[KeyPgByval byval]] //src_bpp// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByval byval]] //dst// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]], [[KeyPgByval byval]] //dst_bpp// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByval byval]] //width// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByval byval]] //isrgb// [[KeyPgAs as]] [[KeyPgInteger integer]] = 1 ) ## {{fbdoc item="usage"}}## **""ImageConvertRow""**( //src//, //src_bpp//, //dst//, //dst_bpp//, //width// [, //isrgb// ] ) ## {{fbdoc item="param"}} ##//src//## The address of the start of the source row. The source can either be a full-color image with a bit depth of 24 or 32 bits per pixel, or a paletted image with a bit depth of 1-8 bits per pixel. Converting a paletted image will only work properly if you are in a screen mode that is using the correct palette for the image when you do the conversion. ##//src_bpp//## The number of bits per pixel in the source row. 1-8, 24 and 32. ##//dst//## The address of the start of the destination row. The image can be a full-color image of 16 or 32 bits per pixel. If the source is a paletted image, the destination can also be a paletted image of 1 to 8 bits per pixel. ##//dst_bpp//## The number of bits per pixel in the destination row. Valid values for this are 1-8, 16 and 32. ##//width//## The length of the row in pixels. ##//isrgb//## A value of zero indicates that the Red and Blue channels are the other way round in the source image. Use this switch if you want the Red and Blue channels to be swapped in the conversion. {{fbdoc item="desc"}} Copies the row of an image from one memory location to another, converting the color information in each pixel to match the destination image. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/imageconvertrow.bas"}}%%(freebasic) #include "fbgfx.bi" #if __fb_lang__ = "fb" Using FB #endif Const As Integer w = 64, h = 64 Dim As IMAGE Ptr img8, img32 Dim As Integer x, y '' create a 32-bit image, size w*h: Screenres 1, 1, 32, , GFX_NULL img32 = ImageCreate(w, h) If img32 = 0 Then Print "Imagecreate failed on img32!": Sleep: End '' create an 8-bit image, size w*h: Screenres 1, 1, 8, , GFX_NULL img8 = ImageCreate(w, h) If img8 = 0 Then Print "Imagecreate failed on img8!": Sleep: End '' fill 8-bit image with a pattern for y = 0 to h - 1 for x = 0 to w - 1 pset img8, (x, y), 56 + (x + y) mod 24 next x next y '' open a graphics window in 8-bit mode, and PUT the image into it: Screenres 320, 200, 8 Windowtitle "8-bit color mode" Put (10, 10), img8 Sleep '' copy the image data into a 32-bit image Dim As Byte Ptr p8, p32 Dim As Integer pitch8, pitch32 #ifndef ImageInfo '' older versions of FB don't have the ImageInfo feature #define GETPITCH(img_) iif(img_->type=PUT_HEADER_NEW,img_->pitch,img_->old.width*img_->old.bpp) #define GETP(img_) CPtr(Byte Ptr,img_)+iif(img_->type=PUT_HEADER_NEW,sizeof(PUT_HEADER),sizeof(_OLD_HEADER)) pitch8 = GETPITCH(img8): p8 = GETP(img8) pitch32 = GETPITCH(img32): p32 = GETP(img32) #else ImageInfo( img8, , , , pitch8, p8 ) ImageInfo( img32, , , , pitch32, p32 ) #endif For y = 0 To h - 1 ImageConvertRow(@p8 [ y * pitch8 ], 8, _ @p32[ y * pitch32], 32, _ w) Next y '' open a graphics window in 32-bit mode and PUT the image into it: Screenres 320, 200, 32 Windowtitle "32-bit color mode" Put (10, 10), img32 Sleep '' free the images from memory: ImageDestroy img8 ImageDestroy img32 %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__ImageConvertRow""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgScreenres ScreenRes]]## - ##[[KeyPgGetgraphics Get (Graphics)]]## - ##[[KeyPgPutgraphics Put (Graphics)]]## - ##[[KeyPgImagecreate ImageCreate]]## - ##[[KeyPgImageDestroy ImageDestroy]]## - ##[[KeyPgImageInfo ImageInfo]]## {{fbdoc item="back" value="CatPgGfx2D|2D Drawing Functions"}}{{fbdoc item="title" value="IMAGECREATE"}}---- Creates and initializes storage for an image {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub function]] **""ImageCreate""**( //width// [[KeyPgAs as]] [[KeyPgInteger integer]], //height// [[KeyPgAs as]] [[KeyPgInteger integer]] [, [ //color// [[KeyPgAs as]] [[KeyPgUinteger uinteger]] ] [, //depth// [[KeyPgAs as]] [[KeyPgInteger integer]] ]] ) [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] ## {{fbdoc item="usage"}}## //buffer// = **""ImageCreate""**( //width//, //height// [, [ //color// ][, //depth// ]] ) ## {{fbdoc item="param"}} ##//width//## Desired width of the image buffer to create. ##//height//## Desired height of the image buffer to create. ##//color//## The pixel value to fill the image buffer with upon creation. ##//depth//## Desired color depth of the image buffer, in bits per pixel. {{fbdoc item="ret"}} The address of the image buffer, or NULL (0) if the buffer could not be created. {{fbdoc item="desc"}} Allocates and initializes a memory buffer for an image. If ##//color//## is omitted, a value of 0 will be used for paletted (8-bit or less) modes, or [[KeyPgRgb RGB]](255, 0, 255) for higher color depth modes (this translates to &hF81F and &hFFFF00FF for 15/16-bit and 24/32-bit modes, respectively - see the [[GfxInternalFormats internal gfx formats]] reference for more info). These are special mask colors, which will be transparent when using ##[[KeyPgPutgraphics Put]]## with the ##[[KeyPgTransGfx Trans]]## method. ##**""ImageCreate""**## only works when a graphics mode has been set up with the ##[[KeyPgScreengraphics Screen]]## statement or ##[[KeyPgScreenres ScreenRes]]## statement. Images can be set up with different color depths from the screen color depth, using the ##//depth//## parameter. An image buffer can be passed to graphics functions across mode changes as long as the different modes use the same color depth. Images should be deleted with ##[[KeyPgImageDestroy ImageDestroy]]## when they are no longer needed, in order to prevent memory leaks. The ##**""ImageCreate""**## function is an alternative to using the ##[[KeyPgGetgraphics Get (Graphics)]]## statement to create a buffer, and can ease the creation of an image buffer for use 2D drawing functions. It is recommended that you always use ##**""ImageCreate""**## though, as it automatically allocates the correct size for the buffer, given its dimensions and the current color depth; the image header may vary in size in future FreeBASIC releases, so using ##[[KeyPgGetgraphics Get (Graphics)]]## with a buffer allocated on the stack may result in corrupted data, as the static buffer size may have been manually computed using a formula that is no longer valid. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/imagecreate.bas"}}%%(freebasic) Dim image_buffer As Any Ptr Const NULL as Any Ptr = 0 '' set screen mode (this must be done before trying to create an image) Screenres 320, 200, 32 '' allocate an image buffer with a darkish green background image_buffer = ImageCreate(64, 64, RGB(0, 128, 0)) '' check that image creation succeeded If image_buffer = NULL Then Print "Image creation failed!" Sleep End End If '' draw a semi-transparent, red circle to the image buffer Circle image_buffer, (32, 32), 28, RGBA(255, 0, 0, 128),,, 1.0, F '' blit image buffer to screen Put (120, 60), image_buffer, PSet Put (140, 80), image_buffer, Alpha Sleep '' free image buffer memory ImageDestroy image_buffer %% {{image class="center" title="Imagecreate example output" url="/images/imagecreate.png"}} {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Imagecreate""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgGetgraphics Get (Graphics)]]## - ##[[KeyPgImageInfo ImageInfo]]## - ##[[KeyPgImageDestroy ImageDestroy]]## - [[GfxInternalFormats Internal pixel formats]] {{fbdoc item="back" value="CatPgGfx2D|2D Drawing Functions"}}{{fbdoc item="title" value="IMAGEDESTROY"}}---- Frees memory associated with an image buffer {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **""ImageDestroy""**( //pointer// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] ) ## {{fbdoc item="usage"}}## **""ImageDestroy""**( //pointer// ) ## {{fbdoc item="param"}} ##//pointer//## The address of the image buffer to be freed. {{fbdoc item="desc"}} Frees memory previously allocated with the ##[[KeyPgImagecreate ImageCreate]]## function. After the memory is freed, ##//pointer//## will be invalid. {{fbdoc item="ex"}} See the ##[[KeyPgImagecreate ImageCreate]]## function for an example on using ##**""ImageDestroy""**##. {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Imagedestroy""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgGetgraphics Get (Graphics)]]## - ##[[KeyPgImagecreate ImageCreate]]## {{fbdoc item="back" value="CatPgGfx2D|2D Drawing Functions"}}{{fbdoc item="title" value="IMAGEINFO"}}---- Retrieves information about a ""FreeBASIC"" image buffer {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Imageinfo** ( [[KeyPgByval byval]] //img// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]], [[KeyPgByref byref]] //width// [[KeyPgAs as]] [[KeyPgInteger integer]] = 0, [[KeyPgByref byref]] //height// [[KeyPgAs as]] [[KeyPgInteger integer]] = 0, [[KeyPgByref byref]] //bypp// [[KeyPgAs as]] [[KeyPgInteger integer]] = 0, [[KeyPgByref byref]] //pitch// [[KeyPgAs as]] [[KeyPgInteger integer]] = 0, [[KeyPgByref byref]] //pixdata// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] = 0, [[KeyPgByref byref]] //imgsize// [[KeyPgAs as]] [[KeyPgInteger integer]] = 0 ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **Imageinfo** ( [//width//] [, [//height//] [, [//bypp//] [, [//pitch//] [, [//pixdata//] [, [//imgsize//]]]]]] ) ## {{fbdoc item="param"}} ##//width//## width of image ##//height//## height of image ##//bypp//## bytes per pixel ##//pitch//## bytes needed per scanline ##//pixdata//## pointer to start of pixel data ##//imgsize//## total memory used by image {{fbdoc item="ret"}} ##0## on success, or ##1## if an invalid header is detected. {{fbdoc item="desc"}} ##**Imageinfo**## provides you with useful information about an image, such as its dimensions and color depth, but also provides you with the information you need to directly access all the pixel data in the pixel buffer. It also provides the size of image buffer in memory, which is useful for when you want to copy the buffer or store it in a file. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/imageinfo.bas"}}%%(freebasic) Dim img As Any Ptr, pixdata As Any Ptr, pitch As Integer '' Create 32-bit screen and image buffer ScreenRes 320, 200, 32 img = ImageCreate(64, 64) '' get pitch and pixel data pointer of image imageinfo img, ,,, pitch, pixdata '' draw pattern directly into the image memory For y As Integer = 0 To 63 Dim As UInteger Ptr p = pixdata + y * pitch For x As Integer = 0 To 63 p[x] = RGB(x * 4, y * 4, (x Xor y) * 4) Next x Next y '' Put the image to screen Put (10, 10), img '' Free the image memory ImageDestroy img '' Wait for a keypress before closing Sleep %% {{image class="center" title="Output image for ImageInfo example" url="/images/imageinfo.png"}} {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Imageinfo""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgGetgraphics Get (Graphics)]]## - ##[[KeyPgPutgraphics Put (Graphics)]]## - ##[[KeyPgImagecreate ImageCreate]]## - ##[[KeyPgImageConvertRow ImageConvertRow]]## - ##[[KeyPgImageDestroy ImageDestroy]]## - [[GfxInternalFormats Internal pixel formats]] {{fbdoc item="back" value="CatPgGfx2D|2D Drawing Functions"}}{{fbdoc item="title" value="IMPORT"}}---- External linkage attribute for public data located in DLL's {{fbdoc item="syntax"}}## [[KeyPgExtern Extern]] **Import** //symbolname//[( //subscripts//)] [ [[KeyPgAlias alias]] "//aliasname//"] [ [[KeyPgAs as]] [[DataType DataType]]] [, ...] ## {{fbdoc item="desc"}} Is used only on Win32 platforms with the ##[[KeyPgExtern Extern]]## keyword and is needed to access global variables in DLLs. This is due to the level of indirection on any such access: an implicit pointer dereference. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/module/mydll.c"}}%%(c) /* mydll.c : compile with gcc -shared -Wl,--strip-all -o mydll.dll mydll.c */ __declspec( dllexport ) int MyDll_Data = 0x1234; %% {{fbdoc item="filename" value="examples/manual/module/import.bas"}}%%(freebasic) /' import.bas : Compile with fbc import.bas '/ #inclib "mydll" Extern Import MyDll_Data Alias "MyDll_Data" As Integer Print "&h" + Hex( MyDll_Data ) ' Output: ' &h1234 %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Import""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgExtern Extern]]## {{fbdoc item="back" value="CatPgModularizing|Modularizing"}}{{fbdoc item="title" value="#INCLIB"}}---- Preprocessor directive {{fbdoc item="syntax"}}## **#inclib** //"filename"// ## {{fbdoc item="desc"}} Includes a library (.a file) in the linking process, making it easier for the user to compile, since the user doesn't have to explicitly type at the command line: ##"fbc sourcefile -a libfile"##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/prepro/inclib.bas"}}%%(freebasic) '' incomplete code snippet '' this will include libmystuff.a in the link process #inclib "mystuff" %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgInclude #include]]## - [[CompilerOptl Compiler Option: -l]] - [[CompilerOptp Compiler Option: -p]] {{fbdoc item="back" value="CatPgPreProcess|Preprocessor"}}{{fbdoc item="title" value="#INCLUDE"}}---- Preprocessor statement to include contents of another source file {{fbdoc item="syntax"}}## **#include** [once] //"file"// ## {{fbdoc item="desc"}} ##**#include**## inserts source code from another file at the point where the ##**#include**## directive appears. This has the effect of compiling the source code from the include file as though it were part of the source file that includes it. Once the compiler has reached the end of the include file, the original source file continues to be compiled. This is useful to remove code from a file and separate it into more files. It is useful to have a single file with declarations in a program formed by several modules. You may include files within an include file, although avoid including the original file into itself, this will not produce valid results. Typically, include files will have an extension of ##.bi## and are mainly used for declaring subs/functions/variables of a library, but any valid source code may be present in an include file. The ##**once**## specifier tells the compiler to include the file only once even if it is included several times by the source code. ##[[KeyPgMetaInclude $Include]]## is an alternate form of ##**include**##, it exists for compatibility with QuickBasic. It is recommended to use ##**#include**## instead. The compiler will automatically convert path separator characters ( '**/**' and '**\**' ) as needed to properly load the file. The filename name may be an absolute or relative path. For relative paths, or where no path is given at all, the include file is search for in the following order: - Relative from the directory of the source file - Relative from the current working directory - Relative from addition directories specified with the //-i// command line option {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/prepro/header.bi"}}%%(freebasic) ' header.bi file TYPE FooType Bar AS BYTE Barbeque AS BYTE END TYPE DIM Foo as FooType %% {{fbdoc item="filename" value="examples/manual/prepro/include.bas"}}%%(freebasic) ' main.bas file #INCLUDE "header.bi" Foo.Bar = 1 Foo.Barbeque = 2 %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgPpdefine #define]]## - ##[[KeyPgInclib #inclib]]## - [[CompilerOpti Compiler Option: -i]] {{fbdoc item="back" value="CatPgPreProcess|Preprocessor"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:54:00 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: f3c73ce54434270b3b3a36fbc065e5e6 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 2730 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="INKEY"}}---- Returns a string representing the first key waiting in the keyboard buffer {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Inkey** ( ) [[KeyPgAs as]] [[KeyPgString string]] ## {{fbdoc item="usage"}}## //result// = **Inkey**[$] ## {{fbdoc item="ret"}} The first character found in the keyboard buffer, or the null string (##"####"##) if none found. {{fbdoc item="desc"}} Peeks into the keyboard buffer and returns a ##[[KeyPgString String]]## representation of the first character, if any, found. The key is then removed from the buffer, and is not echoed to the screen. If the keyboard buffer is empty, the NULL string (##"####"##) is immediately returned without waiting for keys. If the key is in the ASCII character set, a one-character ##[[KeyPgString String]]## consisting of that character is returned. If the key is an "extended" one (numeric pad, cursors, functions) a two-character ##[[KeyPgString String]]## is returned, the first of which is the extended character (//See dialect differences below//) The ""Shift"", ""Ctrl"", ""Alt"", and ""AltGr"" keys can't be read independently by this function as they never enter the keyboard buffer (although, perhaps obviously, Shift-A will be reported by ##**Inkey**## differently than Control-A et cetera; Alt-A is an extended key a la the above). To wait for a key press, ##**Inkey**## can be polled in a loop. See also ##[[KeyPgInputnum Input]]## or ##[[KeyPgGetkey Getkey]]##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/input/inkey.bas"}}%%(freebasic) print "press q to quit" do loop until inkey = "q" %% {{fbdoc item="lang"}} - The extended character is ##Chr(255)## in the //[[CompilerOptlang -lang fb]]// and //[[CompilerOptlang -lang fblite]]// dialects. - In the //[[CompilerOptlang -lang qb]]// dialect, the extended character depends on how the keyword is written. If the QB form ##**Inkey$**## is used the extended character is ##Chr(0)##, while if written as ##**""__Inkey""**## the extended char is ##Chr(255)## as in the other dialects. - The string type suffix "$" is optional in the //[[CompilerOptlang -lang fblite]]// and //[[CompilerOptlang -lang fb]]// dialects. {{fbdoc item="diff"}} - None in the //[[CompilerOptlang -lang qb]]// dialect. - QBasic returned a ##Chr(0)## as the first character for an extended key, but FreeBASIC returns ##Chr(255)## as the first character in the //[[CompilerOptlang -lang fb]]// and //[[CompilerOptlang -lang fblite]]// dialects {{fbdoc item="see"}} - ##[[KeyPgGetkey Getkey]]## - ##[[KeyPgInputnum Input()]]## - ##[[KeyPgMultikey Multikey]]## {{fbdoc item="back" value="CatPgInput|User Input"}} {{fbdoc item="title" value="INP"}}---- Returns a value at a hardware port. {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Inp** ( [[KeyPgByval byval]] //port// [[KeyPgAs as]] [[KeyPgUshort ushort]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //value// = **Inp**(//port//) ## {{fbdoc item="param"}} ##//port//## Port number to read. {{fbdoc item="ret"}} The value at the specified port. {{fbdoc item="desc"}} This function retrieves the value at 'port' and returns immediately. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/hardware/inp.bas"}}%%(freebasic) '' Turn off PC speaker out &h61,inp(&h61) and &hfc %% {{fbdoc item="target"}} - In the Windows and Linux versions three port numbers (&H3C7, &H3C8, &H3C9) are hooked by the graphics library when a graphics mode is in use to emulate QB's VGA palette handling. This use is deprecated; use ##[[KeyPgPalette Palette]]## to retrieve and set palette colors. - Using true port access in the Windows version requires the program to install a device driver for the present session. For that reason, Windows executables using hardware port access should be run with administrator permits each time the computer is restarted. Further runs don't require admin rights as they just use the already installed driver. The driver is only 3K in size and is embedded in the executable. {{fbdoc item="see"}} - ##[[KeyPgOut Out]]## - ##[[KeyPgWait Wait]]## - ##[[KeyPgPalette Palette]]## {{fbdoc item="back" value="CatPgMisc|Miscellaneous"}} {{fbdoc item="title" value="INPUT"}}---- Reads a list of values from the keyboard {{fbdoc item="syntax"}}## **Input** [;] ["//prompt//" //separator//] //variable_list// ## {{fbdoc item="param"}} ##//prompt//## an optional string literal that is written to the screen. ##//separator//## a semicolon (##;##), which appends ##"? "## to the prompt, or comma (##,##), which appends nothing. ##//variable_list//## a list of comma-separated variables used to hold the values read from the user. {{fbdoc item="desc"}} Reads a list values from the keyboard up until the first carriage return. Numerical values are converted from their string representation into the corresponding types in the variable list. Characters are echoed to the screen as they are typed. Each value should be delimited by a comma (##,##). When Inputting a number, whitespace may also be used to delimit it. Surrounding whitespace will be trimmed from string values. If the input string has a comma in it, it can be wrapped in quotes (##"..."##) to prevent it being split up. Alternatively, ##[[KeyPgLineinput Line Input]]## maybe used to input an entire line to a single string without delimiting. The prompt - if any - is written to the screen at the current cursor location, and characters read are echoed to the screen immediately following the prompt. If no prompt is specified, characters are echoed at the current cursor location. The optional leading semicolon after ##**Input**## is similar to the optional trailing semicolon in a ##[[KeyPgPrint Print]]## statement: the cursor will remain on the same line after all of the characters have been echoed, otherwise, the cursor will move to the beginning of the next line. If more values are read than are listed in the variable list, extra values will be ignored; if fewer values are read, the remaining variables will be initialized - numeric variables to zero (##0##), and string variables to the null string (##"####"##). Numeric values are converted similar to the procedures ##[[KeyPgVal Val]]## and ##[[KeyPgVallng ValLng]]##, using the most appropriate function for the number format, converting as many numeric characters as possible. ##**Input**## has a limited edit capacity: it allows to erase characters using the backspace key. If a better user interface is needed, a custom input routine should be used. {{fbdoc item="ex"}} **Example #1** {{fbdoc item="filename" value="examples/manual/console/input.bas"}}%%(freebasic) Dim n As String, a As Integer Input "Enter [Name, Age]: ", n, a Print n Print a %% **Example #2** {{fbdoc item="filename" value="examples/manual/console/input2.bas"}}%%(freebasic) dim as double a, b dim as string yn do input "Please enter a number: ", a input ; "And another: ", b print , "Thank you" sleep 500 print print "The total is "; a + b print do input "Would you like to enter some more numbers"; yn yn = lcase(yn) loop until yn = "y" or yn = "n" loop while lcase(yn) = "y" %% {{fbdoc item="diff"}} - If the user inputs the wrong number of values, or if it expects a number for a value and gets a string that is not a valid number, then QBASIC issues the message "Redo from start", and does not continue further until it receives a valid input. - QB does not treat space as a delimiter when inputting a number from the console. - If no prompt is given, QBASIC will prompt with "? ", while FreeBASIC will not give any prompt. {{fbdoc item="see"}} - ##[[KeyPgInputPp Input #]]## - ##[[KeyPgInputnum Input()]]## - ##[[KeyPgLineinput Line Input]]## {{fbdoc item="back" value="CatPgInput|User Input"}}{{fbdoc item="title" value="INPUT (FILE MODE)"}}---- Specifies text file to be opened for input mode {{fbdoc item="syntax"}}## [[KeyPgOpen open]] //filename// for **Input** [[[KeyPgEncoding encoding]] //encoding_type//] [[[KeyPgLock lock]] //lock_type//] as [#]//filenum// ## {{fbdoc item="param"}} ##//filename//## file name to open for input ##//encoding_type//## indicates encoding type for the file ##//lock_type//## locking to be used while the file is open ##//filenum//## unused file number to associate with the open file {{fbdoc item="desc"}} A file mode used with ##[[KeyPgOpen Open]]## to open a text file for reading. This mode allows to read sequentially lines of text with ##[[KeyPgLineinputPp Line Input #]]##, or to read comma separated values with ##[[KeyPgInputPp Input #]]##. Text files can't be simultaneously read and written in FreeBASIC, so if both functions are required on the same file, it must be opened twice. ##//filename//## must be a string expression resulting in a legal file name in the target OS, without wildcards. The file will be sought for in the present directory, unless the ##//filename//## contains a path . If the file does not exist, an error is issued. The pointer is set at the first character of the file. ##//Encoding_type//## indicates the Unicode ##[[KeyPgEncoding Encoding]]## of the file, so characters are correctly read. If omitted, "ascii" encoding is defaulted. Only little endian character encodings are supported at the moment. -"utf8", -"utf16" -"utf32" -"ascii" (the default) ##//Lock_type//## indicates the way the file is locked for other processes, it is one of: - **Read** - the file can be opened simultaneously by other processes, but not for reading - **Write** - the file can be opened simultaneously by other processes, but not for writing - **Read Write** - the file cannot be opened simultaneously by other processes (the default) ##//filenum//## is a valid FreeBASIC file number (in the range 1-255) not being used for any other file presently open. The file number identifies the file for the rest of file operations. A free file number can be found using the ##[[KeyPgFreefile Freefile]]## function. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/fileio/for-input.bas"}}%%(freebasic) Dim ff As Ubyte Dim randomvar As Integer Dim name_str as string dim age_ubyte as ubyte ff = Freefile input "What is your name? ",name_str input "What is your age? ",age_ubyte Open "testfile" For Output As #ff Write #ff, Int(Rnd(0)*42),name_str,age_ubyte Close #ff randomvar=0 name_str="" age_ubyte=0 Open "testfile" For Input As #ff Input #ff, randomvar,name_str,age_ubyte Close #ff Print "Random Number was: ", randomvar Print "Your name is: " + name_str Print "Your age is: " + str(age_ubyte) 'File outputted by this sample will look like this, 'minus the comment of course: '23,"Your Name",19 %% {{fbdoc item="diff"}} - {{fbdoc item="see"}} - ##[[KeyPgAppend Append]]## - ##[[KeyPgOpen Open]]## - ##[[KeyPgOutput Output]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}} {{fbdoc item="title" value="INPUT()"}}---- Reads a number of characters from console or file {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Input** [[KeyPgOverload overload]] ( //n// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Input** ( //n// [[KeyPgAs as]] [[KeyPgInteger integer]], //filenum// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgString string]] ## {{fbdoc item="usage"}}## //result// = **Input**[$]( //n// [, [#]//filenum// ] ) ## {{fbdoc item="param"}} ##//n//## Number of bytes to read. ##//filenum//## File number of a bound file or device. {{fbdoc item="ret"}} Returns a ##[[KeyPgString String]]## of the characters read. {{fbdoc item="desc"}} Reads a number of characters from the console, or a bound file/device specified by ##//filenum//##. The first version waits for and reads ##//n//## characters from the keyboard buffer. Extended keys are not read. The characters are not echoed to the screen. The second version waits for and reads ##//n//## characters from a file or device. The file position is updated. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/console/input-n.bas"}}%%(freebasic) print "Select a color by number" print "1. blue" print "2. red" print "3. green" dim choice as string do choice = input(1) loop until choice >= "1" and choice <= "3" %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgWinput Winput()]]## - ##[[KeyPgGetkey Getkey]]## - ##[[KeyPgInkey Inkey]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}}{{fbdoc item="back" value="CatPgInput|User Input"}}{{fbdoc item="title" value="INPUT #"}}---- Reads a list of values from a text file {{fbdoc item="syntax"}}## **Input** # //filenum//, //variable_list// ## {{fbdoc item="param"}} ##//filenum//## a file number bound to a file or device ##//variable_list//## a list of variables used to hold the values read {{fbdoc item="desc"}} Reads from a text file through a bound file number a delimiter-separed set of values and writes them in reading order into the variables in //variable_list//. If a variable is numeric the read value is converted from its string representation into the corresponding type. Numeric values are converted similar to the procedures ##[[KeyPgVal Val]]## and ##[[KeyPgVallng ValLng]]##, using the most appropriate function for the number format. Delimiters may be commas or line breaks. (Whitespace is also treated as a separator after numbers.) . A string including a comma or a whitespace must be surronded by double quotes. To read an entire line into a string, use ##[[KeyPgLineinputPp Line Input]]## instead . [[KeyPgWritePp Write #]] can be used to create a file readable with ##**""Input #""**##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/fileio/input.bas"}}%%(freebasic) dim a as integer dim b as string dim c as single open "myfile.txt" for output as #1 write #1, 1, "Hello, World", 34.5 close #1 open "myfile.txt" for input as #1 input #1, a, b, c close #1 print a, b, c %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgInput Input]]## - ##[[KeyPgLineinputPp Line Input #]]## - ##[[KeyPgWritePp Write #]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}}{{fbdoc item="title" value="INSTR"}}---- Locates the first occurrence of a substring or character within a string {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Instr** [[KeyPgOverload overload]] ( [[KeyPgByref byref]] //str// [[KeyPgAs as]] [[KeyPgString string]], [ **Any** ] [[KeyPgByref byref]] //substring// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Instr** ( [[KeyPgByref byref]] //str// [[KeyPgAs as]] [[KeyPgWstring wstring]], [ **Any** ] [[KeyPgByref byref]] //substring// [[KeyPgAs as]] [[KeyPgWstring wstring]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Instr** ( [[KeyPgByval byval]] //start// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByref byref]] //str// [[KeyPgAs as]] [[KeyPgString string]], [ **Any** ] [[KeyPgByref byref]] //substring// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Instr** ( [[KeyPgByval byval]] //start// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByref byref]] //str// [[KeyPgAs as]] [[KeyPgWstring wstring]], [ **Any** ] [[KeyPgByref byref]] //substring// [[KeyPgAs as]] [[KeyPgWstring wstring]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //first// = **Instr**( [ //start//, ] //str//, [ **Any** ] //substring// ) ## {{fbdoc item="param"}} ##//str//## The string to be searched. ##//substring//## The substring to find. ##//start//## The position in ##//str//## at which the search will begin. {{fbdoc item="ret"}} The position of the first occurrence of ##//substring//## in ##//str//##. {{fbdoc item="desc"}} Locates the position of the first occurrence of a substring or character within a string. In the first form of ##**Instr**##, the search begins at the first character. Zero (0) is returned if ##//substring//## is not found, either ##//str//## or ##//substring//## are empty strings, or ##//start//## < 0. If the ##**Any**## keyword is specified, ##**Instr**## returns the first occurrence of any character in ##//substring//##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/instr.bas"}}%%(freebasic) ' It will return 4 Print InStr("abcdefg", "de") ' It will return 0 Print InStr("abcdefg", "h") ' It will search for any of the characters "f", "b", "c", and return 2 as "b" is encountered first Print InStr("abcdefg", Any "fbc") %% {{fbdoc item="filename" value="examples/manual/strings/instr2.bas"}}%%(freebasic) dim test as string dim idx as integer test = "abababab" idx = instr(test, "b") do while idx > 0 'if not found loop will be skipped print """b"" at " & idx idx = instr(idx + 1, Test, "b") loop %% <<'A Unicode example: dim text as wstring*20 text = "Привет, мир!" print instr(text,"ет") ' displays 5 <<::c:: {{fbdoc item="target"}} - DOS does not support the wide-character string versions of ##**Instr**##. {{fbdoc item="diff"}} - QB returns ##//start//## if ##//search//## is a zero length string. - QB does not support Unicode. {{fbdoc item="see"}} - ##[[KeyPgInstrrev Instrrev]]## - ##[[KeyPgMidfunction Mid (Function)]]## {{fbdoc item="back" value="CatPgString|String Functions"}}{{fbdoc item="title" value="INSTRREV"}}---- Locates the last occurrence of a substring or character within a string {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Instrrev** ( [[KeyPgByref byref]] //str// [[KeyPgAs as]] [[KeyPgString string]], [ **Any** ] [[KeyPgByref byref]] //substring// [[KeyPgAs as]] [[KeyPgString string]], [[KeyPgByval byval]] //start// [[KeyPgAs as]] [[KeyPgInteger integer]] = -1 ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Instrrev** ( [[KeyPgByref byref]] //str// [[KeyPgAs as]] [[KeyPgWstring wstring]], [ **Any** ] [[KeyPgByref byref]] //substring// [[KeyPgAs as]] [[KeyPgWstring wstring]], [[KeyPgByval byval]] //start// [[KeyPgAs as]] [[KeyPgInteger integer]] = -1 ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //last// = **Instrrev**( //str//, [ **Any** ] //substring// [, //start// ] ) ## {{fbdoc item="param"}} ##//str//## The string to be searched. ##//substring//## The substring to find. ##//start//## The position in ##//str//## at which the search will begin. {{fbdoc item="ret"}} The position of the last occurrence of ##//substring//## in ##//str//##. {{fbdoc item="desc"}} Locates the position of the last occurrence of a substring or character within a string. If ##//start//## parameter is not given or is -1, the search begins at the last character. Zero (0) is returned if ##//substring//## is not found, or either ##//str//## or ##//substring//## are empty strings, or ##//start//## is less than 1 (except for -1), or start is greater than the length of ##//str//##. If the ##**Any**## keyword is specified, ##**Instrrev**## returns the last occurrence of any character in ##//substring//##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/instrrev.bas"}}%%(freebasic) ' It will return 4 PRINT INSTRREV("abcdefg", "de") ' It will return 0 PRINT INSTRREV("abcdefg", "h") %% {{fbdoc item="filename" value="examples/manual/strings/instrrev2.bas"}}%%(freebasic) dim test as string dim idx as integer test = "abababab" idx = instrrev(test, "b") do while idx > 0 'if not found loop will be skipped print """b"" at " & idx idx = instrrev(Test, "b", idx - 1) loop %% <<'A Unicode example: dim text as wstring*20 text = "Привет, мир!" print instrrev(text,"ет") ' displays 5 <<::c:: {{fbdoc item="target"}} - DOS does not support the wide-character string versions of ##**Instrrev**##. {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Instrrev""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgInstr Instr]]## {{fbdoc item="back" value="CatPgString|String Functions"}}{{fbdoc item="title" value="INT"}}---- Returns the integer part of a number {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Int** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgDouble double]] ) [[KeyPgAs as]] [[KeyPgDouble double]] ## {{fbdoc item="usage"}}## //result// = **Int** ( //number// ) ## {{fbdoc item="param"}} ##//number//## the number {{fbdoc item="ret"}} Returns the largest integer less than or equal to the input. {{fbdoc item="desc"}} For example, ##Int(4.9)## will return ##4.0##, and ##Int(-1.3)## will return ##-2.0## The ##**Int**## unary ##[[KeyPgOperator operator]]## can be overloaded with user defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/math/int.bas"}}%%(freebasic) Print int(1.9) '' will print 1 Print int(-1.9) '' will print -2 %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgFix Fix]]## - ##[[KeyPgCint Cint]]## - ##[[KeyPgOperator Operator]]## {{fbdoc item="back" value="CatPgMath|Math"}}{{fbdoc item="title" value="INTEGER"}}---- Standard data type: 32 bit signed {{fbdoc item="syntax"}}## [[KeyPgDim dim]] //variable// [[KeyPgAs as]] **Integer** ## {{fbdoc item="desc"}} 32-bit signed whole-number data type. Can hold values from -2147483648 to 2147483647. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/datatype/integer.bas"}}%%(freebasic) Dim x As Integer = &H80000000 Dim y As Integer = &H7FFFFFFF Print "Integer Range = "; x; " to "; y %% **Output:** %%Integer Range = -2147483648 to 2147483647%% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang fb]]// and //[[CompilerOptlang -lang fblite]]// dialects, the ##**Integer**## data type is 32-bit. - In the //[[CompilerOptlang -lang qb]]// dialect, the ##**Integer**## data type is 16-bit. {{fbdoc item="diff"}} - The INTEGER type is 16-bit wide in QB. - None, if compiled in the //[[CompilerOptlang -lang qb]]// dialect. {{fbdoc item="see"}} - ##[[KeyPgLong Long]]## - ##[[KeyPgUinteger Uinteger]]## - ##[[KeyPgCint Cint]]## {{fbdoc item="back" value="CatPgStdDataTypes|Standard Data Types"}}{{fbdoc item="title" value="Is"}}---- Clause in the ##[[KeyPgSelectcase Select Case]]## statement block. {{fbdoc item="syntax"}}## **Case Is** //expression// ## {{fbdoc item="desc"}} Is specifies that a particular case inside a Select Case block will be evaluated based on an expression including the greater than (>) or less than (<) operator and a value. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgSelectcase Select Case]]## {{fbdoc item="back" value="CatPgMisc|Miscellaneous"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:54:14 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 2288c840908cb8c7d598e6a7e9791d68 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 1682 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="ISDATE"}}---- Tests if a string can be converted to a [[ProPgDates Date Serial]] {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""IsDate""** ( //stringdate// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## #include "vbcompat.bi" //result// = **""IsDate""**( //stringdate// ) ## {{fbdoc item="param"}} ##//stringdate//## the string to test {{fbdoc item="ret"}} Returns non-zero (-1) if the date string can be converted to a [[ProPgDates Date Serial]], otherwise returns zero (0). {{fbdoc item="desc"}} Date strings must be in the format set in the regional settings of the OS to be considered valid dates. ##**""IsDate""([[KeyPgDate Date]])**## will return non-zero (-1) only if the regional settings specify the same date format that QB used. The compiler will not recognize this function unless ##vbcompat.bi## or ##datetime.bi## is included. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/dates/isdate.bas"}}%%(freebasic) #include "vbcompat.bi" dim s as string, d as integer do print print "Enter a date: " line input s if s = "" then exit do if IsDate( s ) = 0 then print "'"; s; "' is not a valid date" else d = DateValue( s ) print "year = "; Year( d ) print "month = "; Month( d ) print "day = "; Day( d ) end if loop %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - [[ProPgDates Date Serials]] - ##[[KeyPgDateSerial DateSerial]]## - ##[[KeyPgTimeValue TimeValue]]## - ##[[KeyPgDateValue DateValue]]## {{fbdoc item="back" value="CatPgDate|Date and Time Functions"}} {{fbdoc item="title" value="KILL"}}---- Deletes a file from disk / storage media. {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Kill** ( [[KeyPgByref byref]] //filename// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **Kill**( //filename// ) ## {{fbdoc item="param"}} ##//filename//## The //filename// is the name of the disk file to delete. If the file is not in the current directory, a the path must also be given //[path]file//. {{fbdoc item="ret"}} Returns zero (0) on success, or non-zero on error. {{fbdoc item="desc"}} Deletes a file from disk / storage media. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/system/kill.bas"}}%%(freebasic) Dim filename As String = "file.ext" Dim result As Integer = Kill( filename ) If result <> 0 Then Print "error trying to kill " ; filename ; " !" %% {{fbdoc item="diff"}} - KILL can optionally be used as function in FreeBASIC. {{fbdoc item="see"}} - ##[[KeyPgShell Shell]]## - ##[[KeyPgRmdir Rmdir]]## {{fbdoc item="back" value="CatPgOpsys|Operating System Functions"}} {{fbdoc item="title" value="LBOUND"}}---- Returns the lower bound of an array's dimension {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Lbound** ( array() [[KeyPgAs as]] [[KeyPgAny any]], [[KeyPgByval byval]] //dimension// [[KeyPgAs as]] [[KeyPgInteger integer]] = 1 ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **Lbound**( //array// [, //dimension// ] ) ## {{fbdoc item="param"}} ##//array//## an array of any type ##//dimension//## the dimension to get lower bound of {{fbdoc item="ret"}} Returns the lower bound of an array's dimension. {{fbdoc item="desc"}} ##**Lbound**## returns the lowest value that can be used as an index into a particular dimension of an array. Array dimensions are numbered from one (1) to //n//, where //n// is the total number of dimensions. If ##//dimension//## is not specified, ##**Lbound**## will return the lower bound of the first dimension. If ##//dimension//## is less than one (1) or greater than the total number of dimensions (//n//) in the array, the result is undefined. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/array/lbound.bas"}}%%(freebasic) dim array(-10 to 10, 5 to 15, 1 to 2) as integer print lbound(array) 'returns -10 print lbound(array, 2) 'returns 5 print lbound(array, 3) 'returns 1 %% {{fbdoc item="see"}} - ##[[KeyPgUbound Ubound]]## - ##[[KeyPgStatic Static]]## - ##[[KeyPgDim Dim]]## - ##[[KeyPgRedim Redim]]## {{fbdoc item="back" value="CatPgArray|Array Functions"}}{{fbdoc item="title" value="LCASE"}}---- Returns a lower case copy of a string {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Lcase** [[KeyPgOverload overload]] ( [[KeyPgByref byref]] //str// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Lcase** ( [[KeyPgByref byref]] //str// [[KeyPgAs as]] [[KeyPgWstring wstring]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] ## {{fbdoc item="usage"}}## //result// = **Lcase**[$]( //str// ) ## {{fbdoc item="param"}} ##//str//## String to convert to lowercase. {{fbdoc item="ret"}} Lowercase copy of ##//str//##. {{fbdoc item="desc"}} Returns a copy of ##//str//## with all of the letters converted to lower case. If ##//str//## is empty, the null string (##"####"##) is returned. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/lcase.bas"}}%%(freebasic) print lcase("AbCdEfG") %% Output: %% abcdefg %% {{fbdoc item="see"}} - DOS does not support the wide-character string version of ##**Lcase**##. {{fbdoc item="lang"}} - The string type suffix "$" is obligatory in the //[[CompilerOptlang -lang qb]]// dialect. - The string type suffix "$" is optional in the //[[CompilerOptlang -lang fblite]]// and //[[CompilerOptlang -lang fb]]// dialects. {{fbdoc item="diff"}} - QB does not support Unicode. {{fbdoc item="see"}} - ##[[KeyPgUcase Ucase]]## {{fbdoc item="back" value="CatPgString|String Functions"}}{{fbdoc item="title" value="LEFT"}}---- Returns the leftmost substring of a string {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Left** [[KeyPgOverload overload]] ( [[KeyPgByref byref]] //str// [[KeyPgAs as]] [[KeyPgString string]], [[KeyPgByval byval]] //n// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Left** ( [[KeyPgByref byref]] //str// [[KeyPgAs as]] [[KeyPgWstring wstring]], [[KeyPgByval byval]] //n// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] ## {{fbdoc item="usage"}}## //result// = **Left**[$]( //str//, //n// ) ## {{fbdoc item="param"}} ##//str//## The source string.. ##//n//## The number of characters to return from the source string. {{fbdoc item="ret"}} Returns the leftmost substring from ##//str//##. {{fbdoc item="desc"}} Returns the leftmost ##//n//## characters starting from the left (beginning) of ##//str//##. If ##//str//## is empty, then the null string (##"####"##) is returned. If ##//n// <= 0## then the null string ("") is returned. If ##//n// > len(//str//)## then the entire source string is returned. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/left.bas"}}%%(freebasic) dim text as string = "hello world" print left(text, 5) %% will produce the output: %%hello %% An Unicode example: << dim text as wstring*20 text = "Привет, мир!" print left(text, 6) 'displays "Привет" <<::c:: {{fbdoc item="target"}} - DOS does not support the wide-character string version of **##Right##**. {{fbdoc item="lang"}} - The string type suffix "$" is obligatory in the //[[CompilerOptlang -lang qb]]// dialect. - The string type suffix "$" is optional in the //[[CompilerOptlang -lang fblite]]// and //[[CompilerOptlang -lang fb]]// dialects. {{fbdoc item="diff"}} - QB does not support Unicode. {{fbdoc item="see"}} - ##[[KeyPgRight Right]]## - ##[[KeyPgMidfunction Mid (Function)]]## {{fbdoc item="back" value="CatPgString|String Functions"}}{{fbdoc item="title" value="LEN"}}---- Returns the length of a variable or data type {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Len** ( [[KeyPgByref byref]] //variable// [[KeyPgAs as]] [[KeyPgAny any]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Len** ( //datatype// ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **Len**( //variable// ) ##//or//## //result// = **Len**( [[DataType DataType]] ) ## {{fbdoc item="param"}} ##//variable//## A variable of any type. ##//datatype//## A [[DataType DataType]]. {{fbdoc item="ret"}} Returns the size of a variable or [[DataType DataType]] in bytes. {{fbdoc item="desc"}} ##**Len**## returns the length of a variable or [[DataType DataType]], in bytes. In the first form, if ##//variable//## is of type ##[[KeyPgString String]]##, ##[[KeyPgWstring Wstring]]## or ##[[KeyPgZstring Zstring]]##, the length of the string in characters will be returned. Otherwise, the size of ##//variable//##'s type in bytes is returned. In the second form, if ##//datatype//## is ##[[KeyPgZstring Zstring]]## or ##[[KeyPgWstring Wstring]]##, the size of an ASCII or Unicode character is returned, respectively. If ##//datatype//## is ##[[KeyPgString String]]##, the size of the string descriptor type is returned. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/len.bas"}}%%(freebasic) print len("hello world") 'returns "11" print len(Integer) ' returns 4 type xyz a as integer b as integer end type print len(xyz) ' returns 8 %% {{fbdoc item="diff"}} - Can be used with built-in types and user-defined types. {{fbdoc item="see"}} - ##[[KeyPgSizeof Sizeof]]## {{fbdoc item="back" value="CatPgString|String Functions"}}{{fbdoc item="title" value="LET"}}---- Indicates the assignment operator. {{fbdoc item="syntax"}}## **Let** //variable// = //value// //or// **Let**( //variable1// [, //variable2// [, ... ]] ) = //udt// //or// [[KeyPgOperator operator]] //typename//.**Let** ( [ [[KeyPgByref byref]] | [[KeyPgByval byval]] ] rhs [[KeyPgAs as]] [[DataType datatype]] ) //statements// end operator ## {{fbdoc item="desc"}} Command intended to help the programmer to distinguish an assignment statement ( ##**Let** a=1## ) from an equality test ( ##If a=1 then ... ## ). As the compiler does not require it, it is usually omitted. **Let** can be used as a left-hand side operator to assign the members of a user defined type to multiple variables. //See [[KeyPgOpLetlist Operator Let() (Assignment)]]// **Let** is used with operator overloading to refer the assignment operator. //See [[KeyPgOpLet Operator Let (Assignment)]]// {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/misc/let.bas"}}%%(freebasic) '' Compile with -lang fblite or qb ' these two lines have the same effect: Let x = 100 x = 100 %% {{fbdoc item="lang"}} - The use of LET to indicate an assignment statement (##//LET variable = expr//##) is not allowed in the //[[CompilerOptlang -lang fb]]// dialect. - The UDT to multi-variable Let assignment is only available in the //[[CompilerOptlang -lang fb]]// dialect. - Overloading of operators is not available in the //[[CompilerOptlang -lang qb]]// and //[[CompilerOptlang -lang fblite]]// dialects. {{fbdoc item="diff"}} - None in the //[[CompilerOptlang -lang fb]]// dialect. - The Let operator is new to FreeBASIC. - The UDT to multi-variable Let assignment is new to FreeBASIC. {{fbdoc item="see"}} - ##[[KeyPgOpAssignment Operator = (Assignment)]]## - ##[[KeyPgOpLet Operator Let (Assignment)]]## - ##[[KeyPgOpLetlist Operator Let() (Assignment)]]## - ##[[KeyPgOperator Operator]]## {{fbdoc item="back" value="CatPgMisc|Miscellaneous"}}{{fbdoc item="title" value="LIB"}}---- Specifies the DLL where a sub or function can be found as part of a declaration {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] { [[KeyPgSub sub]] | [[KeyPgFunction function]] } //proc_name// **Lib** "//dllname//" [[KeyPgAlias alias]] "//symbol_name//" ( //arguments list// ) [[KeyPgAs as]] //return_type// ## {{fbdoc item="desc"}} In ##[[KeyPgSub Sub]]## and ##[[KeyPgFunction Function]]## declarations, ##**Lib**## indicates the dll containing the function. Libraries specified in this way are linked as if the library had been specified with ##[[KeyPgInclib #inclib]]##. When specifying ##//dllname//##, do not include the extension of the file name. For example, if the declaration is meant to reference the file ##mydll.dll## or ##mydll.so##, use ##**Lib** "mydll"##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/procs/mydll.bas"}}%%(freebasic) '' mydll.bas '' compile with: '' fbc -dll mydll.bas Public Function GetValue() As Integer Export Function = &h1234 End Function %% {{fbdoc item="filename" value="examples/manual/procs/lib.bas"}}%%(freebasic) Declare Function GetValue Lib "mydll" () As Integer Print "GetValue = &h"; Hex(GetValue()) ' Expected Output : ' GetValue = &h1234 %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDeclare Declare]]## - ##[[KeyPgInclib #inclib]]## {{fbdoc item="back" value="CatPgProcedures|Procedures"}}{{fbdoc item="title" value="LINE (GRAPHICS)"}}---- Draws a line {{fbdoc item="syntax"}}## **Line** [//target//,] [[STEP] (//x1//, //y1//)]-[STEP] (//x2, y2//) [, [//color//][, [B|BF][, //style//]]] or **Line** - (//x1//, //y1//) [, [//color//][, [B|BF][, //style//]]] ## {{fbdoc item="param"}} ##//target//## specifies buffer to draw on ##STEP## indicates that the starting coordinates are relative ##//(x1, y1)//## starting coordinates of the line ##STEP## indicates that ending coordinates are relative ##//(x2, y2)//## ending coordinates of the line ##//color//## the color attribute. ##B|BF## specifies box or box filled mode ##//style//## line style {{fbdoc item="desc"}} Graphics statement that draws a straight line or a box between two points. The action will take place on the current work page set via [[KeyPgScreenset ScreenSet]], or onto the buffer [[KeyPgGetgraphics Get]]/[[KeyPgPutgraphics Put]] buffer if specified. **Line** coordinates are affected by custom coordinates system set via [[KeyPgWindow Window]] and [[KeyPgViewgraphics View (Graphics)]] statements, and respect clipping rectangle set by [[KeyPgViewgraphics View (Graphics)]]. If a pair of coordinates is preceded by the ##STEP## keyword, the coordinates are assumed to be relative to the last graphics cursor position. If the ##B## flag is specified, a rectangle will be drawn instead of a line, with ##(//x1//,//y1//)-(//x2//,//y2//)## as the coordinates of the opposite rectangle corners. If ##BF## is specified, a filled rectangle will be drawn. ##//Color//## denotes the color attribute, which is mode specific (see [[KeyPgColor Color]] and [[KeyPgScreengraphics Screen (Graphics)]] for details). If omitted, the current foreground color as set by the [[KeyPgColor Color]] statement is used. ##//Style//##, if specified, allows styled line drawing; its value is interpreted as a 16bit bitmask, and **Line** will use it to skip pixel drawing. Starting at ##(//x1//,//y1//)##, the most significant bit of the style mask is checked: if 1, the pixel is drawn, if 0, it's skipped. This repeats for all the line pixels with the other bits, with the mask being reused when the 16 bits are all checked. When **Line** is used as //Line - (x, y)//, a Line is Drawn from the previous coordinate to the one specified, and no ##//x2//## or ##//y2//## parameters are needed. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/line.bas"}}%%(freebasic) '' draws a diagonal red line with a white box, and waits for 3 seconds screen 13 line (20, 20)-(300, 180), 4 line (140, 80)-(180, 120), 15, b line - ( 200, 200 ), 15 sleep 3000 %% {{fbdoc item="diff"}} - QB LINE could not draw onto GET/PUT buffers. {{fbdoc item="see"}} - [[KeyPgCircle Circle]] - [[KeyPgWindow Window]] - [[KeyPgViewgraphics View (Graphics)]] {{fbdoc item="back" value="CatPgGfx2D|2D Drawing Functions"}}{{fbdoc item="title" value="LINE INPUT"}}---- Reads one line of input from the keyboard {{fbdoc item="syntax"}}## **Line Input** [;] [//promptstring// {;|,} ] //stringvariable// ## {{fbdoc item="param"}} ##//promptstring//## prompt to display before waiting for input ##//stringvariable//## variable to receive the line of text {{fbdoc item="desc"}} Reads a line of text from the keyboard and stores it in a string variable. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/console/lineinput.bas"}}%%(freebasic) dim x as string line input "Enter a line:", x print "You entered '"; x; "'" %% {{fbdoc item="diff"}} - QBASIC only allowed literal strings for the prompt text. FreeBASIC allows any variable or constant string expression. {{fbdoc item="see"}} - ##[[KeyPgLineinputPp Line Input #]]## - ##[[KeyPgInput Input]]## {{fbdoc item="back" value="CatPgInput|User Input"}}{{fbdoc item="title" value="LINE INPUT #"}}---- Reads one line of text from a file {{fbdoc item="syntax"}}## **Line Input** #//file number, string_variable// ## {{fbdoc item="param"}} ##//file number//## file number of an open file ##//string_variable//## variable to receive the line of text {{fbdoc item="desc"}} Reads a line from an open text file and stores it in a string variable. A line of text ends at, but does not include the end of line characters. An end of line character may be the ##LF## character (##[[KeyPgChr Chr]]##(10)) or the ##CRLF## character pair (##[[KeyPgChr Chr]]##(13,10)). {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/fileio/lineinput.bas"}}%%(freebasic) ' compile with -lang qb Dim Filehandle As Integer Dim txt As String On Error Goto HandleErrors Filehandle = Freefile Open "test_text_file.txt" For Input As #filehandle If Lof(filehandle) > 0 Then Line Input #filehandle, txt Else Goto HandleErrors End If Close #filehandle print "The first line of test_text_file.txt is:" print txt HandleErrors: print "Error." Resume Next %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgInputPp Input #]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:54:27 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 063ec9ca7b88ddaf8e4ab81b8ae2b8f4 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 1696 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="LOBYTE"}}---- Macro to return the low byte of an expression {{fbdoc item="syntax"}}## [[KeyPgPpdefine #define]] **Lobyte**( //x// ) ( [[KeyPgCuint CUint]]( x ) [[KeyPgOpAnd and]] &h000000FF ) ## {{fbdoc item="usage"}}## //result// = **Lobyte**(//x//) ## {{fbdoc item="param"}} ##//x//## Number to retrieve low-byte from. {{fbdoc item="ret"}} The least significant byte of ##//x//##. {{fbdoc item="desc"}} Calculates the least significant byte (lo-byte) of a variable. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/bits/lobyte.bas"}}%%(freebasic) DIM N AS UINTEGER 'Note there are 16 bits N = &b1010101110000001 PRINT "N is "; N PRINT "The binary representation of N is "; BIN(N) PRINT "The most significant byte (MSB) of N is "; HIBYTE(N) PRINT "The least significant byte (LSB) of N is "; LOBYTE(N) PRINT "The binary representation of the MSB is "; BIN(HIBYTE(N)) PRINT "The binary representation of the LSB is "; BIN(LOBYTE(N)) SLEEP %% The output would look like: %% N Is 43905 The Binary representation of N Is 1010101110000001 The most significant Byte (MSB) of N Is 171 The least significant Byte (LSB) of N Is 129 The Binary representation of the MSB Is 10101011 The Binary representation of the LSB Is 10000001 %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__LOBYTE""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgHibyte Hibyte]]## {{fbdoc item="back" value="CatPgBits|Bit Manipulation"}} {{fbdoc item="title" value="LOC"}}---- Returns the file position where the last file read/write was performed {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Loc** ( [[KeyPgByval byval]] //filenum// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgLongint longint]] ## {{fbdoc item="usage"}}## //result// = **Loc** ( //filenum// ) ## {{fbdoc item="param"}} ##//filenum//## The file number of an open file. {{fbdoc item="ret"}} The file position where the last read/write was performed. {{fbdoc item="desc"}} Returns the position where the last file read/write was performed. The position is indicated in records: In files opened FOR RANDOM the record length specified when file was opened is used In text files (FOR INPUT|OUTPUT|APPEND, a record length of 128 bytes is supposed. In files opened for BINARY a 1 byte record length is used. In FreeBASIC the file position is 1 based, the first record of a file is record 1. When used with a serial device, ##**Loc**## returns the number of bytes waiting to be read from the serial device's input buffer. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/fileio/loc.bas"}}%%(freebasic) dim b as string if open com ("com1:9600,n,8,1,cs,rs,ds,bin" for binary as #1) <> 0 then print "unable to open serial port" end end if print "Sending command: AT" print #1, "AT" + chr(13, 10); sleep 500,1 print "Response:" while( loc(1) > 0 ) b = input(loc(1), 1) print b; wend close #1 %% {{fbdoc item="diff"}} - !!WRITEME!! ? {{fbdoc item="see"}} - ##[[KeyPgLof Lof]]## - ##[[KeyPgEof Eof]]## - ##[[KeyPgSeekreturn Seek (Function)]]## - ##[[KeyPgOpen Open]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}}{{fbdoc item="title" value="LOCAL"}}---- Error handling statement to set the current error handler {{fbdoc item="syntax"}}## On **Local** Error Goto //label// ## {{fbdoc item="usage"}}## On **Local** Error Goto //label// ## {{fbdoc item="param"}} ##//label//## label to jump to when error occurs {{fbdoc item="desc"}} The ##**Local**## clause in an ##[[KeyPgOnerror On Error]]## construction allows to define an error handler in the same ##[[KeyPgSub Sub]]##/##[[KeyPgFunction Function]]## the ##**On Local Error**## is. ##[[KeyPgExit Exit]]## ##[[KeyPgSub Sub]]##/##[[KeyPgFunction Function]]## must be used before the start of the error handler. Notice the program must be compiled with //[[CompilerOpte -e]]// or //[[CompilerOptex -ex]]// option for the QB-like error handling to work. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/error/local.bas"}}%%(freebasic) '' compile with -lang fblite or qb declare sub foo foo print "ok" sleep sub foo dim errno as integer on local error goto fail open "xzxwz.zwz" for input as #1 on local error goto 0 exit sub fail: ' here starts the error handler errno = err print "Error "; errno ' just print the error number sleep end sub %% {{fbdoc item="diff"}} - The LOCAL clause comes from PDS 7.1. QB 4.5 does not allow local error handling. {{fbdoc item="see"}} - {{fbdoc item="keyword" value="ProPgErrorHandling|Error Handling"}} {{fbdoc item="back" value="CatPgError|Error Handling Functions"}} {{fbdoc item="title" value="LOCATE"}}---- Sets the current cursor position {{fbdoc item="syntax"}}## **Locate** [//row// [[KeyPgAs as]] [[KeyPgInteger integer]] ][, [//column// [[KeyPgAs as]] [[KeyPgInteger integer]] ][, [//cursorstate// [[KeyPgAs as]] [[KeyPgInteger integer]] ]][, [//start// [[KeyPgAs as]] [[KeyPgInteger integer]] ][, [//stop// [[KeyPgAs as]] [[KeyPgInteger integer]] ] ## {{fbdoc item="usage"}}## **Locate** [//row//][, [//column//][, [//cursorstate//]] ## {{fbdoc item="param"}} ##//row//## the 1-based vertical character position in the console. ##//column//## the 1-based horizontal character position in the console. ##//cursorstate//## the state of the cursor. 0 is off, 1 is on (console-mode only). ##//start//## Ignored. Allowed for //[[CompilerOptlang -lang qb]]// dialect compatibility only. ##//stop//## Ignored. Allowed for //[[CompilerOptlang -lang qb]]// dialect compatibility only. {{fbdoc item="desc"}} Sets the text cursor in both graphics and console modes. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/console/locate.bas"}}%%(freebasic) locate 10 print "Current line:"; CSRLIN %% {{fbdoc item="diff"}} - The ##//start//## and ##//stop//## arguments have no effect in FreeBASIC. {{fbdoc item="see"}} - ##[[KeyPgCsrlin Csrlin]]## - ##[[KeyPgPos Pos]]## - ##[[KeyPgPrint Print]]## {{fbdoc item="back" value="CatPgConsole|Console Functions"}}{{fbdoc item="title" value="LOCK"}}---- Restricts read/write access to a file or portion of a file {{fbdoc item="syntax"}}## **Lock** #//filenum// [, //record// ] **Lock** #//filenum//, [ //start// ] To //end// ## {{fbdoc item="param"}} ##//filenum//## The file number used to ##[[KeyPgOpen Open]]## the file. ##//record//## The record (##[[KeyPgRandom Random]]## files) or byte position (##[[KeyPgBinary Binary]]## files) to lock. If omitted, the entire file is locked. ##//start//## The first record (##[[KeyPgRandom Random]]## files) or byte position (##[[KeyPgBinary Binary]]## files) to lock from. If omitted, the current record/byte position (##[[KeyPgSeekreturn Seek]]##(##//filenum//##)) is used. ##//end//## The last record (##[[KeyPgRandom Random]]## files) or byte position (##[[KeyPgBinary Binary]]## files) to lock to. {{fbdoc item="desc"}} ##**Lock**## temporarily restricts access by other threads or programs to a file, or portion of a file, usually to allow safe writing to it. After modifying the data, an ##[[KeyPgUnlock Unlock]]## with the same parameters as the ##**Lock**## should be issued. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/fileio/lock.bas"}}%%(freebasic) '' e.g. locking a file, reading 100 bytes, and unlocking it. '' To run, make sure there exists a file called 'file.ext' '' in the current directory that is at least 100 bytes. dim array(1 to 100) as integer dim f as integer, i as integer f = freefile open "file.ext" for binary as #f lock #f, 1 to 100 for i = 1 to 100 get #f, i, array(i) next unlock #f, 1 to 100 close #f %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgOpen Open]]## - ##[[KeyPgUnlock Unlock]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}}{{fbdoc item="title" value="LOF"}}---- Returns the length of an open disk file {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Lof** ( [[KeyPgByval byval]] //filenum// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgLongint longint]] ## {{fbdoc item="usage"}}## //result// = **Lof**( //filenum// ) ## {{fbdoc item="param"}} ##//filenum//## The file number of an open disk file. {{fbdoc item="ret"}} The length in bytes of an open disk file. {{fbdoc item="desc"}} Returns the length, in bytes, of a file opened previously with ##[[KeyPgOpen Open]]## using the given ##//filenum//##. With ##[[KeyPgOpenCom Open Com]]## it returns the length of the data pending to be read in the receive buffer. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/fileio/lof.bas"}}%%(freebasic) dim f as integer f = freefile open "file.ext" for binary as #f print lof(f) close #f %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgLoc Loc]]## - ##[[KeyPgEof Eof]]## - ##[[KeyPgOpen Open]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}}{{fbdoc item="title" value="LOG"}}---- Returns the natural logarithm of a given number {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Log** [[KeyPgCdecl cdecl]] ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgDouble double]] ) [[KeyPgAs as]] [[KeyPgDouble double]] ## {{fbdoc item="usage"}}## //result// = **Log** ( //number// ) ## {{fbdoc item="param"}} ##//number//## The number to calculate the natural log. {{fbdoc item="ret"}} Returns the logarithm with the base //e// (also know as the natural logarithm) of ##//number//##. {{fbdoc item="desc"}} There can be some confusion with this notation given that in mathematics the natural logarithm function is usually denoted **LN**, while the logarithm of base 10 is often denoted as LOG. FreeBASIC, like most computer programming languages, uses LOG to denote the natural logarithm. The required //number// argument can be any valid numeric expression greater than zero. If ##//number//## is zero, FreeBASIC returns -infinity. If ##//number//## is less than zero, FreeBASIC returns a domain error (-1#IND). If ##//number//## is an uninitialized variable, -infinity is returned. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/math/log.bas"}}%%(freebasic) 'Find the logarithm of any base FUNCTION LogBaseX (BYVAL Number AS DOUBLE, BYVAL BaseX AS DOUBLE) AS DOUBLE LogBaseX = LOG( Number ) / LOG( BaseX ) 'For reference: 1/log(10)=0.43429448 END FUNCTION PRINT "The log base 10 of 20 is:"; LogBaseX ( 20 , 10 ) PRINT "The log base 2 of 16 is:"; LogBaseX ( 16 , 2 ) SLEEP %% The output would look like: %% The log base 10 of 20 is: 1.301029995663981 The log base 2 of 16 is: 4 %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgExp Exp]]## {{fbdoc item="back" value="CatPgMath|Math"}}{{fbdoc item="title" value="LONG"}}---- Standard data type: signed integer having same size as ##[[KeyPgSizeof Sizeof]]([[KeyPgAny Any]] [[KeyPgPtr Ptr]])## {{fbdoc item="syntax"}}## [[KeyPgDim dim]] //variable// [[KeyPgAs as]] **Long** ## {{fbdoc item="desc"}} Depending on the platform, same as ##[[KeyPgInteger Integer]]## or ##[[KeyPgLongint Longint]]##. A 32-bit or 64-bit signed whole-number data type. ##**Long**## has the same size as ##[[KeyPgSizeof Sizeof]]([[KeyPgAny Any]] [[KeyPgPtr Ptr]])##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/datatype/long.bas"}}%%(freebasic) Dim x As Long = &H80000000 Dim y As Long = &H7FFFFFFF Print "Long Range = "; x; " to "; y %% **Output:** %%Long Range = -2147483648 to 2147483647%% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang fb]]// and //[[CompilerOptlang -lang fblite]]// dialects, the ##**Long**## data type has the same size as ##[[KeyPgSizeof Sizeof]]([[KeyPgAny Any]] [[KeyPgPtr Ptr]])##. - In the //[[CompilerOptlang -lang qb]]// dialect, the ##**Long**## data type is always 32-bit. {{fbdoc item="diff"}} - In QB, LONG is always 32-bit. - None, if compiled in the //[[CompilerOptlang -lang qb]]// dialect. {{fbdoc item="see"}} - ##[[KeyPgInteger Integer]]## - ##[[KeyPgLongint Longint]]## - ##[[KeyPgUlong Ulong]]## {{fbdoc item="back" value="CatPgStdDataTypes|Standard Data Types"}}{{fbdoc item="title" value="LONGINT"}}---- Standard data type: 64 bit signed {{fbdoc item="syntax"}}## [[KeyPgDim dim]] //variable// [[KeyPgAs as]] **Longint** ## {{fbdoc item="desc"}} A 64-bit signed whole-number data type. Can hold values from -9 223 372 036 854 775 808 to 9 223 372 036 854 775 807 {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/datatype/longint.bas"}}%%(freebasic) Dim x As LongInt = &H8000000000000000 Dim y As Longint = &H7FFFFFFFFFFFFFFF Print "LongInt Range = "; x; " to "; y %% **Output:** %%LongInt Range = -9223372036854775808 to 9223372036854775807%% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Longint""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgUlongint Ulongint]]## - ##[[KeyPgClngint Clngint]]## {{fbdoc item="back" value="CatPgStdDataTypes|Standard Data Types"}}{{fbdoc item="title" value="LOOP"}}---- Control flow statement for looping. {{fbdoc item="syntax"}}## **Do** [ //statement block// ] **Loop** [ { **Until** | **While** } //condition// ] ## {{fbdoc item="see"}} - ##[[KeyPgDoloop Do...Loop]]## {{fbdoc item="back" value="CatPgMisc|Miscellaneous"}} {{fbdoc item="title" value="LOWORD"}}---- Macro to return the low word of an expression {{fbdoc item="syntax"}}## [[KeyPgPpdefine #define]] **Loword**( //x// ) ([[KeyPgCuint CUint]](//x//) [[KeyPgOpAnd and]] &h0000FFFF) ## {{fbdoc item="usage"}}## //result// = **Loword**(//x//) ## {{fbdoc item="param"}} ##//x//## Number to retrieve low-word from. {{fbdoc item="ret"}} The least significant word of ##//x//##. {{fbdoc item="desc"}} A word is 2 bytes and a byte is 8 bits. This is best understood by an example. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/bits/loword.bas"}}%%(freebasic) DIM N AS UINTEGER 'Note there are 32 bits N = &b10000000000000011111111111111111 PRINT "N is "; N PRINT "The binary representation of N is "; BIN(N) PRINT "The most significant word (MSW) of N is "; HIWORD(N) PRINT "The least significant word (LSW) of N is "; LOWORD(N) PRINT "The binary representation of the MSW is "; BIN(HIWORD(N)) PRINT "The binary representation of the LSW is "; BIN(LOWORD(N)) SLEEP %% The output would look like: %% N Is 2147614719 The Binary representation of N Is 10000000000000011111111111111111 The most significant word (MSW) of N Is 32769 The least significant word (LSW) of N Is 65535 The Binary representation of the MSW Is 1000000000000001 The Binary representation of the LSW Is 1111111111111111 %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__LOWORD""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgHiword Hiword]]## - ##[[KeyPgHibyte Hibyte]]## - ##[[KeyPgLoByte Lobyte]]## {{fbdoc item="back" value="CatPgBits|Bit Manipulation"}}{{fbdoc item="title" value="LPOS"}}---- Returns the number of characters sent to the printer port in the last ##[[KeyPgLprint Lprint]]## statement. {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Lpos** ( [[KeyPgByval byval]] //printer// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = LPOS(//printer//) ## {{fbdoc item="param"}} ##//printer//## Either 0, 1, 2 or 3. Represents the printer port (LPT#) {{fbdoc item="ret"}} Returns the number of characters sent. {{fbdoc item="desc"}} Used to determine, from the last ##[[KeyPgLprint Lprint]]##, how many characters were sent to the printer port. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/hardware/lpos.bas"}}%%(freebasic) ' compile with -lang fblite or qb DIM test AS STRING = "LPrint Example test" PRINT "Sending '" + test + "' to LPT1 (default)" LPRINT test PRINT "LPT1 last recieved " + Str(LPOS(1)) + " characters" PRINT "String sent was " + Str(len(test)) + " characters long" SLEEP %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgLprint Lprint]]## {{fbdoc item="back" value="CatPgMisc|Miscellaneous"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:54:40 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: cb503e48d5b938b7d5b920e6638f015f Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 2249 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="LPRINT"}}---- Writes text to the default printer. {{fbdoc item="syntax"}}## **Lprint** [ [[KeyPgPrintusing Using]] //formatstring//,] [//expressionlist//] [(, | ;)] ... ## {{fbdoc item="param"}} ##//formatstring//## String specifying the output format. ##//expressionlist//## List of variables to output according to the specified format. {{fbdoc item="desc"}} Prints ##//expressionlist//## to the printer attached to the parallel port LPT1, or if it does not exist, to the default printer. To print to a printer different from the default one, use ##[[KeyPgOpenLpt OPEN LPT]]##. The ##[[KeyPgPrintusing Using]]## clause formats ##//expresionlist//## according to ##//formatstring//##. Any data type but a UDT can be passed to **##Lprint##** ##//expressionlist##//, expressions do **not** have to be converted to strings first. Using a comma (,) as separator or in the end of the ##//expressionlist//## will place the cursor in the next column (every 14 characters), using a semi-colon (;) won't move the cursor. If neither of them are used in the end of the ##//expressionlist//##, then a new-line will be printed. Some printers will not print at all until a character 12 (End of Page) is printed. Internally, FreeBASIC uses the special file number -1 for printing using **##Lprint##**. This file number may be safely closed using ##[[KeyPgClose Close]]## -1. Next use of **##Lprint##** will automatically reopen it as needed. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/hardware/lprint.bas"}}%%(freebasic) '' Compile with -lang fblite or qb '' new-line LPRINT "Hello World!" '' no new-line LPRINT "Hello"; "World"; "!"; LPRINT '' column separator LPRINT "Hello!", "World!" LPRINT CHR(12) %% {{fbdoc item="diff"}} - None {{fbdoc item="lang"}} - ##**Lprint**## is not supported in the //[[CompilerOptlang -lang fb]]// dialect. In this dialect the printer must be properly opened with ##[[KeyPgOpenLpt Open LPT]]## and ##[[KeyPgPrintPp Print #]]## must be used to print. {{fbdoc item="see"}} - ##[[KeyPgOpenLpt Open LPT]]## - ##[[KeyPgPrint Print]]## - ##[[KeyPgPrintPp Print #]]## - ##[[KeyPgWrite Write]]## {{fbdoc item="back" value="CatPgMisc|Miscellaneous"}} {{fbdoc item="title" value="LSET"}}---- Left-justifies a string {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Lset** [[KeyPgOverload overload]] ( [[KeyPgByref byref]] //dst// [[KeyPgAs as]] [[KeyPgString string]], [[KeyPgByref byref]] //src// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Lset** ( [[KeyPgByval byval]] //dst// [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgPtr ptr]], [[KeyPgByval byval]] //src// [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgPtr ptr]] ) ## {{fbdoc item="usage"}}## **Lset** //dst//, //src// **Lset** //dst_udt//, //src_udt// ## {{fbdoc item="param"}} ##//src//## String variable to receive the data. ##//dst//## Source string to get the data. ##//dst_udt//## User defined ##[[KeyPgType Type]]## to receive the data. ##//src_udt//## User defined ##[[KeyPgType Type]]## to copy the data from. {{fbdoc item="desc"}} ##**Lset**## left justifies text into the string buffer ##//dst//##, filling the left part of the string with ##//src//## and the right part with spaces. The string buffer size is not modified. For compatibility with QBasic, ##**Lset**## can also copy a user defined type variable into another one. The copy is made byte for byte, without any care for fields or alignment. It's up to the programmer to take care for the validity of the result. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/lset.bas"}}%%(freebasic) dim buffer as string buffer = space(10) lset buffer, "91.5" print "-[" & buffer & "]-" %% {{fbdoc item="filename" value="examples/manual/strings/lset-udt.bas"}}%%(freebasic) type mytype1 x as integer y as integer end type type mytype2 z as integer end type dim a as mytype1 , b as mytype2 b.z = 1234 lset a, b print a.x %% {{fbdoc item="diff"}} -In QB, the syntax was ##**Lset** //dst// = //src//## {{fbdoc item="see"}} - ##[[KeyPgRset Rset]]## - ##[[KeyPgSpace Space]]## - ##[[KeyPgPutfileio Put (File I/O)]]## - ##[[KeyPgMkd Mkd]]## - ##[[KeyPgMki Mki]]## - ##[[KeyPgMkl Mkl]]## - ##[[KeyPgMks Mks]]## {{fbdoc item="back" value="CatPgString|String Functions"}}{{fbdoc item="title" value="LTRIM"}}---- Removes surrounding substrings or characters on the left side of a string {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Ltrim** [[KeyPgOverload overload]] ( [[KeyPgByref byref]] //str// [[KeyPgAs as]] [[KeyPgString string]], [ **Any** ] [[KeyPgByref byref]] //trimset// [[KeyPgAs as]] [[KeyPgString string]] = " " ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Ltrim** ( [[KeyPgByref byref]] //str// [[KeyPgAs as]] [[KeyPgWstring wstring]], [ **Any** ] [[KeyPgByref byref]] //trimset// [[KeyPgAs as]] [[KeyPgWstring wstring]] = [[KeyPgWstr Wstr]](" ") ) [[KeyPgAs as]] [[KeyPgWstring wstring]] ## {{fbdoc item="usage"}}## //result// = **Ltrim**[$]( //str// [, [ **Any** ] //trimset// ] ) ## {{fbdoc item="param"}} ##//str//## The source string. ##//trimset//## The substring to trim. {{fbdoc item="ret"}} Returns the trimmed string. {{fbdoc item="desc"}} This procedure trims surrounding characters from the left (beginning) of a source string. Substrings matching ##//trimset//## will be trimmed if specified, otherwise spaces ([[CptAscii ASCII]] code 32) are trimmed. If the ##**Any**## keyword is used, any character matching a character in ##//trimset//## will be trimmed. All comparisons are case-sensitive. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/ltrim.bas"}}%%(freebasic) dim s1 as string = " 101 Things to do." print "'" + ltrim(s1) + "'" print "'" + ltrim(s1, " 01") + "'" print "'" + ltrim(s1, any " 01") + "'" dim s2 as string = "BaaBaaBAA Test Pattern" Print "'" + ltrim(s2, "Baa") + "'" Print "'" + ltrim(s2, any "BaA") + "'" %% will produce the output: %%'101 Things to do.' ' 101 Things to do.' 'Things to do.' 'BAA Test Pattern' ' Test Pattern' %% {{fbdoc item="lang"}} - DOS does not support the wide-character version of ##**Ltrim**##. - The string type suffix "$" is obligatory in the //[[CompilerOptlang -lang qb]]// dialect. - The string type suffix "$" is optional in the //[[CompilerOptlang -lang fblite]]// and //[[CompilerOptlang -lang fb]]// dialects. {{fbdoc item="diff"}} - QB does not support specifying a ##//trimset//## string or the ##ANY## clause. {{fbdoc item="see"}} - ##[[KeyPgRtrim Rtrim]]## - ##[[KeyPgTrim Trim]]## {{fbdoc item="back" value="CatPgString|String Functions"}}{{fbdoc item="title" value="FUNCTION (Member)"}}---- Declares or defines a member procedure returning a value. {{fbdoc item="syntax"}}## { [[KeyPgType Type]] | [[KeyPgClass Class]] | [[KeyPgUnion Union]] } //typename// [[KeyPgDeclare declare]] [ [[KeyPgStaticMember static]] | [[KeyPgConstMember const]] ] **Function** //fieldname// [//calling convention specifier//] [ [[KeyPgAlias alias]] //external_name// ] ( [ //parameters// ] ) [[KeyPgAs as]] [[DataType datatype]] [ [[KeyPgStatic Static]] ] End { [[KeyPgType Type]] | [[KeyPgClass Class]] | [[KeyPgUnion Union]] } **Function** //typename//.//fieldname// ( [ //parameters// ] ) [[KeyPgAs as]] [[DataType datatype]] //statements// **End Function** ## {{fbdoc item="param"}} ##//typename//## name of the ##[[KeyPgType Type]]##, ##[[KeyPgClass Class]]##, or ##[[KeyPgUnion Union]]## ##//fieldname//## name of the procedure ##//external_name//## name of field as seen when externally linked ##//parameters//## the parameters to be passed to the procedure ##//calling convention specifier//## can be one of: ##[[KeyPgCdecl Cdecl]]##, ##[[KeyPgStdcall Stdcall]]## or ##[[KeyPgPascal Pascal]]## {{fbdoc item="desc"}} ##**Function**## members are accessed with ##[[KeyPgOpMemberAccess Operator . (Member access)]]## or ##[[KeyPgOpPtrMemberAccess Operator -> (Pointer to member access)]]## to call a member procedure that returns a value. The procedure may optionally accept parameters either ##[[KeyPgByval byval]]## or ##[[KeyPgByref byref]]##. ##//typename//## be overloaded without explicit use of the ##[[KeyPgOverload Overload]]## keyword. ##//typename//## is the name of the type for which the ##**Function**## method is declared and defined. Name resolution for ##//typename//## follows the same rules as procedures when used in a ##[[KeyPgNamespace Namespace]]##. A hidden ##[[KeyPgThis this]]## parameter having the same type as ##//typename//## is passed to non-static member procedures. ##[[KeyPgThis this]]## is used to access the fields of the ##[[KeyPgType Type]]##, ##[[KeyPgClass Class]]##, or ##[[KeyPgUnion Union]]##. A ##[[KeyPgStaticMember Static (Member)]]## may be declared using the ##**Static**## specifier. A ##[[KeyPgConstMember Const (Member)]]## may be declared using the ##**Const**## specifier. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/udt/function.bas"}}%%(freebasic) #include "vbcompat.bi" type Date value as double declare static function Today() as Date declare function year() as integer declare function month() as integer declare function day() as integer end type function Date.Today() as Date return type(now()) end function function Date.Year() as integer return ..Year(value) end function function Date.Month() as integer return ..Month(value) end function function Date.Day() as integer return ..Day(value) end function dim d as Date = Date.Today print "Year = "; d.Year print "Month = "; d.Month print "Day = "; d.Day %% {{fbdoc item="lang"}} - Only available in the //[[CompilerOptlang -lang fb]]// dialect. {{fbdoc item="see"}} - ##[[KeyPgClass Class]]## - ##[[KeyPgFunction Function]]## - ##[[KeyPgMemberSub Sub (Member)]]## - ##[[KeyPgType Type]]## {{fbdoc item="back" value="CatPgUserDefTypes|User Defined Types"}}{{fbdoc item="title" value="SUB (Member)"}}---- Declares or defines a member procedure. {{fbdoc item="syntax"}}## { [[KeyPgType Type]] | [[KeyPgClass Class]] | [[KeyPgUnion Union]] } //typename// [[KeyPgDeclare declare]] [ [[KeyPgStaticMember static]] ] **Sub** //fieldname// [//calling convention specifier//] [ [[KeyPgAlias alias]] //external_name// ] ( [ //parameters// ] ) [ [[KeyPgStatic Static]] ] End { [[KeyPgType Type]] | [[KeyPgClass Class]] | [[KeyPgUnion Union]] } **Sub** //typename//.//fieldname// ( [ //parameters// ] ) //statements// **End Sub** ## {{fbdoc item="param"}} ##//typename//## name of the ##[[KeyPgType Type]]##, ##[[KeyPgClass Class]]##, or ##[[KeyPgUnion Union]]## ##//fieldname//## name of the procedure ##//external_name//## name of field as seen when externally linked ##//parameters//## the parameters to be passed to the procedure ##//calling convention specifier//## can be one of: ##[[KeyPgCdecl Cdecl]]##, ##[[KeyPgStdcall Stdcall]]## or ##[[KeyPgPascal Pascal]]## {{fbdoc item="desc"}} ##**Sub**## members are accessed with ##[[KeyPgOpMemberAccess Operator . (Member access)]]## or ##[[KeyPgOpPtrMemberAccess Operator -> (Pointer to member access)]]## to call a member procedure and may optionally accept parameters either ##[[KeyPgByval byval]]## or ##[[KeyPgByref byref]]##. ##//typename//## be overloaded without explicit use of the ##[[KeyPgOverload Overload]]## keyword. ##//typename//## is the name of the type for which the ##**Sub**## method is declared and defined. Name resolution for ##//typename//## follows the same rules as procedures when used in a ##[[KeyPgNamespace Namespace]]##. A hidden ##[[KeyPgThis this]]## parameter having the same type as ##//typename//## is passed to non-static member procedures. ##[[KeyPgThis this]]## is used to access the fields of the ##[[KeyPgType Type]]##, ##[[KeyPgClass Class]]##, or ##[[KeyPgUnion Union]]##. A ##[[KeyPgStaticMember Static (Member)]]## may be declared using the ##**Static**## specifier. A ##[[KeyPgConstMember Const (Member)]]## may be declared using the ##**Const**## specifier. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/udt/sub.bas"}}%%(freebasic) type Statistics count as single sum as single declare sub AddValue( byval x as single ) declare sub ShowResults( ) end type sub Statistics.AddValue( byval x as single ) count += 1 sum += x end sub sub Statistics.ShowResults( ) print "Number of Values = "; count print "Average = "; if( count > 0 ) then print sum / count else print "N/A" end if end sub dim stats as Statistics stats.AddValue 17.5 stats.AddValue 20.1 stats.AddValue 22.3 stats.AddValue 16.9 stats.ShowResults %% **Output:** %% Number of Values = 4 Average = 19.2 %% {{fbdoc item="lang"}} - Only available in the //[[CompilerOptlang -lang fb]]// dialect. {{fbdoc item="see"}} - ##[[KeyPgClass Class]]## - ##[[KeyPgMemberFunction Function (Member)]]## - ##[[KeyPgSub Sub]]## - ##[[KeyPgType Type]]## {{fbdoc item="back" value="CatPgUserDefTypes|User Defined Types"}}{{fbdoc item="title" value="$DYNAMIC"}}---- Metacommand to change the way arrays are allocated {{fbdoc item="syntax"}}## **'$Dynamic** //or// [[KeyPgRem rem]] **$Dynamic** ## {{fbdoc item="desc"}} **'$Dynamic** is metacommand that specifies that any following array declarations are variable-length, whether they are declared with constant subscript ranges or not. This remains in effect for the rest of the module in which **'$Dynamic** is used, and can be overridden with ##[[KeyPgMetaStatic $Static]]##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/meta/dynamic.bas"}}%%(freebasic) ' compile with -lang fblite or qb '$DYNAMIC Dim a(100) '...... ReDim a(200) %% {{fbdoc item="lang"}} - Only available in the //[[CompilerOptlang -lang fblite]]// and //[[CompilerOptlang -lang qb]]// dialects. {{fbdoc item="diff"}} - When used inside comments it must be the first token {{fbdoc item="see"}} - ##[[KeyPgMetaStatic $Static]]## - ##[[KeyPgDim Dim]]## - ##[[KeyPgRedim Redim]]## - ##[[KeyPgErase Erase]]## - ##[[KeyPgOptiondynamic Option Dynamic]]## {{fbdoc item="back" value="CatPgArray|Array Functions"}}{{fbdoc item="back" value="CatPgCompilerSwitches|Compiler Switches"}}{{fbdoc item="back" value="CatPgPreProcess|Preprocessor"}}{{fbdoc item="title" value="$INCLUDE"}}---- Metacommand statement to include contents of another source file {{fbdoc item="syntax"}}## '$Include [once]: '//file//' //or// [[KeyPgRem rem]] $Include [once]: '//file//' ## {{fbdoc item="desc"}} ##**$include**## inserts source code from another file at the point where the ##**$include**## metacommand appears. This has the effect of compiling the source code from the include file as though it were part of the source file that includes it. Once the compiler has reached the end of the include file, the original source file continues to be compiled. The ##**once**## specifier tells the compiler to include the file only once even if it is included several times by the source code. ##**'$Include:**## exists for compatibility with QuickBasic. It is recommended to use ##[[KeyPgInclude #include]]## instead. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/meta/header.bi"}}%%(freebasic) ' header.bi file Type FooType Bar As Byte Barbeque As Byte End Type Dim Foo As FooType %% {{fbdoc item="filename" value="examples/manual/meta/include.bas"}}%%(freebasic) '' compile with -lang fblite or qb '' main.bas file '$INCLUDE: "header.bi" Foo.Bar = 1 Foo.Barbeque = 2 %% {{fbdoc item="lang"}} - Only available in the //[[CompilerOptlang -lang fblite]]// and //[[CompilerOptlang -lang qb]]// dialects. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgInclude #include]]## {{fbdoc item="back" value="CatPgCompilerSwitches|Compiler Switches"}}{{fbdoc item="title" value="$STATIC"}}---- Metacommand to change the way arrays are allocated {{fbdoc item="syntax"}}## **'$Static** //or// [[KeyPgRem rem]] **$Static** ## {{fbdoc item="desc"}} ##**'$Static**## is a metacommand that overrides the behavior of ##[[KeyPgMetaDynamic $Dynamic]]##, that is, arrays declared with constant subscript ranges are fixed-length. This remains in effect for the rest of the module in which ##**'$Static**## is used, and can be overridden with ##[[KeyPgMetaDynamic $Dynamic]]##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/meta/static.bas"}}%%(freebasic) ' compile with -lang fblite or qb '$dynamic Dim a(100) '<= len(//str//)## then all of the remaining characters are returned. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/mid-func.bas"}}%%(freebasic) PRINT MID("abcdefg", 3, 2) PRINT MID("abcdefg", 3) PRINT MID("abcdefg", 2, 1) %% will produce the output: %%cd cdefg b %% A Unicode example: ~&Wiki: code rendered this way to allow display of the Unicode characters. < result Then Print "error: unable to create folder " & pathname & " in the current path." %% {{fbdoc item="target"}} - Linux requires the //filename// case matches the real name of the file. Windows and DOS are case insensitive. - Path separators in Linux are forward slashes / . Windows uses backward slashes \ but it allows for forward slashes . DOS uses backward \ slashes. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgShell Shell]]## - ##[[KeyPgChdir Chdir]]## - ##[[KeyPgRmdir Rmdir]]## {{fbdoc item="back" value="CatPgOpsys|Operating System Functions"}}{{fbdoc item="title" value="MKI"}}---- Does a binary copy from a ##[[KeyPgInteger integer]]## variable to a ##[[KeyPgString string]]##, setting its length to 4 bytes {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Mki** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgString string]] ## {{fbdoc item="usage"}}## //result// = **Mki**[$]( //number// ) ## {{fbdoc item="param"}} ##//number//## A ##[[KeyPgInteger integer]]## variable to binary copy to a ##[[KeyPgString string]]##. {{fbdoc item="ret"}} Returns a ##[[KeyPgString string]]## with a binary copy of the ##[[KeyPgInteger integer]]##. {{fbdoc item="desc"}} Does a binary copy from an ##[[KeyPgInteger Integer]]## variable to a ##[[KeyPgString string]]##, setting its length to 4 bytes. The resulting string can be read back to an ##[[KeyPgInteger Integer]]## by ##[[KeyPgCvi Cvi]]## This function is useful to write numeric values to buffers without using a ##[[KeyPgType Type]]## definition. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/mki.bas"}}%%(freebasic) dim a as integer, b as string a=4534 b=mki(a) print a, cvi(b) sleep %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, ##**Mki**## returns a 2-byte-string, since a QB integer is only 16 bits. - The string type suffix "$" is obligatory in the //[[CompilerOptlang -lang qb]]// dialect. - The string type suffix "$" is optional in the //[[CompilerOptlang -lang fblite]]// and //[[CompilerOptlang -lang fb]]// dialects. {{fbdoc item="see"}} - ##[[KeyPgCvi Cvi]]## {{fbdoc item="back" value="CatPgString|String Functions"}}{{fbdoc item="title" value="MKL"}}---- Does a binary copy from a ##[[KeyPgInteger long]]## variable to a ##[[KeyPgString string]]##, setting its length to 4 bytes {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Mkl** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgString string]] ## {{fbdoc item="usage"}}## //result// = **Mkl**( //number// ) ## {{fbdoc item="param"}} ##//number//## A ##[[KeyPgInteger integer]]## variable to binary copy to a ##[[KeyPgString string]]##. {{fbdoc item="ret"}} Returns a ##[[KeyPgString string]]## with a binary copy of the ##[[KeyPgInteger long]]##. {{fbdoc item="desc"}} Does a binary copy from a long variable to a ##[[KeyPgString string]]##, setting its length to 4 bytes. The resulting string can be read back to a ##[[KeyPgLong Long]]## by ##[[KeyPgCvl Cvl]]##. This function is useful to write numeric values to buffers without using a ##[[KeyPgType Type]]## definition. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/mkl.bas"}}%%(freebasic) dim a as long, b as string a = 4534 b = mkl(a) print a, cvl(b) sleep %% {{fbdoc item="lang"}} - The string type suffix "$" is obligatory in the //[[CompilerOptlang -lang qb]]// dialect. - The string type suffix "$" is optional in the //[[CompilerOptlang -lang fblite]]// and //[[CompilerOptlang -lang fb]]// dialects. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgMkd Mkd]]## - ##[[KeyPgMki Mki]]## - ##[[KeyPgMks Mks]]## - ##[[KeyPgCvd Cvd]]## - ##[[KeyPgCvi Cvi]]## - ##[[KeyPgCvl Cvl]]## - ##[[KeyPgCvs Cvs]]## {{fbdoc item="back" value="CatPgString|String Functions"}}{{fbdoc item="title" value="MKLONGINT"}}---- Does a binary copy from a ##[[KeyPgLongint longint]]## variable to a ##[[KeyPgString string]]##, setting its length to 8 bytes {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Mklongint** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgLongint longint]] ) [[KeyPgAs as]] [[KeyPgString string]] ## {{fbdoc item="usage"}}## //result// = **Mklongint**[$]( //number// ) ## {{fbdoc item="param"}} ##//number//## A ##[[KeyPgLongint longint]]## variable to binary copy to a ##[[KeyPgString string]]##. {{fbdoc item="ret"}} Returns a ##[[KeyPgString string]]## with a binary copy of the ##[[KeyPgLongint longint]]##. {{fbdoc item="desc"}} Does a binary copy from a ##[[KeyPgLongint Longint]]## variable to a string, setting its length to 8 bytes. The resulting string can be read back to a longint by ##[[KeyPgCvlongint Cvlonging]]## This function is useful to write numeric values to buffers without using a ##[[KeyPgType Type]]## definition. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/mklongint.bas"}}%%(freebasic) dim a as longint, b as string a = 4534 b = mklongint(a) print a, cvlongint(b) sleep %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Mklongint""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgCvlongint Cvlongint]]## {{fbdoc item="back" value="CatPgString|String Functions"}}{{fbdoc item="title" value="MKS"}}---- Does a binary copy from a ##[[KeyPgSingle single]]## variable to a ##[[KeyPgString string]]##, setting its length to 4 bytes {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Mks** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgSingle single]] ) [[KeyPgAs as]] [[KeyPgString string]] ## {{fbdoc item="usage"}}## //result// = **Mks**[$]( //number// ) ## {{fbdoc item="param"}} ##//number//## A ##[[KeyPgSingle single]]## variable to binary copy to a ##[[KeyPgString string]]##. {{fbdoc item="ret"}} Returns a ##[[KeyPgString string]]## with a binary copy of the ##[[KeyPgSingle single]]##. {{fbdoc item="desc"}} Does a binary copy from a ##[[KeyPgSingle Single]]## variable to a ##[[KeyPgString string]]##, setting its length to 4 bytes. The resulting string can be read back to a single by ##[[KeyPgCvs Cvs]]##. This function is useful to write numeric values to buffers without using a ##[[KeyPgType Type]]## definition. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/mks.bas"}}%%(freebasic) dim n as single, e as string n = 1.2345 e = mks(n) print n, cvs(e) %% {{fbdoc item="lang"}} - The string type suffix "$" is obligatory in the //[[CompilerOptlang -lang qb]]// dialect. - The string type suffix "$" is optional in the //[[CompilerOptlang -lang fblite]]// and //[[CompilerOptlang -lang fb]]// dialects. {{fbdoc item="diff"}} -None {{fbdoc item="see"}} - ##[[KeyPgMki Mki]]## - ##[[KeyPgMkl Mkl]]## - ##[[KeyPgMks Mks]]## - ##[[KeyPgCvd Cvd]]## - ##[[KeyPgCvi Cvi]]## - ##[[KeyPgCvl Cvl]]## - ##[[KeyPgCvs Cvs]]## {{fbdoc item="back" value="CatPgString|String Functions"}}{{fbdoc item="title" value="MKSHORT"}}---- Does a binary copy from a ##[[KeyPgShort short]]## variable to a ##[[KeyPgString string]]##, setting its length to 2 bytes {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Mkshort** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgShort short]] ) [[KeyPgAs as]] [[KeyPgString string]] ## {{fbdoc item="usage"}}## //result// = **Mkshort**[$](//number//) ## {{fbdoc item="param"}} ##//number//## A ##[[KeyPgShort short]]## variable to binary copy to a ##[[KeyPgString string]]##. {{fbdoc item="ret"}} Returns a ##[[KeyPgString string]]## with a binary copy of the ##[[KeyPgShort short]]##. {{fbdoc item="desc"}} Does a binary copy from a SHORT variable to a string, setting its length to 2 bytes. The resulting string can be read back to a ##[[KeyPgShort short]]## by ##[[KeyPgCvshort Cvshort]]## This function is useful to write numeric values to buffers without using a ##[[KeyPgType Type]]## definition. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/mkshort.bas"}}%%(freebasic) dim a as short, b as string a = 4534 b = mkshort(a) print a, cvshort(b) sleep %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Mkshort""**##. {{fbdoc item="diff"}} - In QBasic this function is called ##**Mki**##. {{fbdoc item="see"}} - ##[[KeyPgCvshort Cvshort]]## {{fbdoc item="back" value="CatPgString|String Functions"}}{{fbdoc item="title" value="CONSTRUCTOR (Module)"}}---- Specifies execution of a procedure before module-level code {{fbdoc item="syntax"}}## [[[KeyPgPublic Public]] | [[KeyPgPrivate Private]]] [[KeyPgSub Sub]] //procedure_name// [[[KeyPgAlias Alias]] "//external_identifier//"] [()] **Constructor** [//priority//] [[[KeyPgStatic Static]]] { //procedure body// } [[KeyPgEndblock End]] [[KeyPgSub Sub]] ## {{fbdoc item="desc"}} The ##**Constructor**## keyword is used in ##[[KeyPgSub Sub]]## definitions to force execution of the procedure prior to that of module-level code. Procedures defined as constructors may be used the same way as ordinary procedures, that is, they may be called from within module-level code, as well as other procedures. The procedure must have an empty parameter list. A compile-time error will be generated if the ##**Constructor**## keyword is used in a Sub definition having one or more parameters. In a set of overloaded procedures, only one (1) constructor may be defined because of the ambiguity of having multiple Subs which take no arguments. In a single module, constructors normally execute in the order in which they are defined. The ##//priority//## attribute, an integer between 101 and 65535, can be used to force constructors to be executed in a certain order. The value of ##//priority//## has no specific meaning, only the relationship of the number with other constructor priorities. 101 is the highest priority and is executed first. All constructors having a ##//priority//## attribute are executed before constructors with no attribute. The priority value of 65535 is the same as not assigning a priority value. A module may define multiple constructor procedures, and multiple modules may define additional constructors provided no two ##[[KeyPgPublic Public]]## constructors share the same //procedure_name//. When linking with modules that also define constructors, the order of execution is not guaranteed at link-time unless the ##//priority//## attribute is used. Therefore, special care should be taken when using constructors that may call on a secondary module also defining a constructor. In such a case it is advisable to use a single constructor that explicitly calls initialization procedures in those modules. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/procs/mod-ctor.bas"}}%%(freebasic) '' ConDesExample.bas : An example program that defines two sets of '' constructors and destructors. Demonstrates when and in what order '' they are called when linking a single module. sub Constructor1() constructor print "Constructor1() called" end sub sub Destructor1() destructor print "Destructor1() called" end sub sub Constructor2() constructor print "Constructor2() called" end sub sub Destructor2() destructor print "Destructor2() called" end sub '' ---------------------- print "module-level code" end 0 '' ---------------------- %% **Output:** %% Constructor1() called Constructor2() called module-level code Destructor1() called Destructor2() called %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - [[KeyPgModuleDestructor Destructor (Module)]] - [[KeyPgSub Sub]] {{fbdoc item="back" value="CatPgProcedures|Procedures"}}{{fbdoc item="title" value="DESTRUCTOR (Module)"}}---- Specifies execution of a procedure at program termination {{fbdoc item="syntax"}}## [[[KeyPgPublic Public]] | [[KeyPgPrivate Private]]] [[KeyPgSub Sub]] //identifier// [[[KeyPgAlias Alias]] "//external_identifier//"] [()] **Destructor** [//priority//] [[[KeyPgStatic Static]]] { //procedure body// } [[KeyPgEnd End]] [[KeyPgSub Sub]] ## {{fbdoc item="desc"}} Defines a procedure to be automatically called from a compiled program's end-code. End-code is generated by the compiler and is executed when the program terminates normally. Procedures defined as destructors may be used the same way as ordinary procedures, that is, they may be called from within module-level code, as well as other procedures. The procedure must have an empty parameter list. A compile-time error will be generated if the ##**Destructor**## keyword is used in a Sub definition having one or more parameters. In a set of overloaded procedures, only one (1) destructor may be defined because of the ambiguity of having multiple Subs which take no arguments. In a single module, destructors normally execute in the order in which they are defined. The ##//priority//## attribute, an integer between 101 and 65535, can be used to force destructors to be executed in a certain order. The value of ##//priority//## has no specific meaning, only the relationship of the number with other destructor priorities. 101 is the lowest priority and is executed last. All destructors having a ##//priority//## attribute are executed after destructors with no attribute. The priority value of 65535 is the same as not assigning a priority value. A module may define multiple destructor procedures. Destructor procedures may also appear in more than one module. All procedures defined with the syntax shown above will be added to the list of procedures to be called during the program's termination. The order in which destructors defined in multiple modules are executed is known only at link time. Therefore, special care should be taken when using destructors that may call on a secondary module also defining a destructors. In such a case it is advisable to use a single destructor that explicit calls termination procedures in multiple modules to ensure a graceful termination of the application. Destructors will be called if the program terminates normally or if error-checking is enabled and the program terminates abnormally. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/procs/mod-dtor.bas"}}%%(freebasic) sub pauseonexit destructor '' If the program reaches the end, or aborts with an error, '' it will run this destructor before closing print "Press any key to end the program..." sleep end sub dim array(0 to 10, 0 to 10) as integer dim as integer i = 0, j = 11 '' this next line will cause the program to abort with an '' error if you compile with array bounds checking enabled (fbc -exx ...) print array(i, j) %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgModuleConstructor Constructor (Module)]]## - ##[[KeyPgSub Sub]]## {{fbdoc item="back" value="CatPgProcedures|Procedures"}}{{fbdoc item="title" value="MONTH"}}---- Gets the month of the year from a [[ProPgDates Date Serial]] {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Month** ( [[KeyPgByval byval]] //date_serial// [[KeyPgAs as]] [[KeyPgDouble double]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## #include "vbcompat.bi" //result// = **Month**( //date_serial// ) ## {{fbdoc item="param"}} ##//date_serial//## the date {{fbdoc item="ret"}} Returns the month number from a variable containing a date in [[ProPgDates Date Serial]] format. The month values are in the range 1-12 being 1 for January and 12 for December. {{fbdoc item="desc"}} The compiler will not recognize this function unless ##vbcompat.bi## is included. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/dates/month.bas"}}%%(freebasic) #include "vbcompat.bi" Dim a As Double = DateSerial(2005,11,28) + TimeSerial(7,30,50) Print Format(a, "yyyy/mm/dd hh:mm:ss "); Month(a) %% {{fbdoc item="diff"}} - Did not exist in QB. This function appeared in PDS and VBDOS {{fbdoc item="see"}} - [[ProPgDates Date Serials]] {{fbdoc item="back" value="CatPgDate|Date and Time Functions"}}{{fbdoc item="title" value="MONTHNAME"}}---- Gets the name of a month from it's integral representation {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""MonthName""** ( [[KeyPgByval byval]] //month// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByval byval]] //abbreviate// [[KeyPgAs as]] [[KeyPgInteger integer]] = 0 ) [[KeyPgAs as]] [[KeyPgString string]] ## {{fbdoc item="usage"}}## #include "vbcompat.bi" //result// = **""MonthName""**( //month_number// [, //abreviate// ] ) ## {{fbdoc item="param"}} ##//month//## the number of the month of the year - 1:January through 12:December ##//abbreviate//## flag to indicate that name should be abbreviated {{fbdoc item="ret"}} Returns the local operating system language month name from ##//month//## value 1 to 12. {{fbdoc item="desc"}} If ##//abbreviate//## is true, the month name abbreviation is returned. If omitted or false, the whole name is returned. The compiler will not recognize this function unless ##vbcompat.bi## or ##datetime.bi## is included. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/dates/monthname.bas"}}%%(freebasic) #include "vbcompat.bi" Dim ds As Double = DateSerial(2005, 11, 28) + TimeSerial(7, 30, 50) Print Format(ds, "yyyy/mm/dd hh:mm:ss "); MonthName(Month(ds)) %% {{fbdoc item="diff"}} - Did not exist in QB. This function appeared in Visual Basic. {{fbdoc item="see"}} - [[ProPgDates Date Serials]] {{fbdoc item="back" value="CatPgDate|Date and Time Functions"}}{{fbdoc item="title" value="MULTIKEY"}}---- Detects the status of keys by keyboard scancode. {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Multikey** ( [[KeyPgByval byval]] //scancode// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **Multikey**(//scancode//) ## {{fbdoc item="param"}} ##//scancode//## The [[GfxScancodes scan code]] of the key to check. {{fbdoc item="ret"}} Returns ##-1## if the key for the specified [[GfxScancodes scan code]] is pressed, otherwise returns ##0##. {{fbdoc item="desc"}} ##**Multikey**## is a function which will detect the status of any key, determined by scancode, at any time. It will return ##-1## if the key is pressed, otherwise it will return 0. The keyboard input buffer is not disabled while you use ##**Multikey**##; that is, pressed keys will be stored and subsequently returned by your next call to ##[[KeyPgInkey Inkey]]##. This means you have to empty ##[[KeyPgInkey Inkey]]## when you finish using ##**Multikey**##: {{fbdoc item="filename" value="examples/manual/check/KeyPgMultikey_1.bas"}}%%(freebasic) While Inkey <> "": Wend %% Keeping ##[[KeyPgInkey Inkey]]## to work while you use ##**Multikey**## allows more flexibility and can be useful to detect ##[[KeyPgChr Chr]](255)+"k"## combo returned on window close button click, if a windowed graphics mode has been set via the ##[[KeyPgScreengraphics Screen]]## statement. For a list of accepted scancodes, see [[GfxScancodes DOS keyboard scancodes]]; these are guaranteed to be valid for all FreeBASIC supported platforms. ##**Multikey**## should always work in graphics mode, as long as the screen is [[KeyPgScreenUnlock unlocked]]. Support in the console depends on the platform the program is run on though, and cannot be guaranteed. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/input/multikey.bas"}}%%(freebasic) #include "fbgfx.bi" DIM work_page AS INTEGER, x AS INTEGER, y AS INTEGER ' Request 640x480 with 2 pages SCREEN 18, ,2 COLOR 2, 15 work_page = 0 x = 320 y = 240 DO ' Let's work on a page while we display the other one SCREENSET work_page, work_page XOR 1 ' Check arrow keys and update position accordingly IF MULTIKEY(FB.SC_LEFT) AND x > 0 THEN x = x - 1 IF MULTIKEY(FB.SC_RIGHT) AND x < 639 THEN x = x + 1 IF MULTIKEY(FB.SC_UP) AND y > 0 THEN y = y - 1 IF MULTIKEY(FB.SC_DOWN) AND y < 479 THEN y = y + 1 CLS CIRCLE(x, y), 30, , , , ,F ' Page flip work_page = work_page XOR 1 LOOP WHILE NOT MULTIKEY(FB.SC_ESCAPE) ' Clear input buffer WHILE INKEY = "": WEND ' Restore both work and visible pages to page 0 SCREENSET PRINT "Press CTRL and H to exit..." DO SLEEP 25 IF MULTIKEY(FB.SC_CONTROL) AND MULTIKEY(FB.SC_H) THEN EXIT DO LOOP %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Multikey""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - [[GfxScancodes Keyboard scancodes]] - ##[[KeyPgGetmouse Getmouse]]## - ##[[KeyPgGetjoystick Getjoystick]]## - ##[[KeyPgScreengraphics Screen (Graphics)]]## - ##[[KeyPgInkey Inkey]]## {{fbdoc item="back" value="CatPgGfxInput|User Input Functions"}}{{fbdoc item="title" value="MUTEXCREATE"}}---- Creates a mutex used for synchronizing the execution of threads {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Mutexcreate** ( ) [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] ## {{fbdoc item="usage"}}## //result// = **Mutexcreate** ## {{fbdoc item="ret"}} The ##[[KeyPgAny any]] [[KeyPgPtr ptr]]## handle of the mutex created, or the null pointer (0) on failure. {{fbdoc item="desc"}} Mutexes, short for "Mutually Exclusive", are a way of synchronizing shared data within threads. If there is a global variable used by multiple threads (or a local variable used by a single thread, called multiple times), it should be "locked" during its use with a mutex. This halts all threads using ##[[KeyPgMutexLock Mutexlock]]## with that mutex, until it is unlocked with ##[[KeyPgMutexUnlock Mutexunlock]]##. ##Mutexcreate## creates a mutex, returning a handle which is to be referred to when locking, unlocking, or destroying the mutex. Mutexes created with ##Mutexcreate## should be destroyed when no longer needed or before the end of the program with ##[[KeyPgMutexDestroy Mutexdestroy]]##. A mutex is a lock that guarantees three things: 1. Atomicity - Locking a mutex is an atomic operation, meaning that the operating system (or threads library) assures you that if you locked a mutex, no other thread succeeded in locking this mutex at the same time. 2. Singularity - If a thread managed to lock a mutex, it is assured that no other thread will be able to lock the thread until the original thread releases the lock. 3. Non-Busy Wait - If a thread attempts to lock a thread that was locked by a second thread, the first thread will be suspended (and will not consume any CPU resources) until the lock is freed by the second thread. At this time, the first thread will wake up and continue execution, having the mutex locked by it. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/threads/mutexcreate.bas"}}%%(freebasic) '' Threading syncronyzation using Mutexes '' If you comment out the lines containing "MutexLock" and "MutexUnlock", '' the threads will not be in sync and some of the data may be printed '' out of place. const MAX_THREADS = 10 DECLARE SUB thread( byval id_ptr as any ptr ) DECLARE SUB teletype (BYVAL text AS STRING, BYVAL x AS INTEGER, BYVAL y AS INTEGER) DIM SHARED threadsync AS any ptr dim i as integer DIM handleTb(0 to MAX_THREADS-1) AS any ptr '' Create a mutex to syncronize the threads threadsync = MUTEXCREATE '' Create threads for i = 0 to MAX_THREADS-1 handleTb(i) = THREADCREATE(@thread, @i) IF handleTb(i) = 0 THEN PRINT "Error creating thread:"; i exit for END IF next '' Wait until all threads are finished for i = 0 to MAX_THREADS-1 if( handleTb(i) <> 0 ) then THREADWAIT( handleTb(i) ) end if next teletype "Testing.................", 1, 1 teletype "Testing again...........", 10, 1 '' Discard the mutex when we are through using teletype MUTEXDESTROY threadsync SUB thread( byval id_ptr as any ptr ) dim id as integer id = *cast( integer ptr, id_ptr ) teletype "Thread (" & id & ").........", 1, 1+id END SUB '' Teletype unfurls some text across the screen at a given location SUB teletype (BYVAL text AS STRING, BYVAL x AS INTEGER, BYVAL y AS INTEGER) DIM i AS INTEGER FOR i = 0 TO LEN(text)-1 '' MutexLock prevents the two simultaneously running '' threads from sharing "x", "y", and "a" MUTEXLOCK threadsync LOCATE y, x+i PRINT CHR(text[i]) '' MutexUnlock releases these variables for other use MUTEXUNLOCK threadsync SLEEP 25 NEXT END SUB %% {{fbdoc item="lang"}} - Threading is not allowed in the //[[CompilerOptlang -lang qb]]// dialect. {{fbdoc item="target"}} - The DOS version of FreeBASIC does not allow for threads, as the OS does not support them. - In Linux the threads are always started in the order they are created, this can't be assumed in Win32. It's an OS, not a FreeBASIC issue. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgMutexDestroy Mutexdestroy]]## - ##[[KeyPgMutexLock Mutexlock]]## - ##[[KeyPgMutexUnlock Mutexunlock]]## - ##[[KeyPgThreadCreate Threadcreate]]## - ##[[KeyPgThreadWait Threadwait]]## {{fbdoc item="back" value="CatPgThreading|Threading Support Functions"}}{{fbdoc item="title" value="MUTEXDESTROY"}}---- Destroys a mutex {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Mutexdestroy** ( [[KeyPgByval byval]] //id// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] ) ## {{fbdoc item="usage"}}## **Mutexdestroy**( //id// ) ## {{fbdoc item="param"}} ##//id//## The ##[[KeyPgAny any]] [[KeyPgPtr ptr]]## handle of the mutex to be destroyed. {{fbdoc item="desc"}} ##Mutexdestroy## discards a mutex created by ##[[KeyPgMutexCreate Mutexcreate]]##. This call should be executed after any threads using the mutex are no longer in use. See ##[[KeyPgMutexCreate Mutexcreate]]## for more general information on mutexes. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/threads/mutexdestroy.bas"}}%%(freebasic) '' Threading synchronization using Mutexes '' If you comment out the lines containing "MutexLock" and "MutexUnlock", '' the threads will not be in sync and some of the data may be printed '' out of place. DECLARE SUB thread1( param as any ptr ) DECLARE SUB thread2( param as any ptr ) DECLARE SUB teletype (BYVAL text AS STRING, BYVAL x AS INTEGER, BYVAL y AS INTEGER) DIM SHARED threadsync AS any ptr DIM SHARED thread1handle AS any ptr DIM SHARED thread2handle AS any ptr '' Create a mutex to syncronize the threads threadsync = MUTEXCREATE '' Call thread 1 thread1handle = THREADCREATE(@thread1) IF thread1handle = 0 THEN PRINT "Error creating thread1" END IF '' Call thread 2 thread2handle = THREADCREATE(@thread2) IF thread2handle = 0 THEN PRINT "Error creating thread1" END IF '' Wait until both threads are finished THREADWAIT(thread1handle) THREADWAIT(thread2handle) teletype "Testing.................", 1, 1 teletype "Testing again...........", 10, 1 '' Discard the mutex when we are through using teletype MUTEXDESTROY threadsync SLEEP END '' Thread 1 calls a simple "teletype" routine SUB thread1( param as any ptr ) teletype "This is a test...", 4, 1 END SUB '' ...As does thread 2 SUB thread2( param as any ptr ) teletype "This is another test...", 7, 1 END SUB '' Teletype unfurls some text across the screen at a given location SUB teletype (BYVAL text AS STRING, BYVAL x AS INTEGER, BYVAL y AS INTEGER) DIM i AS INTEGER, a AS INTEGER DIM text_length AS INTEGER text_length = LEN(text) FOR a = 0 TO text_length '' MutexLock prevents the two simultaneously running '' threads from sharing "x", "y", and "a" MUTEXLOCK threadsync LOCATE x,(y+a) PRINT CHR(text[a]) '' MutexUnlock releases these variables for other use MUTEXUNLOCK threadsync SLEEP 25 NEXT a END SUB %% {{fbdoc item="lang"}} - Threading is not allowed in the //[[CompilerOptlang -lang qb]]// dialect. {{fbdoc item="target"}} - The DOS version of FreeBASIC does not allow for threads, as the OS does not support them. - In Linux the threads are always started in the order they are created, this can't be assumed in Win32. It's an OS, not a FreeBASIC issue. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgMutexCreate Mutexcreate]]## - ##[[KeyPgMutexLock Mutexlock]]## - ##[[KeyPgMutexUnlock Mutexunlock]]## - ##[[KeyPgThreadCreate Threadcreate]]## - ##[[KeyPgThreadWait Threadwait]]## {{fbdoc item="back" value="CatPgThreading|Threading Support Functions"}}{{fbdoc item="title" value="MUTEXLOCK"}}---- Acquires a mutex {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Mutexlock** ( [[KeyPgByval byval]] //id// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] ) ## {{fbdoc item="usage"}}## **Mutexlock**( //id// ) ## {{fbdoc item="param"}} ##//id//## The ##[[KeyPgAny any]] [[KeyPgPtr ptr]]## handle of the mutex to be locked. {{fbdoc item="desc"}} ##Mutexlock## halts any other threads using a mutex "handle", generated by ##[[KeyPgMutexCreate Mutexcreate]]##, until the handle is unlocked with ##[[KeyPgMutexUnlock Mutexunlock]]##. See ##[[KeyPgMutexCreate Mutexcreate]]## for more general information on mutexes. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/threads/mutexlock.bas"}}%%(freebasic) '' Threading synchronization using Mutexes '' If you comment out the lines containing "MutexLock" and "MutexUnlock", '' the threads will not be in sync and some of the data may be printed '' out of place. DECLARE SUB thread1( param as any ptr ) DECLARE SUB thread2( param as any ptr ) DECLARE SUB teletype (BYVAL text AS STRING, BYVAL x AS INTEGER, BYVAL y AS INTEGER) DIM SHARED threadsync AS any ptr DIM SHARED thread1handle AS any ptr DIM SHARED thread2handle AS any ptr '' Create a mutex to synchronize the threads threadsync = MUTEXCREATE '' Call thread 1 thread1handle = THREADCREATE(@thread1) IF thread1handle = 0 THEN PRINT "Error creating thread1" END IF '' Call thread 2 thread2handle = THREADCREATE(@thread2) IF thread2handle = 0 THEN PRINT "Error creating thread1" END IF '' Wait until both threads are finished THREADWAIT(thread1handle) THREADWAIT(thread2handle) teletype "Testing.................", 1, 1 teletype "Testing again...........", 10, 1 '' Discard the mutex when we are through using teletype MUTEXDESTROY threadsync SLEEP END '' Thread 1 calls a simple "teletype" routine SUB thread1( param as any ptr ) teletype "This is a test...", 4, 1 END SUB '' ...As does thread 2 SUB thread2( param as any ptr ) teletype "This is another test...", 7, 1 END SUB '' Teletype unfurls some text across the screen at a given location SUB teletype (BYVAL text AS STRING, BYVAL x AS INTEGER, BYVAL y AS INTEGER) DIM i AS INTEGER, a as INTEGER DIM text_length AS INTEGER text_length = LEN(text) FOR a = 0 TO text_length '' MutexLock prevents the two simultaneously running '' threads from sharing "x", "y", and "a" MUTEXLOCK threadsync LOCATE x,(y+a) PRINT CHR(text[a]) '' MutexUnlock releases these variables for other use MUTEXUNLOCK threadsync SLEEP 25 NEXT a END SUB %% {{fbdoc item="lang"}} - Threading is not allowed in the //[[CompilerOptlang -lang qb]]// dialect. {{fbdoc item="target"}} - The DOS version of FreeBASIC does not allow for threads, as the OS does not support them. - In Linux the threads are always started in the order they are created, this can't be assumed in Win32. It's an OS, not a FreeBASIC issue. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgMutexCreate Mutexcreate]]## - ##[[KeyPgMutexDestroy Mutexdestroy]]## - ##[[KeyPgMutexUnlock Mutexunlock]]## - ##[[KeyPgThreadCreate Threadcreate]]## - ##[[KeyPgThreadWait Threadwait]]## {{fbdoc item="back" value="CatPgThreading|Threading Support Functions"}}{{fbdoc item="title" value="MUTEXUNLOCK"}}---- Releases a mutex lock {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Mutexunlock** ( [[KeyPgByval byval]] //id// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] ) ## {{fbdoc item="usage"}}## **Mutexunlock**( //id// ) ## {{fbdoc item="param"}} ##//id//## The ##[[KeyPgAny any]] [[KeyPgPtr ptr]]## handle of the mutex to be unlocked. {{fbdoc item="desc"}} ##Mutexunlock## releases a mutex "handle" created by ##[[KeyPgMutexCreate Mutexcreate]]##, and locked with ##[[KeyPgMutexLock Mutexlock]]##. This allows other threads sharing the mutex to continue execution. See ##[[KeyPgMutexCreate Mutexcreate]]## for more general information on mutexes. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/threads/mutexunlock.bas"}}%%(freebasic) '' Threading synchronization using Mutexes '' If you comment out the lines containing "MutexLock" and "MutexUnlock", '' the threads will not be in sync and some of the data may be printed '' out of place. DECLARE SUB thread1( param as any ptr ) DECLARE SUB thread2( param as any ptr ) DECLARE SUB teletype (BYVAL text AS STRING, BYVAL x AS INTEGER, BYVAL y AS INTEGER) DIM SHARED threadsync AS any ptr DIM SHARED thread1handle AS any ptr DIM SHARED thread2handle AS any ptr '' Create a mutex to synchronize the threads threadsync = MUTEXCREATE '' Call thread 1 thread1handle = THREADCREATE(@thread1) IF thread1handle = 0 THEN PRINT "Error creating thread1" END IF '' Call thread 2 thread2handle = THREADCREATE(@thread2) IF thread2handle = 0 THEN PRINT "Error creating thread1" END IF '' Wait until both threads are finished THREADWAIT(thread1handle) THREADWAIT(thread2handle) teletype "Testing.................", 1, 1 teletype "Testing again...........", 10, 1 '' Discard the mutex when we are through using teletype MUTEXDESTROY threadsync SLEEP END '' Thread 1 calls a simple "teletype" routine SUB thread1( param as any ptr ) teletype "This is a test...", 4, 1 END SUB '' ...As does thread 2 SUB thread2( param as any ptr ) teletype "This is another test...", 7, 1 END SUB '' Teletype unfurls some text across the screen at a given location SUB teletype (BYVAL text AS STRING, BYVAL x AS INTEGER, BYVAL y AS INTEGER) DIM i AS INTEGER, a as INTEGER DIM text_length AS INTEGER text_length = LEN(text) FOR a = 0 TO text_length '' MutexLock prevents the two simultaneously running '' threads from sharing "x", "y", and "a" MUTEXLOCK threadsync LOCATE x,(y+a) PRINT CHR(text[a]) '' MutexUnlock releases these variables for other use MUTEXUNLOCK threadsync SLEEP 25 NEXT a END SUB %% {{fbdoc item="lang"}} - Threading is not allowed in the //[[CompilerOptlang -lang qb]]// dialect. {{fbdoc item="target"}} - The DOS version of FreeBASIC does not allow for threads, as the OS does not support them. - In Linux the threads are always started in the order they are created, this can't be assumed in Win32. It's an OS, not a FreeBASIC issue. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgMutexCreate Mutexcreate]]## - ##[[KeyPgMutexDestroy Mutexdestroy]]## - ##[[KeyPgMutexLock Mutexlock]]## - ##[[KeyPgThreadCreate Threadcreate]]## - ##[[KeyPgThreadWait Threadwait]]## {{fbdoc item="back" value="CatPgThreading|Threading Support Functions"}}{{fbdoc item="title" value="NAME"}}---- Renames a file on disk {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Name**( [[KeyPgByref Byref]] //oldname// [[KeyPgAs as]] [[KeyPgString string]], [[KeyPgByref Byref]] //newname// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **Name**( //oldname//, //newname// ) ## {{fbdoc item="param"}} ##//oldname//## Name of an existing file. ##//newname//## New name of the file. {{fbdoc item="ret"}} Returns zero (0) on success and non-zero on failure. {{fbdoc item="desc"}} Renames a file originally called ##//oldname//## to ##//newname//##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/system/name.bas"}}%%(freebasic) Dim OldName As String Dim NewName As String Dim result As Integer OldName = "dsc001.jpg" NewName = "landscape.jpg" result = Name( OldName, NewName ) If 0 <> result Then Print "error renaming " & oldname & " to " & newname & "." End If %% {{fbdoc item="diff"}} - In QB, NAME required AS rather than a comma between the old and new names. {{fbdoc item="see"}} - ##[[KeyPgKill Kill]]## {{fbdoc item="back" value="CatPgOpsys|Operating System Functions"}}{{fbdoc item="title" value="NAMESPACE"}}---- Declares a namespace block {{fbdoc item="syntax"}}## **Namespace** //identifier// //statements// **End Namespace** ## {{fbdoc item="desc"}} Namespaces are commonly used in libraries where you don't want all the symbols from that library to crowd the user's space (called the Global Namespace). For example, if you used the "Forms" library, it might define the Point type for describing an X and Y coordinate, and you might also define it for another purpose. This can be resolved by creating the namespace Forms for the library, and then referring to its Point type as Forms.Point, and yours as just Point. To access duplicated symbols defined in the global namespace use: ##.""SomeSymbol""## (or ##..""SomeSymbol""## if inside a [[KeyPgWith With..End With]] block). {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/module/namespace.bas"}}%%(freebasic) Namespace Forms Type Point '' A 2D point As Integer x As Integer y End Type '' Since we are inside of the namespace, Point resolves to Forms.Point. Sub AdjustPoint( ByRef pt As Point, ByVal newx As Integer, ByVal newy As Integer ) pt.x = newx pt.y = newy End Sub End Namespace Type Point '' A 3D point As Integer x As Integer y As Integer z End Type Sub AdjustPoint( ByRef pt As Point, ByVal newx As Integer, ByVal newy As Integer, ByVal newz As Integer ) pt.x = newx pt.y = newy pt.z = newz End Sub Dim pt1 As Point AdjustPoint( pt1, 1, 1, 1 ) Dim pt2 As Forms.Point Forms.AdjustPoint( pt2, 1, 1 ) %% {{fbdoc item="lang"}} - Namespaces are not supported in the //[[CompilerOptlang -lang qb]]// dialect. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - [[KeyPgUsing Using (Namespaces)]] {{fbdoc item="back" value="CatPgModularizing|Modularizing"}}{{fbdoc item="title" value="NEXT"}}---- Control flow statement to mark the end of a ##[[KeyPgFornext For...Next]]## loop. {{fbdoc item="syntax"}}## **Next** [ //identifier_list// ] ## {{fbdoc item="desc"}} Indicates the end of a statement block associated with a matching ##[[KeyPgFornext For]]## statement. When ##**Next**## is used on its own without an //identifier_list//, it closes the most recent ##[[KeyPgFornext For]]## statement block. ##//identifier_list//## is optional and may be one or more variable names separated by commas. This form of the ##**Next**## statement is retained for compatibility with QB. ##//identifier_list//##, if given, must match the identifiers used in the associated ##[[KeyPgFornext For]]## statements in reverse order. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/control/next.bas"}}%%(freebasic) dim i as integer, j as integer for i=1 to 10 for j=1 to 2 ' ... next next %% {{fbdoc item="filename" value="examples/manual/control/next2.bas"}}%%(freebasic) dim i as integer, j as integer for i=1 to 10 for j=1 to 2 ' ... next j next i %% {{fbdoc item="filename" value="examples/manual/control/next3.bas"}}%%(freebasic) dim i as integer, j as integer for i=1 to 10 for j=1 to 2 ' ... next j,i %% {{fbdoc item="diff"}} - ##[[KeyPgByref Byref]]## arguments cannot be used as counters. {{fbdoc item="see"}} - ##[[KeyPgFornext For...Next]]## {{fbdoc item="back" value="CatPgMisc|Miscellaneous"}}{{fbdoc item="title" value="NOW"}}---- Gets the current system time as a [[ProPgDates Date Serial]] {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Now** ( ) [[KeyPgAs as]] [[KeyPgDouble double]] ## {{fbdoc item="usage"}}## #include "vbcompat.bi" //result// = **Now** ## {{fbdoc item="ret"}} Returns a date serial containing the system's date and time at execution time. {{fbdoc item="desc"}} As the time is the decimal part of a date serial, if the value of **Now** is saved to an integer, the time in it will be reset to 00:00:00 The compiler will not recognize this function unless ##vbcompat.bi## is included. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/dates/now.bas"}}%%(freebasic) #include "vbcompat.bi" dim a as double = now() print format(a, "yyyy/mm/dd hh:mm:ss") %% {{fbdoc item="diff"}} - Did not exist in QB. This function appeared in PDS and VBDOS {{fbdoc item="see"}} - [[ProPgDates Date Serials]] {{fbdoc item="back" value="CatPgDate|Date and Time Functions"}}{{fbdoc item="title" value="OCT"}}---- Converts a number to octal representation {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""Oct""**( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgByte byte]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""Oct""**( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgByte byte]], [[KeyPgByval byval]] //digits// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""Oct""**( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgShort short]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""Oct""**( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgShort short]], [[KeyPgByval byval]] //digits// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""Oct""**( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""Oct""**( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByval byval]] //digits// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""Oct""**( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgLongint longint]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""Oct""**( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgLongint longint]], [[KeyPgByval byval]] //digits// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgString string]] ## {{fbdoc item="usage"}}## //result// = **Oct**[$]( //number// [, //digits// ] ) ## {{fbdoc item="param"}} ##//number//## A number or expression evaluating to a number. A floating-point number will be converted to a ##[[KeyPgLongint longint]]##. ##//digits//## Desired number of digits in the returned string. {{fbdoc item="ret"}} A string containing the unsigned octal representation of ##//number//##. {{fbdoc item="desc"}} Returns the unsigned octal string representation of ##//number//##. Octal digits range from 0 to 7. If you specify ##//digits//## > 0, the result string will be exactly that length. It will be truncated or padded with zeros on the left, if necessary. The length of the returned string will not be longer than the maximum number of digits required for the type of ##//number//## (3 characters for ##[[KeyPgByte Byte]]##, 6 for ##[[KeyPgShort Short]]##, 11 for ##[[KeyPgInteger Integer]]##, and 22 for ##[[KeyPgLongint Longint]]##) If you want to do the opposite, i.e. convert an octal string back into a number, the easiest way to do it is to prepend the string with ##"&O"##, and convert it using ##[[KeyPgValint Valint]]## or ##[[KeyPgVallng Vallng]]##, similarly to a normal numeric string. E.g. ##[[KeyPgValint Valint]]("&O77")## {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/oct.bas"}}%%(freebasic) Print Oct(54321) Print Oct(54321, 4) Print Oct(54321, 8) %% will produce the output: %%152061 2061 00152061 %% {{fbdoc item="lang"}} - The string type suffix ##"$"## is obligatory in the //[[CompilerOptlang -lang qb]]// dialect. - The string type suffix ##"$"## is optional in the //[[CompilerOptlang -lang fblite]]// and //[[CompilerOptlang -lang fb]]// dialects. {{fbdoc item="diff"}} - In QBASIC, there was no way to specify the number of digits returned. - The size of the string returned was limited to 32 bits, or 11 octal digits. {{fbdoc item="see"}} - ##[[KeyPgBin Bin]]## - ##[[KeyPgHex Hex]]## - ##[[KeyPgValint Valint]]## - ##[[KeyPgVallng Vallng]]## {{fbdoc item="back" value="CatPgString|String Functions"}}{{fbdoc item="title" value="OFFSETOF"}}---- Returns the offset of a field within a type. {{fbdoc item="syntax"}}## [[KeyPgPpdefine #define]] **Offsetof**(//typename//, //fieldname//) [[KeyPgCint cint]]( @[[KeyPgCast cast]]( //typename// [[KeyPgPtr ptr]], 0 )->//fieldname// ) ## {{fbdoc item="usage"}}## //result// = **Offsetof**( //typename//, //fieldname// ) ## {{fbdoc item="param"}} ##//typename//## Name of the type as defined using the ##[[KeyPgType Type...End Type]]## statements. ##//fieldname//## Name of the field as defined within the type. {{fbdoc item="desc"}} ##**Offsetof**## will return the location ##//fieldname//## as offset in bytes from the beginning of ##//typename//##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/misc/offsetof.bas"}}%%(freebasic) Type MyType x As Single y As Single Union b As Byte i As Integer End Union End Type Print "OffsetOf x = "; OffsetOf(MyType, x) Print "OffsetOf y = "; OffsetOf(MyType, y) Print "OffsetOf b = "; OffsetOf(MyType, b) Print "OffsetOf i = "; OffsetOf(MyType, i) %% **Output** %%OffsetOf x = 0 OffsetOf y = 4 OffsetOf b = 8 OffsetOf i = 8 %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Offsetof""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgType Type...End Type]]## - ##[[KeyPgSizeof Sizeof]]## {{fbdoc item="back" value="CatPgMisc|Miscellaneous"}}{{fbdoc item="title" value="ON ERROR"}}---- Error handling statement to set the current error handler {{fbdoc item="syntax"}}## **On [Local] Error Goto** //label// ## {{fbdoc item="usage"}}## **On [Local] Error Goto** //label// ## {{fbdoc item="param"}} ##//label//## label to jump to when error occurs {{fbdoc item="desc"}} ##[[KeyPgOnerror On Error]]## triggers a jump to an error handler when an error occurs. If ##[[KeyPgLocal Local]]## is not used the handler must be in the main part of the module. Using ##[[KeyPgLocal Local]]## allows to have the error handler inside the ##[[KeyPgSub Sub]]##/##[[KeyPgFunction Function]]## where the ##**On Error**## is located. ##**On Error GOTO 0**## deactivates the current error handler. The use of QB-like error handling requires compilation with switch //[[CompilerOpte -e]]//, //[[CompilerOptex -ex]]// or //[[CompilerOptexx -exx]]// activated. See [[TblRuntimeErrors Runtime Error Codes]] for a listing of runtime error numbers and their associated meaning. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/error/onerror.bas"}}%%(freebasic) '' Compile with QB (-lang qb) dialect on error goto errorhandler error 24 '' simulate an error print "this message will not be seen" errorhandler: print "Error #"; err; "!" end %% {{fbdoc item="lang"}} - ON ERROR is supported in the //[[CompilerOptlang -lang qb]]// dialect only. In the //[[CompilerOptlang -lang fb]]// dialect, statements can be used in function form to return an error code {{fbdoc item="filename" value="examples/manual/check/KeyPgOnerror_2.bas"}}%%(freebasic) '' Compile with FB default (-lang fb) dialect If Open( "text" For Input As #1 ) <> 0 Then Print "Unable to open file" End If %% {{fbdoc item="diff"}} - QB has no LOCAL clause and requires the label to be in the main part of the module. {{fbdoc item="see"}} - ##[[KeyPgError Error]]## - ##[[KeyPgLocal Local]]## - ##[[KeyPgErr Err]]## - [[TblRuntimeErrors Runtime Error Codes]] {{fbdoc item="back" value="CatPgError|Error Handling Functions"}}{{fbdoc item="title" value="ON...GOSUB"}}---- Calls a label based on an expression {{fbdoc item="syntax"}}## **On** //expression// **Gosub** //label1//[, ...] ## {{fbdoc item="desc"}} Branches to different labels depending on the value of //expression//. An expression value of 1 will branch to the first label, a value of 2 to the second, etc. If the value of //expression// is zero (0) or greater than the number of items in the list, execution continues on the next statement following the ##**On...Gosub**##. This statement behaves exactly like ##[[KeyPgGosub Gosub]]## and execution may return to the statement following the ##**On...Gosub**## using ##[[KeyPgReturn Return]]##. It is recommended that the structured ##[[KeyPgSelectcase Select Case]]## conditional statement be used instead of ##**On...Gosub**##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/control/ongosub.bas"}}%%(freebasic) '' Compile with -lang qb choice = 3 on choice gosub labela, labelb, labelc print "Good bye." end labela: print "choice a" return labelb: print "choice b" return labelc: print "choice c" return %% {{fbdoc item="lang"}} - Only available in the //[[CompilerOptlang -lang qb]]// and //[[CompilerOptlang -lang fblite]]// dialects. - ##**On Gosub**## support is disabled by default in the //[[CompilerOptlang -lang fblite]]// unless the ##[[KeyPgOptiongosub Option Gosub]]## statement is used. {{fbdoc item="diff"}} - FreeBASIC does not generate a run-time error if ##//expression//## is negative or greater than 255. {{fbdoc item="see"}} - ##[[KeyPgSelectcase Select Case]]## - ##[[KeyPgOngoto On...Goto]]## - ##[[KeyPgGosub Gosub]]## - ##[[KeyPgReturn Return]]## - ##[[KeyPgOptiongosub Option Gosub]]## {{fbdoc item="back" value="CatPgControlFlow|Control Flow"}}{{fbdoc item="title" value="ON...GOTO"}}---- Jumps to a label based on an expression. {{fbdoc item="syntax"}}## **On** //expression// **Goto** label1[, ...] ## {{fbdoc item="desc"}} Branches to different labels depending on the value of //expression//. An expression value of 1 will branch to the first label, a value of 2 to the second, etc. If the value of //expression// is zero (0) or greater than the number of items in the list, execution continues on the next statement following the ##**On...Goto**##. It is recommended that the structured ##[[KeyPgSelectcase Select Case]]## conditional statement be used instead of ##**On...Goto**##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/control/on-goto.bas"}}%%(freebasic) Dim choice as integer Input "Enter a number: ", choice On choice Goto labela, labelb, labelc labela: Print "choice a" End labelb: Print "choice b" End labelc: Print "choice c" End %% {{fbdoc item="diff"}} - FreeBASIC does not generate a run-time error if ##//expression//## is negative or greater than 255. {{fbdoc item="see"}} - ##[[KeyPgSelectcase Select Case]]## - ##[[KeyPgOngosub On...Gosub]]## - ##[[KeyPgGoto Goto]]## {{fbdoc item="back" value="CatPgControlFlow|Control Flow"}}{{fbdoc item="title" value="Operator + (Addition)"}}---- Sums two expressions {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **+** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgByte byte]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgByte byte]] ) [[KeyPgAs as]] [[KeyPgByte byte]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **+** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUbyte ubyte]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUbyte ubyte]] ) [[KeyPgAs as]] [[KeyPgUbyte ubyte]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **+** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgShort short]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgShort short]] ) [[KeyPgAs as]] [[KeyPgShort short]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **+** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUshort ushort]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUshort ushort]] ) [[KeyPgAs as]] [[KeyPgUshort ushort]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **+** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **+** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUinteger uinteger]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUinteger uinteger]] ) [[KeyPgAs as]] [[KeyPgUinteger uinteger]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **+** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgLongint longint]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgLongint longint]] ) [[KeyPgAs as]] [[KeyPgLongint longint]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **+** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUlongint ulongint]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUlongint ulongint]] ) [[KeyPgAs as]] [[KeyPgUlongint ulongint]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **+** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgSingle single]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgSingle single]] ) [[KeyPgAs as]] [[KeyPgSingle single]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **+** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgDouble double]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgDouble double]] ) [[KeyPgAs as]] [[KeyPgDouble double]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **+** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] //T//, [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] //T// [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **+** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] //T// ) [[KeyPgAs as]] //T// ## {{fbdoc item="usage"}}## //result// = //lhs// **##+##** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The left-hand side expression to sum. ##//rhs//## The right-hand side expression to sum. ##//T//## Any pointer type. {{fbdoc item="ret"}} Returns the sum of two expressions. {{fbdoc item="desc"}} When the left and right-hand side expressions are numeric values, **##Operator +## (Add)** returns the sum of the two values. When the left and right-hand side expressions are string values, **##Operator +## (Add)** concatenates the two strings and returns the result. If either the left or right-hand side expressions is of [[KeyPgPointer Pointer]] type, **##Operator +## (Add)** performs pointer arithmetic on the address, returning the result. Neither operand is modified in any way. This operator can be overloaded to accept user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/add.bas"}}%%(freebasic) DIM n AS SINGLE n = 4.54 + 5.46 PRINT n SLEEP %% will produce the output: %% 10 %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - [[KeyPgOpConcat Operator + (String concatenation)]] - [[CatPgMath Mathematical Functions]] {{fbdoc item="back" value="CatPgOpArithmetic|Arithmetic Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator AND (Conjunction)"}}---- Returns the bitwise-and (conjunction) of two numeric values {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **And** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] //T1//, [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] //T2// ) [[KeyPgAs as]] //Ret// ## {{fbdoc item="usage"}}## //result// = //lhs// **And** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The left-hand side expression. ##//T1//## Any numeric type. ##//rhs//## The right-hand side expression. ##//T2//## Any numeric type. ##//Ret//## A numeric type (varies with ##//T1//## and ##//T2//##). {{fbdoc item="ret"}} Returns the bitwise-and (conjunction) of the two operands. {{fbdoc item="desc"}} This operator returns the bitwise-and of its operands, a logical operation that results in a value with bits set depending on the bits of the operands. The truth table below demonstrates all combinations of a boolean-and operation: {{table columns="3" cellpadding="2" cells="Lhs Bit;Rhs Bit;Result;0;0;0;1;0;0;0;1;0;1;1;1"}} No short-circuiting is performed - both expressions are always evaluated. The return type depends on the types of values passed. ##[[KeyPgByte Byte]]##, ##[[KeyPgUbyte Ubyte]]## and floating-point type values are first converted to ##[[KeyPgInteger Integer]]##. If the left and right-hand side types differ only in signedness, then the return type is the same as the left-hand side type (##//T1//##), otherwise, the larger of the two types is returned. This operator can be overloaded for user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/and-bitwise.bas"}}%%(freebasic) ' Using the AND operator on two numeric values DIM AS UBYTE numeric_value1, numeric_value2 numeric_value1 = 15 '00001111 numeric_value2 = 30 '00011110 'Result = 14 = 00001110 PRINT numeric_value1 AND numeric_value2 SLEEP %% {{fbdoc item="filename" value="examples/manual/operator/and-logical.bas"}}%%(freebasic) ' Using the AND operator on two conditional expressions Dim As UByte numeric_value1, numeric_value2 numeric_value1 = 15 numeric_value2 = 25 IF numeric_value1 > 10 AND numeric_value1 < 20 Then Print "Numeric_Value1 is between 10 and 20" IF numeric_value2 > 10 AND numeric_value2 < 20 Then Print "Numeric_Value2 is between 10 and 20" SLEEP ' This will output "Numeric_Value1 is between 10 and 20" because ' both conditions of the IF statement is true ' It will not output the result of the second IF statement because the first ' condition is true and the second is false. %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - [[TblTruth Operator Truth Tables]] {{fbdoc item="back" value="CatPgOpLogical|Logical Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator () (Array index)"}}---- Returns a reference to an element in an array {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **()** ( //lhs//() [[KeyPgAs as]] //T//, [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgInteger integer]], ... ) [[KeyPgAs as]] //T// ## ~&//Note that **##Operator ()## (Array index)** returns a reference. As of 02.27.07, ""FreeBASIC"" syntax does not support returning references. When it does, this syntax will need to be changed.// {{fbdoc item="usage"}}## //result// = //lhs// **(** //rhs// [, ...] **)** ## {{fbdoc item="param"}} ##//lhs//## An array. ##//rhs//## An index of an element in the array. ##//T//## Any data type. {{fbdoc item="desc"}} This operator returns a reference to an element in an array. For multidimensional arrays, multiple indexes must be specified (up to the total number of dimensions of the array). For any one dimension //d// in array //a//, any index outside of the range (##[[KeyPgLbound Lbound]](//a//(), //d//), [[KeyPgUbound Ubound]](//a//(), //d//)##) will result in a runtime error. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/arrayindex.bas"}}%%(freebasic) dim array(4) as integer = { 0, 1, 2, 3, 4 } for index as integer = 0 to 4 print array(index) next %% will produce the output: %% 0 1 2 3 4 %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} {{fbdoc item="back" value="CatPgOpIndexing|Indexing Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator = (Assign)"}}---- Assigns a value to a variable {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Let** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] //T1//, [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] //T2// ) ## {{fbdoc item="usage"}}## //lhs// **=** //rhs// ##//or, in the //QB// dialect,//## [ [[KeyPgLet Let]] ] //lhs// **=** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The variable to assign to. ##//T1//## Any numeric, string or pointer type. ##//rhs//## The value to assign to ##//lhs//##. ##//T2//## Any type convertible to ##//T2//##. {{fbdoc item="desc"}} This operator assigns the value of its right-hand side operand (##//rhs//##) to its left-hand side operand (##//lhs//##). The right-hand side operand must be implicitly convertible to the left-hand side type (##//T1//##). For example, you cannot assign a numeric value to a string type; to do that, first convert the numeric value to a string using ##[[KeyPgStr Str]]## or ##[[KeyPgWstr Wstr]]##. Avoid confusion with ##[[KeyPgOpEqual Operator = (Equal)]]##, which also uses the '=' symbol. This operator can be overloaded for user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/assign.bas"}}%%(freebasic) dim i as integer i = 420 ' <- this is the assignment operator if i = 69 then '<-this is the equivalence operator print "ERROR: i should equal 420" end -1 end if print "All is good." end 0 %% {{fbdoc item="filename" value="examples/manual/operator/assign-let.bas"}}%%(freebasic) ' compile with -lang fblite or qb dim i as integer LET i = 300 ' <-alternate syntax %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. - In the //[[CompilerOptlang -lang qb]]// dialect, an assignment expression can be preceded by the ##[[KeyPgLet Let]]## keyword. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgOpEqual Operator = (Equal)]]## - ##[[KeyPgOpLet Operator Let (Assignment)]]## {{fbdoc item="back" value="CatPgOpAssignment|Assignment Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator @ (Address of)"}}---- Returns the address of a string literal, variable, object or procedure {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **@** ( [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] //T// ) [[KeyPgAs as]] //T// [[KeyPgPointer pointer]] ## {{fbdoc item="usage"}}## //result// = **@** //rhs// ## {{fbdoc item="param"}} ##//rhs//## The string literal, variable, object or procedure to retrieve the address of. ##//T//## Any [[CatPgStdDataTypes standard]], [[CatPgUserDefTypes user-defined]] or procedure type. {{fbdoc item="ret"}} Returns the address of the right-hand side (##//rhs//##) operand. {{fbdoc item="desc"}} **##Operator @## (Address of)** returns the memory address of it's operand. When the operand is of type ##[[KeyPgString String]]##, the address of the internal string descriptor is returned. Use ##[[KeyPgOpStrptr Operator Strptr]]## (String pointer) to retrieve the address of the string data. The operand cannot be an array, but may be an array element. For example, ##"@myarray(0)"## returns the address of ##"myarray(0)"##. This operator can be overloaded for user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/address-var.bas"}}%%(freebasic) 'This program demonstrates the use of the @ operator. Dim a As Integer Dim b As Integer Dim addr As Integer Ptr a = 5 'Here we place the values 5 and 10 into a and b, respectively. b = 10 'Here, we print the value of the variables, then where in memory they are stored. Print "The value in A is ";a;" but the pointer to a is ";@a Print "The value in B is ";b;" but the pointer to b is ";@b 'Now, we will take the integer ptr above, and use @ to place a value into it. 'Note that the * will check the value in the ptr, just as @ checked the ptr 'for a normal variable. addr = @a Print "The pointer addr is now pointing at the memory address to a, value: ";*addr addr = @b Print "The pointer addr is now pointing at the memory address to b, value: ";*addr %% {{fbdoc item="filename" value="examples/manual/operator/address-func.bas"}}%%(freebasic) 'This program demonstrates how the @ symbol can be used 'to create pointers to subroutines. Declare Sub mySubroutine () Dim say_Hello As Sub() say_Hello = @mySubroutine 'We tell say_Hello to point to mySubroutine. 'The sub() datatype acts as a pointer here. say_Hello() 'Now we can run say_Hello just like mySubroutine. Sub mySubroutine Print "hi" End Sub %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgOpValueOf Operator * (Value of)]]## - [[ProPgPointers Pointers]] {{fbdoc item="back" value="CatPgOpPoint|Pointer Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator += (Add and Assign)"}}---- Adds and assigns a value to a variable {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **+=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] //T1//, [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] //T2// ) [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **+=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] //T// [[KeyPgPointer ptr]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **+=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgString string]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **+=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgWstring wstring]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgWstring wstring]] ) ## {{fbdoc item="usage"}}## //lhs// **+=** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The variable to assign to. ##//T1//## Any numeric type. ##//rhs//## The value to add to ##//lhs//##. ##//T2//## Any numeric type. ##//T//## Any data type. {{fbdoc item="desc"}} This operator adds and assigns a value to a variable. It is functionally equivalent to: ## //lhs// = //lhs// [[KeyPgOpAdd +]] //rhs// ## For numeric types, the right-hand side expression (##//rhs//##) will be converted to the left-hand side type (##//T1//##). For string types, this operator is functionally equivalent to ##[[KeyPgOpCombineConcat Operator &= (Concatenate and assign)]]##. This operator can be overloaded for user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/add-assign.bas"}}%%(freebasic) DIM n AS DOUBLE n = 6 n += 1 PRINT n SLEEP %% Output: %% 7 %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgOpAdd Operator + (Add)]]## - [[CatPgMath Mathematical Functions]] {{fbdoc item="back" value="CatPgOpAssignment|Assignment Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator AND= (Conjunction and Assign)"}}---- Performs a bitwise-and (conjunction) and assigns the result to a variable {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **And=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] //T1//, [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] //T2// ) ## {{fbdoc item="usage"}}## //lhs// **And=** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The variable to assign to. ##//T1//## Any numeric type. ##//rhs//## The value to perform a bitwise-and (conjunction) with ##//lhs//##. ##//T2//## Any numeric type. {{fbdoc item="desc"}} This operator performs a bitwise-and and assigns the result to a variable. It is functionally equivalent to: ## //lhs// = //lhs// [[KeyPgOpAnd and]] //rhs// ## ##**And=**## compares each bit of its operands, ##//lhs//## and ##//rhs//##, and if both bits are 1, then the corresponding bit in the first operand, ##//lhs//##, is set to 1, otherwise it is set to 0. ##**And=**## cannot be used in conditional expressions. This operator can be overloaded for user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/and-assign.bas"}}%%(freebasic) ' Using the AND= operator on two numeric values DIM AS UBYTE numeric_value1, numeric_value2 numeric_value1 = 15 '' 00001111 numeric_value2 = 30 '' 00011110 numeric_value1 AND= numeric_value2 '' Result = 14 = 00001110 PRINT numeric_value1 SLEEP %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgOpAnd And]]## {{fbdoc item="back" value="CatPgOpAssignment|Assignment Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator &= (Concatenate and Assign)"}}---- Appends and assigns a string onto another string {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **&=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgString string]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] //T2// ) [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **&=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgWstring wstring]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] //T2// ) ## {{fbdoc item="usage"}}## //lhs// &= //rhs// ## {{fbdoc item="param"}} ##//lhs//## The string to assign to. ##//rhs//## The value to append to ##//lhs//##. ##//T2//## Any numeric, string or user-defined type that can be converted to a string. {{fbdoc item="desc"}} This operator appends one string onto another. The right-hand side expression (##//rhs//##) is converted to a string before concatenation. It is functionally equivalent to, ## //lhs// = //lhs// [[KeyPgOpAdd &]] //rhs// ## where the result is assigned back to the left-hand side string. This operator can be overloaded for user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/concat-assign.bas"}}%%(freebasic) dim s as string = "Hello, " s &= " world!" print s %% will produce the output: %% Hello, world! %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgOpConcatConvert Operator & (String concatenation with conversion)]]## - ##[[KeyPgOpCombineAdd Operator += (Add and Assign)]]## {{fbdoc item="back" value="CatPgOpAssignment|Assignment Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator /= (Divide and Assign)"}}---- Divides and assigns a value to a variable {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **/=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] //T1//, [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] //T2// ) ## {{fbdoc item="usage"}}## //lhs// **/=** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The variable to assign to. ##//T1//## Any numeric type. ##//rhs//## The value to divide ##//lhs//## by. ##//T2//## Any numeric type. {{fbdoc item="desc"}} This operator divides and assigns a value to a variable. It is functionally equivalent to: ## //lhs// = //lhs// [[KeyPgOpDivide /]] //rhs// ## The right-hand side expression (##//rhs//##) will be converted to the left-hand side type (##//T1//##). This operator can be overloaded for user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/divide-assign.bas"}}%%(freebasic) DIM n AS DOUBLE n = 6 n /= 2.2 PRINT n SLEEP %% Output: %% 2.727272727272727 %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgOpDivide Operator / (Divide)]]## - [[CatPgMath Mathematical Functions]] {{fbdoc item="back" value="CatPgOpAssignment|Assignment Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator EQV= (Equivalence and Assign)"}}---- Performs a bitwise-eqv (equivalence) and assigns the result to a variable {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **And=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] //T1//, [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] //T2// ) ## {{fbdoc item="usage"}}## //lhs// **Eqv=** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The variable to assign to. ##//T1//## Any numeric type. ##//rhs//## The value to perform a bitwise-eqv (equivalence) with ##//lhs//##. ##//T2//## Any numeric type. {{fbdoc item="desc"}} This operator performs a bitwise-eqv and assigns the result to a variable. It is functionally equivalent to: ## //lhs// = //lhs// [[KeyPgOpEqv eqv]] //rhs// ## ##**Eqv=**## compares each bit of its operands, ##//lhs//## and ##//rhs//##, and if both bits are the same (either both 0 or both 1), then the corresponding bit in the first operand, ##//lhs//##, is set to 1, otherwise it is set to 0. This operator can be overloaded for user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/eqv-assign.bas"}}%%(freebasic) dim as ubyte a = &b00110011 dim as ubyte b = &b01010101 a eqv= b '' Result a = &b10011001 print bin(a) %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgOpEqv Eqv]]## {{fbdoc item="back" value="CatPgOpAssignment|Assignment Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator ^= (Exponentiate and Assign)"}}---- Exponentiates and assigns a value to a variable {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **^=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgDouble double]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgDouble double]] ) ## {{fbdoc item="usage"}}## //lhs// **^=** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The variable to assign to. ##//rhs//## The value to exponentiate ##//lhs//## by. {{fbdoc item="desc"}} This operator exponentiates and assigns a value to a variable. It is functionally equivalent to: ## //lhs// = //lhs// [[KeyPgOpExponentiate ^]] //rhs// ## This operator can be overloaded for user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/exponent-assign.bas"}}%%(freebasic) DIM n AS DOUBLE n = 6 n ^= 2 PRINT n SLEEP %% Output: %% 36 %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgOpExponentiate Operator ^ (Exponentiate)]]## - [[CatPgMath Mathematical Functions]] {{fbdoc item="back" value="CatPgOpAssignment|Assignment Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator IMP= (Implication and Assign)"}}---- Performs a bitwise-imp (implication) and assigns the result to a variable {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Imp=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] //T1//, [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] //T2// ) ## {{fbdoc item="usage"}}## //lhs// **Imp=** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The variable to assign to. ##//T1//## Any numeric type. ##//rhs//## The value to perform a bitwise-imp (implication) with ##//lhs//##. ##//T2//## Any numeric type. {{fbdoc item="desc"}} This operator performs a bitwise-imp and assigns the result to a variable. It is functionally equivalent to: ## //lhs// = //lhs// [[KeyPgOpImp imp]] //rhs// ## ##**Imp**## is a bitwise operator which is the same as (##[[KeyPgOpNot Not]]## ##//lhs//##) ##[[KeyPgOpOr Or]]## ##//rhs//##. ##**Imp=**## compares each bit of its operands, ##//lhs//## and ##//rhs//##, and if the bit in ##//lhs//## is 0 or the bit in ##//rhs//## is 1, then the corresponding bit in the first operand, ##//lhs//##, is set to 1, otherwise it is set to 0. This operator can be overloaded for user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/imp-assign.bas"}}%%(freebasic) dim as ubyte a = &b00110011 dim as ubyte b = &b01010101 a Imp= b '' Result a = &b11011101 print bin(a) %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgOpImp Imp]]## - [[CatPgOpAssignment Assignment Operators]] {{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator \= (Integer divide and Assign)"}}---- Integer divides and assigns a value to a variable {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **\=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] //T1//, [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] //T2// ) ## {{fbdoc item="usage"}}## //lhs// **\=** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The variable to assign to. ##//T1//## Any numeric type. ##//rhs//## The value to divide ##//lhs//## by. ##//T2//## Any numeric type. {{fbdoc item="desc"}} This operator multiplies and assigns a value to a variable. It is functionally equivalent to: ## //lhs// = //lhs// [[KeyPgOpIntegerDivide \]] //rhs// ## This operator can be overloaded for user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/integer-divide-assign.bas"}}%%(freebasic) DIM n AS DOUBLE n = 6 n \= 2.2 PRINT n SLEEP %% Output: %% 3 %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgOpIntegerDivide Operator \ (Integer divide)]]## - [[CatPgMath Mathematical Functions]] {{fbdoc item="back" value="CatPgOpAssignment|Assignment Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:55:17 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: c6d0e86c6b9934e551c1c2a80b596fd9 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 1408 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="Operator Mod= (Modulus and Assign)"}}---- Divides a value and assigns the remainder to a variable {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Mod=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgInteger integer]] ) ## {{fbdoc item="usage"}}## //lhs// **Mod=** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The variable to assign to. ##//rhs//## The value to divide ##//lhs//## by. {{fbdoc item="desc"}} This operator divides two values of ##[[KeyPgInteger Integer]]## type and assigns the remainder to its left-hand side (##//lhs//##) variable. It is functionally equivalent to: ## //lhs// = //lhs// [[KeyPgOpModulus Mod]] //rhs// ## This operator can be overloaded for user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/mod-assign.bas"}}%%(freebasic) DIM n AS INTEGER n = 11 n mod= 3 '' The result is 2 PRINT n SLEEP %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgOpModulus Operator + (Modulus)]]## - [[CatPgMath Mathematical Functions]] {{fbdoc item="back" value="CatPgOpAssignment|Assignment Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}} {{fbdoc item="title" value="Operator *= (Multiply and Assign)"}}---- Multiplies and assigns a value to a variable {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] ***=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] //T1//, [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] //T2// ) ## {{fbdoc item="usage"}}## //lhs// ***=** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The variable to assign to. ##//T1//## Any numeric type. ##//rhs//## The value to multiply ##//lhs//## by. ##//T2//## Any numeric type. {{fbdoc item="desc"}} This operator multiplies and assigns a value to a variable. It is functionally equivalent to: ## //lhs// = //lhs// [[KeyPgOpMultiply *]] //rhs// ## The right-hand side expression (##//rhs//##) will be converted to the left-hand side type (##//T1//##). This operator can be overloaded for user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/multiply-assign.bas"}}%%(freebasic) DIM n AS DOUBLE n = 6 n *= 2 PRINT n SLEEP %% Output: %% 12 %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgOpMultiply Operator * (Multiply)]]## - [[CatPgMath Mathematical Functions]] {{fbdoc item="back" value="CatPgOpAssignment|Assignment Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:55:26 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 4e40a9cc7dcc76f0dc2d89dcb75c015d Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 1620 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="Operator OR= (Inclusive Disjunction and Assign)"}}---- Performs a bitwise-or (inclusive disjunction) and assigns the result to a variable {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Or=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] //T1//, [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] //T2// ) ## {{fbdoc item="usage"}}## //lhs// **Or=** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The variable to assign to. ##//T1//## Any numeric type. ##//rhs//## The value to perform a bitwise-or (inclusive disjunction) with ##//lhs//##. ##//T2//## Any numeric type. {{fbdoc item="desc"}} This operator performs a bitwise-or and assigns the result to a variable. It is functionally equivalent to: ## //lhs// = //lhs// [[KeyPgOpOr or]] //rhs// ## ##**Or=**## compares each bit of its operands, ##//lhs//## and ##//rhs//##, and if either bits are 1, then the corresponding bit in the first operand, ##//lhs//##, is set to 1, otherwise it is set to 0. This operator can be overloaded for user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/or-assign.bas"}}%%(freebasic) dim as ubyte a = &b00110011 dim as ubyte b = &b01010101 a or= b '' Result a = &b01110111 print bin(a) %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgOpOr Or]]## {{fbdoc item="back" value="CatPgOpAssignment|Assignment Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}} {{fbdoc item="title" value="Operator Shl= (Shift left and Assign)"}}---- Shifts left and assigns a value to a variable {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Shl=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Shl=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUinteger uinteger]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUinteger uinteger]] ) [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Shl=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgLongint longint]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgLongint longint]] ) [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Shl=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUlongint ulongint]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUlongint ulongint]] ) ## {{fbdoc item="usage"}}## //lhs// **shl=** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The variable to assign to. ##//rhs//## The value to shift ##//lhs//## left by. {{fbdoc item="desc"}} This operator shifts the bits in its left-hand side (##//lhs//##) parameter a number of times specified by its right-hand side (##//rhs//##) parameter, and assigns the result to ##//lhs//##. It is functionally equivalent to: ## //lhs// = //lhs// [[KeyPgOpShiftLeft Shl]] //rhs// ## This operator can be overloaded for user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/shl-assign.bas"}}%%(freebasic) DIM i AS INTEGER i = &b00000011 '' = 3 i shl= 3 '' = i*2^3 '' Result: 11000 24 24 print bin(i), i, 3*2^3 SLEEP %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Shl=""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgOpShiftLeft Operator Shl (Shift left)]]## - ##[[KeyPgOpCombineShiftRight Operator Shr= (Shift right and Assign)]]## - [[CatPgMath Mathematical Functions]] {{fbdoc item="back" value="CatPgOpAssignment|Assignment Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator Shr= (Shift right and Assign)"}}---- Shifts right and assigns a value to a variable {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Shr=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Shr=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUinteger uinteger]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUinteger uinteger]] ) [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Shr=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgLongint longint]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgLongint longint]] ) [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Shr=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUlongint ulongint]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUlongint ulongint]] ) ## {{fbdoc item="usage"}}## //lhs// **shr=** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The variable to assign to. ##//rhs//## The value to shift ##//lhs//## right by. {{fbdoc item="desc"}} This operator shifts the bits in its left-hand side (##//lhs//##) parameter a number of times specified by its right-hand side (##//rhs//##) parameter, and assigns the result to ##//lhs//##. It is functionally equivalent to: ## //lhs// = //lhs// [[KeyPgOpShiftRight Shr]] //rhs// ## This operator can be overloaded for user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/shr-assign.bas"}}%%(freebasic) DIM i AS INTEGER i = &b00011000 '' = 24 i shr= 3 '' = i\2^3 '' Result: 11 3 3 print bin(i), i, 24\2^3 SLEEP %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Shr=""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgOpShiftRight Operator Shr (Shift right)]]## - ##[[KeyPgOpCombineShiftLeft Operator Shl= (Shift Left and Assign)]]## - [[CatPgMath Mathematical Functions]] {{fbdoc item="back" value="CatPgOpAssignment|Assignment Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator -= (Subtract and Assign)"}}---- Subtracts and assigns a value to a variable {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **-=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] //T1//, [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] //T2// ) [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **-=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] //T// [[KeyPgPointer ptr]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgInteger integer]] ) ## {{fbdoc item="usage"}}## //lhs// **-=** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The variable to assign to. ##//T1//## Any numeric type. ##//rhs//## The value to subtract from ##//lhs//##. ##//T2//## Any numeric type. ##//T//## Any data type. {{fbdoc item="desc"}} This operator subtracts and assigns a value to a variable. It is functionally equivalent to: ## //lhs// = //lhs// [[KeyPgOpSubtract -]] //rhs// ## For numeric types, the right-hand side expression (##//rhs//##) will be converted to the left-hand side type (##//T1//##). This operator can be overloaded for user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/subtract-assign.bas"}}%%(freebasic) DIM n AS DOUBLE n = 6 n -= 2.2 PRINT n SLEEP %% Output: %% 3.8 %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgOpSubtract Operator - (Subtract)]]## - [[CatPgMath Mathematical Functions]] {{fbdoc item="back" value="CatPgOpAssignment|Assignment Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator XOR= (Exclusive Disjunction and Assign)"}}---- Performs a bitwise-xor (exclusive disjunction) and assigns the result to a variable {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Xor=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] //T1//, [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] //T2// ) ## {{fbdoc item="usage"}}## //lhs// **Xor=** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The variable to assign to. ##//T1//## Any numeric type. ##//rhs//## The value to perform a bitwise-xor (exclusive or) with ##//lhs//##. ##//T2//## Any numeric type. {{fbdoc item="desc"}} This operator performs a bitwise-or and assigns the result to a variable. It is functionally equivalent to: ## //lhs// = //lhs// [[KeyPgOpXor xor]] //rhs// ## ##**Xor=**## compares each bit of its operands, ##//lhs//## and ##//rhs//##, and if both bits are the same (both 1 or both 0), then the corresponding bit in the first operand, ##//lhs//##, is set to 0, otherwise it is set to 1. This operator can be overloaded for user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/xor-assign.bas"}}%%(freebasic) dim as ubyte a = &b00110011 dim as ubyte b = &b01010101 a xor= b '' Result a = &b01100110 print bin(a) %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgOpXor Xor]]## {{fbdoc item="back" value="CatPgOpAssignment|Assignment Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator + (String concatenation)"}}---- Concatenates two strings {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **+** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgString string]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **+** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgZstring zstring]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgZstring zstring]] ) [[KeyPgAs as]] [[KeyPgZstring zstring]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **+** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgWstring wstring]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgWstring wstring]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] ## {{fbdoc item="usage"}}## //result// = //lhs// **+** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The left-hand side string to concatenate. ##//rhs//## The right-hand side string to concatenate. {{fbdoc item="desc"}} This operator concatenates two strings. Unlike [[KeyPgOpConcatConvert Operator & (String concatenation with conversion)]] both expressions //must// be strings, and may not be converted (in fact, any attempt to concatenate a string with a non-string or two non-strings will result in a type mismatch error, with the exception of when operator overloading is used in a UDT). {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/concat_nocvt.bas"}}%%(freebasic) Dim As String a = "Hello, ", b = "World!" Dim As String c c = a + b Print c %% Output: %% Hello, World! %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - [[KeyPgOpAdd Operator + (Add)]] - [[KeyPgOpConcatConvert Operator & (String concatenation with conversion)]] - ##[[KeyPgStr Str]]## {{fbdoc item="back" value="CatPgOpString|String Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator & (String concatenation with conversion)"}}---- Concatenates two strings, converting non-strings to strings as needed {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **&** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] //T//, [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] //U// ) [[KeyPgAs as]] //V// ## {{fbdoc item="usage"}}## //result// = //lhs// **&** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The left-hand side expression to concatenate. ##//T//## Any standard data type or user-defined type that can be converted to a standard data type. ##//rhs//## The right-hand side expression to concatenate. ##//U//## Any standard data type or user-defined type that can be converted to a standard data type. ##//V//## The resultant string type (varies with operands). {{fbdoc item="desc"}} This operator concatenates two expressions. If either of the expressions is not a string type, it is converted to ##[[KeyPgString String]]## with ##[[KeyPgStr Str]]##. If either of the expressions is a ##[[KeyPgWstring Wstring]]##, a ##[[KeyPgWstring Wstring]]## is returned, otherwise a ##[[KeyPgString String]]## is returned. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/concat.bas"}}%%(freebasic) DIM AS STRING A,C DIM AS SINGLE B A="The result is: " B=124.3 C=A & B PRINT C SLEEP %% Output: %% The result is: 124.3 %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - [[KeyPgOpConcat Operator + (String concatenation)]] - ##[[KeyPgStr Str]]## {{fbdoc item="back" value="CatPgOpString|String Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator Delete"}}---- Operator to delete data allocated with the ##[[KeyPgOpNew New]]## operator {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **delete** ( //buf// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] ) [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **delete[]** ( //buf// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] ) ## {{fbdoc item="usage"}}## **Delete** //expression// //or// **Delete[]** //expression// ## {{fbdoc item="param"}} ##//buf//## An address of memory to free. ##//expression//## An address of memory to free. {{fbdoc item="desc"}} ##**Delete**## is used to destroy and free the memory of an object created with [[KeyPgOpNew New]]. When deleting a TYPE, its destructor will be called. ##**Delete**## should only be used with addresses returned from ##[[KeyPgOpNew New]]##. The array version of ##**Delete**##, ##**Delete[]**##, is used to destroy an array of objects previously created with [[KeyPgOpNew New]][]. Destructors will be called here as well. ##**Delete**## must be used with addresses returned from [[KeyPgOpNew New]], and ##**Delete[]**## with [[KeyPgOpNew New]][]. You cannot mix and match the different versions of the operators. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/delete.bas"}}%%(freebasic) type Rational as integer numerator, denominator end type scope ' Create and initialize a Rational, and store it's address. dim p as Rational ptr = new Rational(3, 4) print p->numerator & "/" & p->denominator ' Destroy the rational and give its memory back to the system. delete p end scope scope ' Allocate memory for 100 integers, store the address of the first one. dim p as integer ptr = new integer[100] ' Assign some values to the integers in the array. for i as integer = 0 to 99 p[i] = i next ' Free the entire integer array. delete[] p end scope %% {{fbdoc item="lang"}} - Only available in the //[[CompilerOptlang -lang fb]]// dialect. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgOpNew New]]## {{fbdoc item="back" value="CatPgOpMemory|Memory Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator / (Divide)"}}---- Divides two numeric expressions {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **/** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgByte byte]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgByte byte]] ) [[KeyPgAs as]] [[KeyPgByte byte]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **/** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUbyte ubyte]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUbyte ubyte]] ) [[KeyPgAs as]] [[KeyPgUbyte ubyte]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **/** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgShort short]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgShort short]] ) [[KeyPgAs as]] [[KeyPgShort short]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **/** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUshort ushort]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUshort ushort]] ) [[KeyPgAs as]] [[KeyPgUshort ushort]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **/** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **/** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUinteger uinteger]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUinteger uinteger]] ) [[KeyPgAs as]] [[KeyPgUinteger uinteger]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **/** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgLongint longint]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgLongint longint]] ) [[KeyPgAs as]] [[KeyPgLongint longint]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **/** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUlongint ulongint]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUlongint ulongint]] ) [[KeyPgAs as]] [[KeyPgUlongint ulongint]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **/** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgSingle single]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgSingle single]] ) [[KeyPgAs as]] [[KeyPgSingle single]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **/** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgDouble double]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgDouble double]] ) [[KeyPgAs as]] [[KeyPgDouble double]] ## {{fbdoc item="usage"}}## //result// = //lhs// **##/##** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The left-hand side dividend expression. ##//rhs//## The right-hand side divisor expression. {{fbdoc item="ret"}} Returns the quotient of a dividend and divisor. {{fbdoc item="desc"}} **##Operator /## (Divide)** returns the quotient of a dividend and divisor. Neither operand is modified in any way. This operator can be overloaded to accept user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/divide.bas"}}%%(freebasic) DIM n AS DOUBLE PRINT n / 5 n = 6 / 2.3 PRINT n SLEEP %% Output: %% 0 2.608695652173913 %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - [[CatPgMath Mathematical Functions]] {{fbdoc item="back" value="CatPgOpArithmetic|Arithmetic Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="OPEN"}}---- Opens a disk file for reading or writing using file operations {{fbdoc item="syntax"}}## **Open** //filename// **For** **[[KeyPgInputfilemode Input]]** [//encoding_type//] [//lock_type//] **As** [**#**]//filenumber// **Open** //filename// **For** **[[KeyPgOutput Output]]** [//encoding_type//] [//lock_type//] **As** [**#**]//filenumber// **Open** //filename// **For** **[[KeyPgAppend Append]]** [//encoding_type//] [//lock_type//] **As** [**#**]//filenumber// **Open** //filename// **For** **[[KeyPgBinary Binary]]** [//access_type//] [//lock_type//] **As** [**#**]//filenumber// **Open** //filename// **For** **[[KeyPgRandom Random]]** [//access_type//] [//lock_type//] **As** [**#**]//filenumber// [**Len =** //record_length//] ## {{fbdoc item="usage"}}## //result// = **Open**( //filename//, **For** {**[[KeyPgInputfilemode Input]]**|**[[KeyPgOutput Output]]**|**[[KeyPgAppend Append]]**}, **As** //filenumber// ) ##//or,//## //result// = **Open**( //filename//, **For** **[[KeyPgBinary Binary]]**, **[[KeyPgAccess Access]]** {**Read**|**Write**}, **As** //filenumber// ) ##//or,//## //result// = **Open**( //filename//, **For** **[[KeyPgRandom Random]]**, **[[KeyPgAccess Access]]** {**Read**|**Write**}, **As** //filenumber// [, **Len = ** //record_length//] ) ##//(or in the QB-like syntax,)//## **Open** //filename// **For** {**[[KeyPgInputfilemode Input]]**|**[[KeyPgOutput Output]]**|**[[KeyPgAppend Append]]**} **As** //filenumber// ##//(or,)//## **Open** //filename// **For** **[[KeyPgBinary Binary]]** **[[KeyPgAccess Access]]** {**Read**|**Write**} **As** //filenumber// ##//(or,)//## **Open** //filename// **For** **[[KeyPgRandom Random]]** **[[KeyPgAccess Access]]** {**Read**|**Write**} **As** //filenumber// [**Len = ** //record_length//] ## {{fbdoc item="param"}} ##//filename//## A string value of the name of the disk file to open. Relative file paths are relative to the current directory (see ##[[KeyPgCurdir Curdir]]##). ##//encoding_type//## The encoding to be used when reading or writing text, can be one of: - ##Encoding "ascii"## //(ASCII encoding is used, default)// - ##Encoding "utf8"## //(8-bit Unicode encoding is used)// - ##Encoding "utf16"## //(16-bit Unicode encoding is used)// - ##Encoding "utf32"## //(32-bit Unicode encoding is used)// ##//access_type//## The type of access requested by the calling process. - ##Access## [##Read##] [##Write##] //(both read and write access can be used, which is the default)// ##//lock_type//## Imposes restrictions on disk file access from other processes (threads or programs), can be either: - ##Shared## //(the file can be freely accessed by other processes)// - ##Lock## [##Read##] [##Write##] //(both read and write access can be denied to other processes)// ##//filenum//## An available file number to bind to the disk file, which can be found with ##[[KeyPgFreefile Freefile]]##. ##//record_length//## The size, in bytes, of each record read from or written to the disk file. The default is 128. {{fbdoc item="ret"}} In the first usage, ##**Open**## returns zero (0) on success and a non-zero error code otherwise. {{fbdoc item="desc"}} Opens a disk file for reading and/or writing. A //file number// is bound to the file on disk, which is used in subsequent file operations, such as ##[[KeyPgInputPp Input #]]## and ##[[KeyPgLock Lock]]##. An available //file number// can be retrieved with ##[[KeyPgFreefile Freefile]]##. The ##[[KeyPgInputfilemode Input]]##, ##[[KeyPgOutput Output]]## and ##[[KeyPgAppend Append]]## //file modes// open disk files for sequential text I/O, useful for reading or writing plain text files. When the ##[[KeyPgInputfilemode Input]]## mode is specified, only reading file operations can be used, like ##[[KeyPgLineinput Line Input #]]## and ##[[KeyPgGetfileio Get #]]##. If the disk file does not exist a runtime error will be thrown. The ##[[KeyPgOutput Output]]## mode specifies that only writing operations can be used, like ##[[KeyPgPrintPp Print #]]## and ##[[KeyPgPutfileio Put #]]##. If the disk file does not exist it is created empty. The ##[[KeyPgAppend Append]]## mode is like the ##[[KeyPgOutput Output]]## mode, except that writing operations will begin at the end of the disk file, if it exists. The ##[[KeyPgInputfilemode Input]]##, ##[[KeyPgOutput Output]]## and ##[[KeyPgAppend Append]]## //file modes// also allow selection of a character encoding to be used when reading from or writing text to the disk file. ASCII or a Unicode encoding may be specified (see the description of the ##//encoding_type//## parameter above). The ##[[KeyPgBinary Binary]]## and ##[[KeyPgRandom Random]]## //file modes// open disk files for random-access reading or writing of arbitrary sized binary data. The ##[[KeyPgBinary Binary]]## //file mode// allows reading and writing of simple data type values, like ##[[KeyPgByte Byte]]## or ##[[KeyPgLongint Longint]]##, using binary read or write operations, like ##[[KeyPgGetfileio Get #]]##. ##[[KeyPgLoc Loc]]## and ##[[KeyPgSeekreturn Seek]]## are among the procedures used for reading and writing to arbitrary locations in the disk file. The ##[[KeyPgRandom Random]]## //file mode// is similar to ##[[KeyPgBinary Binary]]##, except that file I/O operations always use a constant data size when reading or writing. By default, the ##[[KeyPgBinary Binary]]## and ##[[KeyPgRandom Random]]## //file modes// allow both reading and writing operations on the opened disk file, but this can be changed by specifying an //access type// (see the description for the ##//access_type//## parameter above). For any //file mode//, access to the opened disk file can be restricted or granted to other threads or programs by specifying a //lock type// (see the description for the ##//lock_type//## parameter above). If no //lock type// is specified, other threads of the current program can freely open the disk file (##Shared##), while other programs cannot (##Lock Read Write##). ##[[KeyPgLock Lock]]## and ##[[KeyPgUnlock Unlock]]## can be used to temporarily restrict access to parts of a file. The error code returned by ##**Open**## can be checked using ##[[KeyPgErr Err]]## in the next line. The function version of ##**Open**## returns directly the error code as an integer. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/fileio/open.bas"}}%%(freebasic) ' Create a string and fill it. Dim buffer As String, f as integer buffer = "Hello World within a file." ' Find the first free file number. f = Freefile ' Open the file "file.ext" for binary usage, using the file number "f". Open "file.ext" For Binary As #f If Err>0 then Print "Error opening the file":end ' Place our string inside the file, using number "f". Put #f, , buffer ' Close all open files. Close ' End the program. (Check the file "file.ext" upon running to see the output.) End %% {{fbdoc item="filename" value="examples/manual/fileio/opencom.bas"}}%%(freebasic) 'OPEN A COM PORT Open Com "COM1:9600,N,8,1" As #1 if Err>0 then print "The port could not be opended" 'COM1, 9600 BAUD, NO PARITY BIT, EIGHT DATA BITS, ONE STOP BIT %% {{fbdoc item="filename" value="examples/manual/fileio/openfunc.bas"}}%%(freebasic) 'function version of OPEN if OPEN("file.ext" FOR BINARY ACCESS READ AS #1)>0 then PRINT "Error opening file " END IF %% {{fbdoc item="target"}} - Linux requires the ##//filename//## case matches the real name of the file. Windows and DOS are case insensitive. - Path separators in Linux are forward slashes /. Windows uses backward slashes \ but it allows for forward slashes . DOS uses backward \ slashes. - On Windows, a file number used in a dynamic link library is not the same as an identical file number used in the main program. File numbers can not be passed or returned and then used between a DLL and an executable. {{fbdoc item="diff"}} - Using MS-DOS device names to open streams or hardware devices (##"LPT:"##, ##"SCR:"##, etc.) is supported only in the //[[CompilerOptlang -lang qb]]// dialect; for other modes FreeBASIC's new composite keywords must be used: see ##[[KeyPgOpenCom Open Com]]##, ##[[KeyPgOpenCons Open Cons]]##, ##[[KeyPgOpenErr Open Err]]##, ##[[KeyPgOpenPipe Open Pipe]]##, ##[[KeyPgOpenLpt Open Lpt]]##, ##[[KeyPgOpenScrn Open Scrn]]##. - ##**Open**## can be called as a procedure that returns an error code. {{fbdoc item="lang"}} - The //[[CompilerOptlang -lang qb]]// dialect supports the old GW-BASIC-style syntax ##OPEN mode_string, #filenum, filename [length]## with mode_string being "I" for input, "O" for output , "A" for append, "R" for random, "B" for binary. {{fbdoc item="see"}} - ##[[KeyPgErr Err with a list of error codes]]## - ##[[KeyPgClose Close]]## - ##[[KeyPgFreefile Freefile]]## - ##[[KeyPgOpenCons Open Cons]]##, ##[[KeyPgOpenErr Open Err]]##, ##[[KeyPgOpenPipe Open Pipe]]##, ##[[KeyPgOpenLpt Open Lpt]]##, ##[[KeyPgOpenCom Open Com]]##, ##[[KeyPgOpenScrn Open Scrn]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}}{{fbdoc item="title" value="OPEN COM"}}---- Opens a serial port for input and output {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Open Com** ( byref //options// [[KeyPgAs as]] [[KeyPgString string]], **AS** //filenum// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **Open Com**( //options//, **AS**[#] //filenum// ) ## {{fbdoc item="param"}} ##//options//## A [[KeyPgString string]] containing options used in controlling the port. ##//filenum//## The file number to bind to the port. {{fbdoc item="ret"}} Returns zero (0) on success and a non-zero error code otherwise. {{fbdoc item="desc"}} This command opens a serial port of the PC, allowing to send and receive data by using the normal file commands as PRINT #, INPUT#, GET #,... The main parameter is a [[KeyPgString string]] that describes, at the very least, which communications port to open. It has the format: ##"**COM**//n//**:** [ //baudrate// ][ , [ //parity// ][ , [ //data_bits// ][ , [ //stop_bits// ][ , [ //extended_options// ]]]]]"## where, ##//n//## Com port to open. "1", "2", "3", "4", etc. Some platforms will support more serial ports depending on how the operating system is configured. Where ##//n//## is not given, "COM:" will map to "COM1:", except on Linux where "COM:" maps to "/dev/modem" ##//baudrate//## "300" (default), "1200", ..., etc. ##//parity//## "N" (none), "E" (even, default), "O" (odd), "S" (space), "M" (mark), "PE" (QB-quirk: checked, even parity) ##//data_bits//## "5", "6", "7" (default) or "8". ##//stop_bits//## "1", "1.5" or "2". //(default value depends on baud rate and data bits, see table below)// {{table columns="2" cellpadding="2" cells="Condition;Default number of stop bits;baud rate <= 110 and data bits = 5;1.5;baud rate <= 110 and data bits >= 6;2;baud rate > 110;1"}} ##//extended_options//## Miscellaneous options. //(See table below)// {{table columns="2" cellpadding="2" cells="Option;Action;'CSn';Set the CTS duration (in ms) (n>=0), 0 = turn off, default = 1000;'DSn';Set the DSR duration (in ms) (n>=0), 0 = turn off, default = 1000;'CDn';Set the Carrier Detect duration (in ms) (n>=0), 0 = turn off;'OPn';Set the 'Open Timeout' (in ms) (n>=0), 0 = turn off;'TBn';Set the 'Transmit Buffer' size (n>=0), 0 = default, depends on platform;'RBn';Set the 'Receive Buffer' size (n>=0), 0 = default, depends on platform;'RS';Suppress RTS detection;'LF';Communicate in ASCII mode (add LF to every CR) - Win32 doesn't support this one;'ASC';same as 'LF';'BIN';The opposite of LF and it'll always work;'PE';Enable 'Parity' check;'DT';Keep DTR enabled after CLOSE;'FE';Discard invalid character on error;'ME';Ignore all errors;'IRn';IRQ number for COM (only supported (?) on DOS)"}} All items except for the COM port are optional. The order of ##//baudrate//##, ##//parity//##, ##//data_bits//##, ##//stop_bits//## is fixed. Any skipped fixed item ( ##//baudrate//##, etc...) must be empty. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/fileio/opencom1.bas"}}%%(freebasic) OPEN COM "COM1:9600,N,,2" as 1 %% Opens COM1 with 9600 baud, no parity, 7 data bits and 2 stop bits. {{fbdoc item="filename" value="examples/manual/fileio/opencom2.bas"}}%%(freebasic) OPEN COM "COM1:115200" as 1 %% Opens COM1 with 115200 baud, "even" parity, 7 data bits and 1 stop bits. {{fbdoc item="target"}} - On the Windows platform ##"COM:"## maps to ##"COM1:"## - On the Linux platform ##"COM:"## maps to ##"/dev/modem"## ##"COM1:"## maps to ##"/dev/ttyS0"## ##"COM2:"## maps to ##"/dev/ttyS1"##, etc ##"/dev/xyz:"## maps to ##"/dev/xyz"##, etc - The DOS serial driver is experimental and can access COM ports 1 to 4 It uses the following base io and IRQ's as default: COM1 - &h3f8 - IRQ4 COM2 - &h2f8 - IRQ3 COM3 - &h3e8 - IRQ4 COM4 - &h2e8 - IRQ3 Since fbc-0.18.4, an alternate IRQ can be specified using the the "IRn" protocol option where "n" is 3 through 7. Currently not supported: IRQ's on the slave PIC, alternate base I/O addresses, Timeouts and most errors as detected in QB, hardware flow control, FIFO's. ##"COM:"## maps to ##"COM1:"## {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect the old syntax ##OPEN "COMx:...## is supported. {{fbdoc item="diff"}} - In QB the syntax was ##OPEN "COMx:[baudrate] [,parity, [data_bits, [stop_bits, [extended_options]]]]" FOR INPUT|OUTPUT|RANDOM AS [#] n## - In QB, only ##"COM1:"## and ##"COM2:"## are supported. In FreeBASIC, any correctly configured serial port may be used. {{fbdoc item="see"}} - ##[[KeyPgOpen Open]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}}{{fbdoc item="title" value="OPEN CONS"}}---- Opens the console's standard input (//stdin//) or output (//stdout//) streams for use in file operations. {{fbdoc item="syntax"}}## **Open Cons** **As** [**#**]//filenumber// **Open Cons** **For** [[KeyPgInputfilemode Input]] **As** [**#**]//filenumber// **Open Cons** **For** [[KeyPgOutput Output]] **As** [**#**]//filenumber// ## {{fbdoc item="usage"}}## //result// = **Open Cons**( [**For** {**[[KeyPgInputfilemode Input]]**|**[[KeyPgOutput Output]]**},] **As** //filenumber// ) ##//(or using the QB-like syntax//,)## **Open Cons** [**For** {**[[KeyPgInputfilemode Input]]**|**[[KeyPgOutput Output]]**}] **As** //filenumber// ## {{fbdoc item="param"}} ##//filenumber//## An available //file number// to bind to the //stdin// or //stdout// stream, which can be found with ##[[KeyPgFreefile Freefile]]##. {{fbdoc item="ret"}} In the first usage, ##**Open Cons**## returns zero (0) on success and a non-zero error code otherwise. {{fbdoc item="desc"}} ##**Open Cons**## opens the console's //stdin// or //stdout// streams for reading or writing. A //file number// is bound to the stream, which is used in subsequent file operations, such as ##[[KeyPgInputPp Input #]]##. An available //file number// can be retrieved with ##[[KeyPgFreefile Freefile]]##. The ##[[KeyPgInputfilemode Input]]## //file mode// opens the //stdin// stream for reading file operations, such as ##[[KeyPgInputPp Line Input #]]##, while the ##[[KeyPgOutput Output]]## //file mode// opens the //stdout// stream for writing file operations, such as ##[[KeyPgPrintPp Print #]]##. The ##[[KeyPgOutput Output]]## //file mode// is the default if not specified. The //stdin// and //stdout// streams are the ones used when the calling process' input or output is redirected (piped) by OS commands, or when it is opened with ##[[KeyPgOpenPipe Open Pipe]]##. To open both the //stdin// and //stdout// streams for file operations, a process must use multiple //file numbers//. **Runtime errors:** ##**Open Cons**## throws one of the following [[ProPgErrorHandling runtime errors]]: //(##1##) Illegal function call// - Filenumber was not free at the time. use ##[[KeyPgFreefile Freefile]]## to ensure that filenumber is free. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/fileio/opencons.bas"}}%%(freebasic) dim a as string Open CONS For input As #1 Open CONS For output as #2 Print #2,"Please write something and press ENTER" Line Input #1,a Print #2, "You wrote : ";a Close Sleep %% {{fbdoc item="diff"}} - In QB the syntax was ##OPEN "CON:" FOR INPUT|OUTPUT AS [#] //filenum//## {{fbdoc item="see"}} - ##[[KeyPgOpenScrn Open Scrn]]## - ##[[KeyPgOpenErr Open Err]]## - ##[[KeyPgFreefile FreeFile]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}}{{fbdoc item="title" value="OPEN ERR"}}---- Opens standard input and standard error as a file. {{fbdoc item="syntax"}}## **[[KeyPgOpen Open]] Err** [for //mode//] [[KeyPgAs as]] [#]//filenum// [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## **Open Err** [for //mode//] as [#]//filenum// //or// //result// = **Open Err**( [for //mode//] as [#]//filenum// ) ## {{fbdoc item="param"}} ##//mode//## Ignored. ##//filenum//## An unused file number. {{fbdoc item="ret"}} Zero is returned if ##**Open Err**## completed successfully, otherwise a non-zero value is returned to indicate failure. {{fbdoc item="desc"}} This command opens ##stdin## to read from and ##stderr## to write to the console allowing read and write operations with normal file commands. The normal console commands, such as ##[[KeyPgColor Color]]## and ##[[KeyPgLocate Locate]]##, do not work in this mode, because they do not accept a file number. The ##[For Input|Output]## ##//mode//## is allowed for compatibility, but is ignored. **Runtime errors:** ##**Open Err**## throws one of the following [[ProPgErrorHandling runtime errors]]: //(##1##) Illegal function call// - Filenumber was not free at the time. use ##[[KeyPgFreefile Freefile]]## to ensure that filenumber is free. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/fileio/openerr.bas"}}%%(freebasic) Dim a as string OPEN ERR for input AS #1 print #1,"Please write something and press ENTER" line input #1, a PRINT #1, "You wrote"; a CLOSE sleep %% {{fbdoc item="diff"}} -New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgOpen Open]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}}{{fbdoc item="title" value="OPEN LPT"}}---- Open a printer device {{fbdoc item="syntax"}}## **Open Lpt** ["[LPT[x]:][//Printer_Name//][,//TITLE=Doc_Title//][,//EMU=TTY//]"] [For Input|Output] [[KeyPgAs as]] #//filenum// ## {{fbdoc item="usage"}}## **Open Lpt** "LPT..." [[KeyPgAs as]] [#]//filenum// //or// //result// = **Open Lpt**( "LPT..." [[KeyPgAs as]] [#]//filenum// ) ## {{fbdoc item="param"}} ##//x//## Specifies a port number. If omitted, output is sent to the system print spooler. ##//Printer_Name//## Name of printer to open. This parameter is ignored on DOS. ##//TITLE=Doc_Title//## Title of the print job as seen by the printer spooler. This parameter is ignored on DOS. ##//EMU=TTY//## Emulation of TTY output on a windows GDI printer, using driver text imaging. This parameter is ignored on DOS and Linux. ##For Input|Output## clause is allowed for compatibility, but it is ignored. ##//filenum//## An unused file number to assign to the device. {{fbdoc item="ret"}} Zero is returned if **Open Lpt** completed successfully, otherwise a non-zero value is returned to indicate failure. {{fbdoc item="desc"}} **Open Lpt** opens a connection to a printer device. The connection is treated like a file, so data may be written to the printer using ##[[KeyPgPrint Print]]## and ##[[KeyPgPutfileio Put #]]## commands. Any printer attached to the system may be opened with **Open Lpt** ##**Open Lpt** "LPT:" ...## will try to open the default printer on Windows and Linux, and "LPT1:" on DOS. ##[[KeyPgLprint Lprint]]## will automatically try to open the default printer on Windows and Linux, and ##"LPT1:"## on DOS. Platform specific notes: ==Windows== The argument EMU=TTY assumes printable ASCII or Unicode text, and applies printer driver text imaging to the input. EMU=TTY also allows the usage of CR, LF, BS, TAB, FF, etc., for virtual print-head movement...even when the printer is a GDI printer and therefore doesn't itself understand these special characters. If ",EMU=TTY" is omitted, the data must be sent in the printer's language (ESC/P, HPGL, PostScript, etc...). Other useful emulation modes aren't supported yet. ==Linux== A printer spooler available through ##lp## must be installed to access printers by name or a default printer. Spooler access was tested only with CUPS, but other spoolers may work that are invoked through ##lp##. Port are zero based on linux. ##"LPT1:"## corresponds with ##"/dev/lp0"##. The data must be sent in the printer's language (ESC/P, HPGL, PostScript, etc...). Emulation modes aren't supported yet. ==DOS== FreeBASIC does not support print spoolers on DOS. Printers must be accessible through ##"LPTx:"##. The data must be sent in the printer's language (ESC/P, HPGL, PostScript, etc...). Emulation modes aren't supported yet. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/fileio/openlpt1.bas"}}%%(freebasic) ' Send some text to the Windows printer on LPT1:, using driver text imaging. Open LPT "LPT1:EMU=TTY" For Output As #1 Print #1, "Testing!" Close %% {{fbdoc item="filename" value="examples/manual/fileio/openlpt2.bas"}}%%(freebasic) ' Sends contents of text file test.txt to Windows printer named "ReceiptPrinter" Dim RptInput As String Dim PrintFileNum as integer, RptFileFileNum as integer RptFileFileNum = Freefile Open "test.txt" For Input As #RptFileFileNum PrintFileNum = Freefile OPEN LPT "LPT:ReceiptPrinter,TITLE=ReceiptWinTitle,EMU=TTY" AS _ #PrintFilenum While (EOF(RptFileFileNum) = 0) Line Input #RptFileFileNum, RptInput Print #PrintFileNum, RptInput Wend Close #PrintFileNum ' Interestingly, does not require CHR(12). But if pagination is desired, CHR(12) is the way. Close #RptFileFileNum Print "Press any key to end program..." GetKey End %% {{fbdoc item="filename" value="examples/manual/fileio/openlpt.bas"}}%%(freebasic) 'This simple program will print a PostScript file to a PostScript compatible printer. Dim As UByte FFI, PPO Dim As String temp FFI = FreeFile() Open "sample.ps" For Input Access Read As #FFI PPO = FreeFile() Open Lpt "LPT1:" For Output As #PPO While (EOF(FFI) = 0) Line Input #FFI, temp Print #PPO, temp Wend Close #FFI Close #PPO Print "Printing Completed!" %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect the old syntax is supported OPEN "LPT:..." . This syntax used in the other dialects will open a regular file. {{fbdoc item="see"}} - ##[[KeyPgLprint Lprint]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}}{{fbdoc item="title" value="OPEN PIPE"}}---- Opens an external process' standard input (//stdin//) or output (//stdout//) stream for file operations. {{fbdoc item="syntax"}}## **Open Pipe** //shell_command// **For** **[[KeyPgInputfilemode Input]]** **As** [**#**]//filenumber// **Open Pipe** //shell_command// **For** **[[KeyPgOutput Output]]** **As** [**#**]//filenumber// **Open Pipe** //shell_command// **For** **[[KeyPgBinary Binary]]** //access_type// [**#**]//filenumber// ## {{fbdoc item="usage"}}## //result// = **Open Pipe**( //command//, **For** {**[[KeyPgInputfilemode Input]]**|**[[KeyPgOutput Output]]**}, **As** //filenumber// ) ##//or,//## //result// = **Open Pipe**( //command//, **For** **[[KeyPgBinary Binary]]**, //access_type//, **As** //filenumber// ) ##//(or in the QB-like syntax,)//## **Open Pipe** //filename// **For** {**[[KeyPgInputfilemode Input]]**|**[[KeyPgOutput Output]]**} **As** //filenumber// ##//(or,)//## **Open Pipe** //filename// **For** **[[KeyPgBinary Binary]]** //access_type// **As** //filenumber// ## {{fbdoc item="param"}} ##//shell_command//## The external process to execute in the operating system command shell. Relative file paths are relative to the current directory (see ##[[KeyPgCurdir Curdir]]##). When opening a pipe for a process that requires double quotes in either its executable path, or its arguments, the entire pipe string should be nested inside of double quotes. ##//access_type//## The type of read or write access requested by the calling process. - ##[[KeyPgAccess Access]]## {##Read##|##Write##} //(either the //stdin// or //stdout// stream of the external process can be opened)// ##//filenumber//## An available file number to bind to the external process' //stdin// or //stdout// stream. {{fbdoc item="ret"}} In the first usage, ##**Open Pipe**## returns zero (0) on success and a non-zero error code otherwise. {{fbdoc item="desc"}} ##**Open Pipe**## executes another process in the command shell and opens either its //stdin// or //stdout// streams for reading or writing. A //file number// is bound to the stream, which is used in subsequent file operations, such as ##[[KeyPgInputPp Input #]]##. An available ##//filenumber//## can be retrieved with ##[[KeyPgFreefile Freefile]]##. If the external process does not exist, a runtime error is thrown. The ##[[KeyPgInputfilemode Input]]## and ##[[KeyPgOutput Output]]## //file modes// open the external process' //stdin// and //stdout// streams, respectively, for sequential text I/O, useful for reading or writing plain text. Characters, words or whole lines can then be read or written using text-mode file operations, such as ##[[KeyPgLineinput Line Input #]]## and ##[[KeyPgPrintPp Print #]]##. The ##[[KeyPgBinary Binary]]## //file mode// opens the external process' //stdin// or //stdout// streams - depending on the //access type// specified (see description of the ##//access_type//## parameter above) - for random-access reading or writing of arbitrarily sized and interpreted raw data. Simple data type values, like ##[[KeyPgByte Byte]]## and ##[[KeyPgLongint Longint]]##, and whole chunks of memory can be read from or written to the streams with binary-mode file operations like ##[[KeyPgGetfileio Get #]]## and ##[[KeyPgPutfileio Put #]]##. {{fbdoc item="target"}} - The ##[[KeyPgBinary Binary]]## //file mode// is not supported on all platforms; ##**Open Pipe**## will throw an error if it is unable to open the external process' //stdin// or //stdout// streams in binary mode. **Runtime errors:** ##**Open Pipe**## throws one of the following [[ProPgErrorHandling runtime errors]]: //(##1##) Illegal function call// - Filenumber was not free at the time. use ##[[KeyPgFreefile Freefile]]## to ensure that filenumber is free. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/fileio/openpipe.bas"}}%%(freebasic) dim text as string open pipe "fbc.exe" for input as #1 print "Output of fbc:" do while not eof(1) line input #1, text print text loop %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgOpenCons Open Cons]]## - ##[[KeyPgOpenErr Open Err]]## - ##[[KeyPgFreefile Freefile]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}}{{fbdoc item="title" value="OPEN SCRN"}}---- Opens the console directly for input and output as a file {{fbdoc item="syntax"}}## **[[KeyPgOpen Open]] Scrn** [for //mode//] [[KeyPgAs as]] [#]//filenum// [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## **Open Scrn** [for //mode//] as [#]//filenum// //or// //result// = **Open Scrn**( [for //mode//] as [#]//filenum// ) ## {{fbdoc item="param"}} ##//mode//## Either ##[[KeyPgInputfilemode Input]]## or ##[[KeyPgOutput Output]]##. If omitted, ##[[KeyPgOutput Output]]## is assumed. ##//filenum//## An unused file number. {{fbdoc item="ret"}} Zero is returned if ##**Open Err**## completed successfully, otherwise a non-zero value is returned to indicate failure. {{fbdoc item="desc"}} This command opens the console for both input and output as a file, allowing to read/write from/to it with normal file commands. This command may use direct access to the console for speed in some implementations, so it should not be used when the input / output is required to be redirected or piped with OS commands. The normal console commands, such as ##[[KeyPgColor Color]]## and ##[[KeyPgLocate Locate]]##, do not work in this mode, because they do not accept a file number. The ##[For Input|Output]## clause is allowed for compatibility, but is ignored. ##//filenum//## is an unused file number. An unused file number can be found using ##[[KeyPgFreefile FreeFile]]##. **Runtime errors:** ##**Open Cons**## throws one of the following [[ProPgErrorHandling runtime errors]]: //(##1##) Illegal function call// - Filenumber was not free at the time. use ##[[KeyPgFreefile Freefile]]## to ensure that filenumber is free. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/fileio/openscrn.bas"}}%%(freebasic) dim a as string OPEN SCRN for input AS #1 print #1,"Please write something and press ENTER" line input #1,a PRINT #1, "You wrote";a CLOSE sleep %% {{fbdoc item="diff"}} - QB used OPEN "SCRN:" ... {{fbdoc item="see"}} - ##[[KeyPgOpenCons Open Cons]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}}{{fbdoc item="title" value="Operator = (Equal)"}}---- Compares two expressions for equality {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgByte byte]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgByte byte]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUbyte ubyte]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUbyte ubyte]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgShort short]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgShort short]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUshort ushort]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUshort ushort]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUinteger uinteger]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUinteger uinteger]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgLongint longint]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgLongint longint]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUlongint ulongint]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUlongint ulongint]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgString string]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgZstring zstring]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgZstring zstring]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgWstring wstring]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgWstring wstring]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] //T//, [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] //T// ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = //lhs// **=** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The left-hand side expression to compare to. ##//rhs//## The right-hand side expression to compare to. ##//T//## Any pointer type. {{fbdoc item="ret"}} Returns negative one (-1) if expressions are equal, or zero (0) if unequal. {{fbdoc item="desc"}} **##Operator =## (Equality)** is a binary operator that compares two expressions for equality and returns the result - a boolean value in the form of an ##[[KeyPgInteger Integer]]##: negative one (-1) for true and zero (0) for false. The arguments are not modified in any way. This operator can be overloaded to accept user-defined types as well. **##Operator =## (Equality)** should not be confused with initializations or assignments, both of which also use the "##=##" symbol. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/equal.bas"}}%%(freebasic) dim i as integer = 0 '' initialization: initialise i with a value of 0 i = 420 '' assignment: assign to i the value of 420 if (i = 69) then '' equation: compare the equality of the value of i and 69 print "serious error: i should equal 420" end -1 end if %% ##[[KeyPgOpNotEqual Operator <>]]## (Inequality) is complement to **##Operator =## (Equality)**, and is functionally identical when combined with ##[[KeyPgOpNot Operator Not]]## (Bit-wise Complement). {{fbdoc item="filename" value="examples/manual/operator/equal2.bas"}}%%(freebasic) if (420 = 420) then print "(420 = 420) is true." if not (69 <> 69) then print "not (69 <> 69) is true." %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - none {{fbdoc item="see"}} - ##[[KeyPgOpNotEqual Operator <>]]## (Inequality) - ##[[KeyPgOpAssignment Operator = ]]## (Assignment) {{fbdoc item="back" value="CatPgOpConditional|Relational Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator EQV (Equivalence)"}}---- Returns the bitwise-and (equivalence) of two numeric values {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Eqv** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] //T1//, [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] //T2// ) [[KeyPgAs as]] //Ret// ## {{fbdoc item="usage"}}## //result// = //lhs// **Eqv** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The left-hand side expression. ##//T1//## Any numeric type. ##//rhs//## The right-hand side expression. ##//T2//## Any numeric type. ##//Ret//## A numeric type (varies with ##//T1//## and ##//T2//##). {{fbdoc item="ret"}} Returns the bitwise-equivalence of the two operands. {{fbdoc item="desc"}} This operator returns the bitwise-equivalence of its operands, a logical operation that results in a value with bits set depending on the bits of the operands. The truth table below demonstrates all combinations of a boolean-equivalence operation: {{table columns="3" cellpadding="2" cells="Lhs Bit;Rhs Bit;Result;0;0;1;1;0;0;0;1;0;1;1;1"}} No short-circuiting is performed - both expressions are always evaluated. The return type depends on the types of values passed. ##[[KeyPgByte Byte]]##, ##[[KeyPgUbyte Ubyte]]## and floating-point type values are first converted to ##[[KeyPgInteger Integer]]##. If the left and right-hand side types differ only in signedness, then the return type is the same as the left-hand side type (##//T1//##), otherwise, the larger of the two types is returned. This operator can be overloaded for user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/eqv-bitwise.bas"}}%%(freebasic) dim as ubyte a = &b00110011 dim as ubyte b = &b01010101, c c = a eqv b '' c = &b10011001 %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - [[TblTruth Operator Truth Tables]] {{fbdoc item="back" value="CatPgOpLogical|Logical Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="OPERATOR"}}---- Declares or defines an overloaded operator. {{fbdoc item="syntax"}}## { [[KeyPgType Type]] | [[KeyPgClass Class]] | [[KeyPgUnion Union]] | [[KeyPgEnum Enum]] } //typename// [[KeyPgDeclare declare]] **Operator** [[KeyPgCast cast]] () [[KeyPgAs as]] [[DataType datatype]] [[KeyPgDeclare declare]] **Operator** //assignment_op// ( [ [[KeyPgByref byref]] | [[KeyPgByval byval]] ] //rhs// [[KeyPgAs as]] [[DataType datatype]] ) [[KeyPgDeclare declare]] **Operator** [[KeyPgOpNew new]] ( //size// [[KeyPgAs as]] [[KeyPgUinteger uinteger]] ) [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] [[KeyPgDeclare declare]] [[KeyPgStaticMember static]] **Operator** [[KeyPgOpNew new]][] ( //size// [[KeyPgAs as]] [[KeyPgUinteger uinteger]] ) [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] [[KeyPgDeclare declare]] **Operator** [[KeyPgOpDelete delete]] ( //buf// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] ) [[KeyPgDeclare declare]] [[KeyPgStaticMember static]] **Operator** [[KeyPgOpDelete delete]][] ( //buf// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] ) End { [[KeyPgType Type]] | [[KeyPgClass Class]] | [[KeyPgUnion Union]] | [[KeyPgEnum Enum]] } { [[KeyPgType Type]] | [[KeyPgClass Class]] | [[KeyPgUnion Union]] } //typename// [[KeyPgDeclare declare]] **Operator** [[KeyPgOpFor For]] () [[KeyPgDeclare declare]] **Operator** [[KeyPgOpFor For]] ( [ [[KeyPgByref byref]] | [[KeyPgByval byval]] ] //stp// [[KeyPgAs as]] //typename// ) [[KeyPgDeclare declare]] **Operator** [[KeyPgOpStep Step]] () [[KeyPgDeclare declare]] **Operator** [[KeyPgOpStep Step]] ( [ [[KeyPgByref byref]] | [[KeyPgByval byval]] ] //stp// [[KeyPgAs as]] //typename// ) [[KeyPgDeclare declare]] **Operator** [[KeyPgOpNext Next]] ( [ [[KeyPgByref byref]] | [[KeyPgByval byval]] ] //cond// [[KeyPgAs as]] //typename// ) [[KeyPgAs as]] [[KeyPgInteger Integer]] [[KeyPgDeclare declare]] **Operator** [[KeyPgOpNext Next]] ( [ [[KeyPgByref byref]] | [[KeyPgByval byval]] ] //cond// [[KeyPgAs as]] //typename//, [ [[KeyPgByref byref]] | [[KeyPgByval byval]] ] //stp// [[KeyPgAs as]] //typename// ) [[KeyPgAs as]] [[KeyPgInteger Integer]] End { [[KeyPgType Type]] | [[KeyPgClass Class]] | [[KeyPgUnion Union]] } [[KeyPgDeclare declare]] **Operator** //unary_op// ( [ [[KeyPgByref byref]] | [[KeyPgByval byval]] ] //rhs// [[KeyPgAs as]] [[DataType datatype]] ) [[KeyPgAs as]] [[DataType datatype]] [[KeyPgDeclare declare]] **Operator** //binary_op// ( [ [[KeyPgByref byref]] | [[KeyPgByval byval]] ] //lhs// [[KeyPgAs as]] [[DataType datatype]], [ [[KeyPgByref byref]] | [[KeyPgByval byval]] ] //rhs// [[KeyPgAs as]] [[DataType datatype]] ) [[KeyPgAs as]] [[DataType datatype]] **Operator** //typename//.[[KeyPgCast cast]] () [[KeyPgAs as]] [[DataType datatype]] **Operator** //typename//.//assignment_op// ( [ [[KeyPgByref byref]] | [[KeyPgByval byval]] ] //rhs// [[KeyPgAs as]] [[DataType datatype]] ) **Operator** //unary_op// ( [ [[KeyPgByref byref]] | [[KeyPgByval byval]] ] //rhs// [[KeyPgAs as]] [[DataType datatype]] ) [[KeyPgAs as]] [[DataType datatype]] **Operator** //binary_op// ( [ [[KeyPgByref byref]] | [[KeyPgByval byval]] ] //lhs// [[KeyPgAs as]] [[DataType datatype]], [ [[KeyPgByref byref]] | [[KeyPgByval byval]] ] //rhs// [[KeyPgAs as]] [[DataType datatype]] ) [[KeyPgAs as]] [[DataType datatype]] **Operator** //typename//.[[KeyPgOpNew new]] ( //size// as uinteger ) [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] [[KeyPgStaticMember static]] **Operator** //typename//.[[KeyPgOpNew new]][] ( //size// [[KeyPgAs as]] [[KeyPgUinteger uinteger]] ) [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] **Operator** //typename//.[[KeyPgOpDelete delete]] ( //buf// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] ) [[KeyPgStaticMember static]] **Operator** //typename//.[[KeyPgOpDelete delete]][] ( //buf// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] ) ## {{fbdoc item="param"}} ##//typename//## Name of the ##[[KeyPgType Type]]##, ##[[KeyPgClass Class]]##, ##[[KeyPgUnion Union]]##, or ##[[KeyPgEnum Enum]]##. ##//assignment_op//## ##let += -= *= /= \= mod= shl= shr= and= or= xor= imp= eqv= ^=## ##//unary_op//## ##""-"" not @ * -> abs sgn fix frac int## ##//binary_op//## ##+ - * / \ mod shl shr and or xor imp eqv ^ = <> < > <= >=## {{fbdoc item="desc"}} The built in operators like ##=##, ##+##, and ##cast## have predefined behaviors when used in expressions. These operators can be overloaded to do something other than predefined operations when at least one of the arguments to the operator is a ##[[KeyPgType Type]]##, ##[[KeyPgClass Class]]##, ##[[KeyPgEnum Enum]]##, or ##[[KeyPgUnion Union]]## data type. Operators are just functions. The operator '+' has functionality like ##Function Plus( A as DataType, B as DataType ) as DataType##. See //[[ProPgOperatorOverloading Operator Overloading]]// for more information. Operators can be overloaded to accept different data types as parameters. Only the ##[[KeyPgCast Cast]]## Operator can be overloaded to return different types. Non-static operator members are declared inside the ##[[KeyPgType Type]]## or ##[[KeyPgClass Class]]##. Global operators are declared outside. All operator definitions (procedure bodies) must appear outside. ##**Let**##, ##**Cast**##, and other assignment operators must be declared inside the ##[[KeyPgType Type]]## or ##[[KeyPgClass Class]]##. They are passed a hidden ##[[KeyPgThis this]]## parameter and have a return data type same as the ##[[KeyPgType Type]]## or ##[[KeyPgClass Class]]## they are declared in. Unary operators must be declared outside the ##[[KeyPgType Type]]##, ##[[KeyPgClass Class]]##, or ##[[KeyPgEnum Enum]]## and have a return data type explicitly declared. Unary operators can be overloaded to return any valid data type, except for ##[[KeyPgOpPtrMemberAccess Operator -> (Pointer to member access)]]## which must return a ##[[KeyPgType Type]]## or ##[[KeyPgClass Class]]## data type. Binary operators must be declared outside the ##[[KeyPgType Type]]##, ##[[KeyPgClass Class]]##, or ##[[KeyPgEnum Enum]]## and have a return data type explicitly declared. Binary operators can be overloaded with valid data types, except for relational operators, which must return ##[[KeyPgInteger Integer]]##. ##[[KeyPgLet Let]]## refers to the assignment operator, as in ##LET a=b##. The ##[[KeyPgLet Let]]## keyword is omitted in common practice, and is not allowed in the //[[CompilerOptlang -lang fb]]// dialect. However, ##[[KeyPgOpLetlist Let()]]## can be used to assign the fields of a UDT to multiple variables. See ##[[KeyPgOpFor For]]##, ##[[KeyPgOpStep Step]]##, and ##[[KeyPgOpNext Next]]## for more information on overloading the ##[[KeyPgFornext For..Next]]## statement for use with user defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/udt/operator.bas"}}%%(freebasic) Type Vector2D As Single x, y '' Return a string containing the vector data. Declare Operator Cast() As String End Type '' Allow two vectors to be able to be added together. Declare Operator + ( ByRef lhs As Vector2D, ByRef rhs As Vector2D ) As Vector2D Operator Vector2D.cast () As String Return "(" + Str(x) + ", " + Str(y) + ")" End Operator Operator + ( ByRef lhs As Vector2D, ByRef rhs As Vector2D ) As Vector2D Return type( lhs.x + rhs.x, lhs.y + rhs.y ) End Operator Dim a As Vector2D = type( 1.2, 3.4 ) Dim b As Vector2D = type( 8.9, 6.7 ) Print "a = "; a Print "b = "; b Print "a + b = "; a + b %% {{fbdoc item="lang"}} - Only available in the //[[CompilerOptlang -lang fb]]// dialect. {{fbdoc item="see"}} - ##[[KeyPgClass Class]]## - ##[[KeyPgClass Enum]]## - ##[[KeyPgType Type]]## {{fbdoc item="back" value="CatPgUserDefTypes|User Defined Types"}}{{fbdoc item="title" value="Operator ^ (Exponentiate)"}}---- Raises a numeric expression to some power {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **^** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgDouble double]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgDouble double]] ) [[KeyPgAs as]] [[KeyPgDouble double]] ## {{fbdoc item="usage"}}## //result// = //lhs// **##^##** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The left-hand side base expression. ##//rhs//## The right-hand side exponent expression. {{fbdoc item="ret"}} Returns the exponentiation of a base expression raised to some exponent. {{fbdoc item="desc"}} **##Operator ^## (Exponentiate)** returns the result of a base expression (##//lhs//##) raised to some exponent expression (##//rhs//##). **^** works with double float numbers only, operands of other types will be converted into double before performing the exponentiation. Exponent of a fractional value (1/n) is the same as taking n-th root from the base, for example, 2 **^** (1/3) is the cubed root of 2. Neither of the operands are modified in any way. This operator can be overloaded for user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/exponent.bas"}}%%(freebasic) DIM AS DOUBLE n INPUT "Please enter a positive number: ", n PRINT PRINT n;" squared is "; n ^ 2 PRINT "The fifth root of "; n;" is "; n ^ 0.2 SLEEP %% Output: %% Please enter a positive number: 3.4 3.4 squared is 11.56 The fifth root of 3.4 is 1.27730844458754 %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - [[CatPgMath Mathematical Functions]] {{fbdoc item="back" value="CatPgOpArithmetic|Arithmetic Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator For (iteration)"}}---- Declares or defines operators used by a ##[[KeyPgFornext For...Next]]## loop with user defined type variables {{fbdoc item="syntax"}}## { [[KeyPgType Type]] | [[KeyPgClass Class]] | [[KeyPgUnion Union]] } //typename// [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **For** () [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **For** ( [ [[KeyPgByref byref]] | [[KeyPgByval byval]] ] //stp// [[KeyPgAs as]] //typename// ) //...// End { [[KeyPgType Type]] | [[KeyPgClass Class]] | [[KeyPgUnion Union]] } ## {{fbdoc item="usage"}}## [[KeyPgFornext For]] //iterator// [ As //typename// ] = //start_value// To //end_value// [ [[KeyPgFornext Step]] //step_value// ] [// ...statements... //] [[KeyPgFornext Next]] ## {{fbdoc item="param"}} ##//typename//## name of the ##[[KeyPgType Type]]##, ##[[KeyPgClass Class]]##, or ##[[KeyPgUnion Union]]## ##//stp//##, ##//step_value//## a ##//typename//## object used as an incremental value ##//iterator//## a ##//typename//## object used as an iterator ##//end_value//## a ##//typename//## object used as a loop-terminating value ##//start_value//## a ##//typename//## object used to copy construct or assign to the iterator initially {{fbdoc item="desc"}} ##**Operator For**##, ##[[KeyPgOpNext Operator Next]]## and ##[[KeyPgOpStep Operator Step]]## can be overloaded in user-defined type definitions to allow objects of that type to be used as iterators and step values in ##[[KeyPgFornext For...Next]]## loops. ##**Operator For**## is called immediately after copy constructing or assigning to the iterator object, and allows the object to perform any additional initialization needed in preparation for the loop. The first version of ##**Operator For**## is used if no step value is given in the ##[[KeyPgFornext For...Next]]## statement. If a step value is given, the second version is used and is passed the step value. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/udt/for.bas"}}%%(freebasic) '' Example Type type T value as double declare constructor( byval x as double = 0 ) declare operator += ( byval x as double ) declare operator for() declare operator step() declare operator next( byref cond as T ) as integer declare operator cast() as string end type constructor T ( byval x as double ) value = x end constructor operator <= ( byref lhs as T, byref rhs as T ) as integer operator = ( lhs.value <= rhs.value ) end operator operator T.+= ( byval x as double ) value += x end operator operator T.for() end operator operator T.step() this += 1 end operator operator T.next( byref cond as T ) as integer operator = ( this <= cond ) end operator operator T.cast() as string operator = str( value ) end operator '' Example Usage for i as T = 1 to 10 print i next i %% {{fbdoc item="lang"}} - Only available in the //[[CompilerOptlang -lang fb]]// dialect. {{fbdoc item="see"}} - ##[[KeyPgOpNext Operator Next]]## - ##[[KeyPgOpStep Operator Step]]## - ##[[KeyPgFornext For...Next]]## {{fbdoc item="back" value="CatPgOpIterating|Iterating Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator > (Greater than)"}}---- Compares an expression greater than another expression {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **>** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgByte byte]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgByte byte]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **>** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUbyte ubyte]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUbyte ubyte]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **>** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgShort short]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgShort short]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **>** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUshort ushort]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUshort ushort]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **>** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **>** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUinteger uinteger]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUinteger uinteger]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **>** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgLongint longint]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgLongint longint]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **>** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUlongint ulongint]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUlongint ulongint]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **>** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgString string]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **>** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgZstring zstring]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgZstring zstring]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **>** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgWstring wstring]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgWstring wstring]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **>** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] //T//, [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] //T// ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = //lhs// **>** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The left-hand side expression to compare to. ##//rhs//## The right-hand side expression to compare to. ##//T//## Any pointer type. {{fbdoc item="ret"}} Returns negative one (-1) if the left-hand side expression is greater than the right-hand side expression, or zero (0) if less than or equal. {{fbdoc item="desc"}} **##Operator >## (Greater than)** is a binary operator that compares an expression greater than another expression and returns the result - a boolean value in the form of an ##[[KeyPgInteger Integer]]##: negative one (-1) for true and zero (0) for false. The arguments are not modified in any way. This operator can be overloaded to accept user-defined types as well. {{fbdoc item="ex"}} ##[[KeyPgOpLessThanOrEqual Operator <=]]## (Less than or equal) is complement to **##Operator >## (Greater than)**, and is functionally identical when combined with ##[[KeyPgOpNot Operator Not]]## (Bit-wise Complement). {{fbdoc item="filename" value="examples/manual/operator/greater-than.bas"}}%%(freebasic) if (420 > 69) then print "(420 > 69) is true." if not (420 <= 69) then print "not (420 <= 69) is true." %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - none {{fbdoc item="see"}} - ##[[KeyPgOpLessThanOrEqual Operator <=]]## (Less than or equal) {{fbdoc item="back" value="CatPgOpConditional|Relational Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator >= (Greater than or Equal)"}}---- Compares an expression greater than or equal to another expression {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **>=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgByte byte]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgByte byte]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **>=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUbyte ubyte]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUbyte ubyte]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **>=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgShort short]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgShort short]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **>=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUshort ushort]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUshort ushort]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **>=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **>=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUinteger uinteger]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUinteger uinteger]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **>=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgLongint longint]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgLongint longint]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **>=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUlongint ulongint]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUlongint ulongint]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **>=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgString string]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **>=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgZstring zstring]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgZstring zstring]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **>=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgWstring wstring]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgWstring wstring]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **>=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] //T//, [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] //T// ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = //lhs// **>=** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The left-hand side expression to compare to. ##//rhs//## The right-hand side expression to compare to. ##//T//## Any pointer type. {{fbdoc item="ret"}} Returns negative one (-1) if the left-hand side expression is greater than or equal to the right-hand side expression, or zero (0) if less than. {{fbdoc item="desc"}} **##Operator >=## (Greater than or Equal)** is a binary operator that compares an expression greater than or equal to another expression and returns the result - a boolean value in the form of an ##[[KeyPgInteger Integer]]##: negative one (-1) for true and zero (0) for false. The arguments are not modified in any way. This operator can be overloaded to accept user-defined types as well. {{fbdoc item="ex"}} ##[[KeyPgOpLessThan Operator <]]## (Less than) is complement to **##Operator >=## (Greater than or Equal)**, and is functionally identical when combined with ##[[KeyPgOpNot Operator Not]]## (Bit-wise Complement). {{fbdoc item="filename" value="examples/manual/operator/greater-than-or-equal.bas"}}%%(freebasic) if (420 >= 69) then print "(420 >= 69) is true." if not (420 < 69) then print "not (420 < 69) is true." %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - none {{fbdoc item="see"}} - ##[[KeyPgOpLessThan Operator <]]## (Less than) {{fbdoc item="back" value="CatPgOpConditional|Relational Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator Imp (Implication)"}}---- Returns the bitwise-and (implication) of two numeric values {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Imp** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] //T1//, [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] //T2// ) [[KeyPgAs as]] //Ret// ## {{fbdoc item="usage"}}## //result// = //lhs// **Imp** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The left-hand side expression. ##//T1//## Any numeric type. ##//rhs//## The right-hand side expression. ##//T2//## Any numeric type. ##//Ret//## A numeric type (varies with ##//T1//## and ##//T2//##). {{fbdoc item="ret"}} Returns the bitwise-implication of the two operands. {{fbdoc item="desc"}} This operator returns the bitwise-implication of its operands, a logical operation that results in a value with bits set depending on the bits of the operands. The truth table below demonstrates all combinations of a boolean-implication operation: {{table columns="3" cellpadding="2" cells="Lhs Bit;Rhs Bit;Result;0;0;1;1;0;0;0;1;1;1;1;1"}} No short-circuiting is performed - both expressions are always evaluated. The return type depends on the types of values passed. ##[[KeyPgByte Byte]]##, ##[[KeyPgUbyte Ubyte]]## and floating-point type values are first converted to ##[[KeyPgInteger Integer]]##. If the left and right-hand side types differ only in signedness, then the return type is the same as the left-hand side type (##//T1//##), otherwise, the larger of the two types is returned. This operator can be overloaded for user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/imp-bitwise.bas"}}%%(freebasic) dim as ubyte a, b, c a = &b00001111 b = &b01010101 c = a imp b '' c = &b11110101 %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - [[TblTruth Operator Truth Tables]] {{fbdoc item="back" value="CatPgOpLogical|Logical Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator \ (Integer divide)"}}---- Divides two ##[[KeyPgInteger Integer]]## expressions {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **\** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = //lhs// **##\##** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The left-hand side dividend expression. ##//rhs//## The right-hand side divisor expression. {{fbdoc item="ret"}} Returns the quotient of an ##[[KeyPgInteger Integer]]## dividend and divisor. {{fbdoc item="desc"}} **##Operator \## (Integer division)** divides two ##[[KeyPgInteger Integer]]## expressions and returns the result. Numeric values are converted to ##[[KeyPgInteger Integer]]## by rounding up or down, and the fractional part of the resulting quotient is truncated. If the divisor (##//rhs//##) is zero (0), a division by zero error will be raised. Neither of the operands are modified in any way. This operator can be overloaded for user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/integer-divide.bas"}}%%(freebasic) DIM n AS DOUBLE PRINT n \ 5 n = 7 \ 2.6 '' => 7 \ 3 => 2.33333 => 2 PRINT n n = 7 \ 2.4 '' => 7 \ 2 => 3.5 => 3 PRINT n SLEEP %% Output: %% 0 2 3 %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - [[CatPgMath Mathematical Functions]] {{fbdoc item="back" value="CatPgOpArithmetic|Arithmetic Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator < (Less than)"}}---- Compares an expression less than another expression {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgByte byte]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgByte byte]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUbyte ubyte]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUbyte ubyte]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgShort short]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgShort short]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUshort ushort]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUshort ushort]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUinteger uinteger]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUinteger uinteger]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgLongint longint]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgLongint longint]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUlongint ulongint]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUlongint ulongint]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgString string]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgZstring zstring]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgZstring zstring]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgWstring wstring]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgWstring wstring]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] //T//, [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] //T// ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = //lhs// **<** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The left-hand side expression to compare to. ##//rhs//## The right-hand side expression to compare to. ##//T//## Any pointer type. {{fbdoc item="ret"}} Returns negative one (-1) if the left-hand side expression is less than the right-hand side expression, or zero (0) if greater than or equal. {{fbdoc item="desc"}} **##Operator <## (Less than)** is a binary operator that compares two expressions for inequality and returns the result - a boolean value in the form of an ##[[KeyPgInteger Integer]]##: negative one (-1) for true and zero (0) for false. The arguments are not modified in any way. This operator can be overloaded to accept user-defined types as well. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/less-than1.bas"}}%%(freebasic) const size as integer = 4 dim array(size - 1) as integer = { 1, 2, 3, 4 } dim index as integer = 0 while (index < size) print array(index) index += 1 wend %% ##[[KeyPgOpGreaterThanOrEqual Operator >=]]## (Greater than or equal) is complement to **##Operator <## (Less than)**, and is functionally identical when combined with ##[[KeyPgOpNot Operator Not]]## (Bit-wise Complement). {{fbdoc item="filename" value="examples/manual/operator/less-than3.bas"}}%%(freebasic) if (69 < 420) then print "(69 < 420) is true." if not (69 >= 420) then print "not (69 >= 420) is true." %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - none {{fbdoc item="see"}} - ##[[KeyPgOpGreaterThanOrEqual Operator >=]]## (Greater than or equal) {{fbdoc item="back" value="CatPgOpConditional|Relational Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator <= (Less than or Equal)"}}---- Compares an expression less than or equal to another expression {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgByte byte]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgByte byte]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUbyte ubyte]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUbyte ubyte]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgShort short]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgShort short]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUshort ushort]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUshort ushort]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUinteger uinteger]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUinteger uinteger]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgLongint longint]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgLongint longint]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUlongint ulongint]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUlongint ulongint]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgString string]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgZstring zstring]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgZstring zstring]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgWstring wstring]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgWstring wstring]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<=** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] //T//, [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] //T// ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = //lhs// **<=** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The left-hand side expression to compare to. ##//rhs//## The right-hand side expression to compare to. ##//T//## Any pointer type. {{fbdoc item="ret"}} Returns negative one (-1) if the left-hand side expression is less than or equal to the right-hand side expression, or zero (0) if greater than. {{fbdoc item="desc"}} **##Operator <=## (Less than or Equal)** is a binary operator that compares an expression less than or equal to another expression and returns the result - a boolean value in the form of an ##[[KeyPgInteger Integer]]##: negative one (-1) for true and zero (0) for false. The arguments are not modified in any way. This operator can be overloaded to accept user-defined types as well. {{fbdoc item="ex"}} ##[[KeyPgOpGreaterThan Operator >]]## (Greater than) is complement to **##Operator <=## (Less than or Equal)**, and is functionally identical when combined with ##[[KeyPgOpNot Operator Not]]## (Bit-wise Complement). {{fbdoc item="filename" value="examples/manual/operator/less-than-or-equal.bas"}}%%(freebasic) if (69 <= 420) then print "(69 <= 420) is true." if not (60 > 420) then print "not (420 > 69) is true." %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - none {{fbdoc item="see"}} - ##[[KeyPgOpGreaterThan Operator >]]## (Greater than) {{fbdoc item="back" value="CatPgOpConditional|Relational Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator Let (Assign)"}}---- Indicates the assignment operator when overloading [[KeyPgOpAssignment Operator = (Assignement]] {{fbdoc item="syntax"}}## { [[KeyPgType Type]] | [[KeyPgClass Class]] | [[KeyPgUnion Union]] | [[KeyPgEnum Enum]] } //typename// [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Let** ( [ [[KeyPgByref byref]] | [[KeyPgByval byval]] ] //rhs// [[KeyPgAs as]] [[DataType datatype]] ) End { [[KeyPgType Type]] | [[KeyPgClass Class]] | [[KeyPgUnion Union]] } [[KeyPgOperator operator]] //typename//.**Let** ( [ [[KeyPgByref byref]] | [[KeyPgByval byval]] ] //rhs// [[KeyPgAs as]] [[DataType datatype]] ) ## {{fbdoc item="usage"}}## //lhs// **=** //rhs// ## {{fbdoc item="param"}} ##//typename//## name of the ##[[KeyPgType Type]]##, ##[[KeyPgClass Class]]##, ##[[KeyPgUnion Union]]##, or ##[[KeyPgEnum Enum]]## ##//lhs//## The variable to assign to. ##//rhs//## The value to assign. {{fbdoc item="desc"}} ##**Let**## is used to overload the ##[[KeyPgOpAssignment Operator = (Assignment)]]## operator and to distinguish it from the comparison operator ##[[KeyPgOpEqual Operator = (Equal)]]##. ##//lhs// **=** //rhs//## will assign the ##//rhs//## to ##//lhs//## by invoking the **Let** operator procedure defined int ##//typename//##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/let.bas"}}%%(freebasic) type T x as integer y as integer declare operator let( byref rhs as T ) end type operator T.let( byref rhs as T ) x = rhs.x y = rhs.y end operator dim a as T = ( 5, 7 ) dim b as T '' Do the assinment invoking the LET '' operator procedure b = a print "a.x = "; a.x print "a.y = "; a.y print print "b.x = "; b.x print "b.y = "; b.y %% Output: %% a.x = 5 a.y = 7 b.x = 5 b.y = 7 %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. - In the //[[CompilerOptlang -lang qb]]// dialect, an assignment expression can be preceded by the ##[[KeyPgLet Let]]## keyword. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgLet Let]]## - ##[[KeyPgOpEqual Operator Let() (Assignment)]]## - ##[[KeyPgOpEqual Operator = (Assignment)]]## - ##[[KeyPgOpEqual Operator = (Equal)]]## {{fbdoc item="back" value="CatPgOpAssignment|Assignment Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator LET() (Assignment)"}}---- Assigns fields of a user defined type to a list of variables {{fbdoc item="syntax"}}## **Let**( //variable1// [, //variable2// [, ... ]] ) = //UDT_var// ## {{fbdoc item="param"}} ##//variable1// [, //variable2// [, ... ]]## Comma separated list of variables to receive the values of the ##//UDT//## variable's fields. ##//UDT_var//## A user defined type variable. {{fbdoc item="desc"}} Assigns the values from the ##//UDT_var//## variable's fields to the list of variables. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/let-list.bas"}}%%(freebasic) Type Vector3D x As Double y As Double z as Double End Type Dim a As Vector3D = ( 5, 7, 9 ) Dim x As Double, y As Double '' Get the first two fields only Let( x, y ) = a Print "x = "; x Print "y = "; y %% Output: %% x = 5 y = 7 %% {{fbdoc item="lang"}} - Only available in the //[[CompilerOptlang -lang fb]]// dialect. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgLet Let]]## - ##[[KeyPgOpAssignment Operator = (Assignment)]]## - ##[[KeyPgOpLet Operator Let (Assignment)]]## {{fbdoc item="back" value="CatPgOpAssignment|Assignment Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:55:47 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 14d566f152713092e47e28131e8a161d Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 1805 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="Operator . (Member access)"}}---- Returns a reference to a member from a reference to an object {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **.** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] //T// ) [[KeyPgAs as]] //U// ## ~&//Note that **##Operator .## (Member access)** returns a reference. As of 02.27.07, ""FreeBASIC"" syntax does not support returning references. When it does, this syntax will need to be changed.// {{fbdoc item="usage"}}## //result// = //lhs// **.** //rhs// ## {{fbdoc item="param"}} ##//lhs//## An object. ##//T//## A user-defined type. ##//rhs//## The name of a member to access. ##//U//## The type that ##//rhs//## refers to. {{fbdoc item="ret"}} Returns a reference to the member specified by ##//rhs//##. {{fbdoc item="desc"}} **##Operator .## (Member access)** returns a reference to a member of an object. **##Operator .## (Member access)** can also be used to access members of an implicit object inside a ##[[KeyPgWith With..End With]]## block. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/udt/access.bas"}}%%(freebasic) type T as integer a, b end type dim x as T '' Access the member 'a' of x. x.a = 10 '' Access the member 'b' of x. with x .b = 20 end with %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgOpPtrMemberAccess Operator -> (Pointer to member access)]]## - ##[[KeyPgOpAt Operator @ (Address of)]]## - ##[[KeyPgOpValueOf Operator * (Value of)]]## - ##[[KeyPgWith With..End With]]## {{fbdoc item="back" value="CatPgOpTypeclass|Type or Class Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}} {{fbdoc item="title" value="Operator Mod (Modulus)"}}---- Finds the remainder from a division operation {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Mod** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = //lhs// **Mod** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The left-hand side dividend expression. ##//rhs//## The right-hand side divisor expression. {{fbdoc item="ret"}} Returns the remainder of a division operation. {{fbdoc item="desc"}} **##Operator Mod## (Modulus)** divides two ##[[KeyPgInteger Integer]]## expressions and returns the remainder. Numeric values are converted to ##[[KeyPgInteger Integer]]## by rounding up or down. Neither of the operands are modified in any way. This operator can be overloaded for user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/mod.bas"}}%%(freebasic) PRINT 47 MOD 7 PRINT 5.6 MOD 2.1 PRINT 5.1 MOD 2.8 %% Output: %% 5 0 2 %% This is because: - 47 divided by 7 gives a remainder of 5 - 5.6 is rounded to 6 while 2.1 is rounded to 2. This makes the problem 6 MOD 2 which means 6 divided by 2 which gives a remainder of 0 - 5.1 is rounded to 5 while 2.8 is rounded to 3. This makes the problem 5 MOD 3 which means 5 divided by 3 which gives a remainder of 2 {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - [[CatPgMath Mathematical Functions]] {{fbdoc item="back" value="CatPgOpArithmetic|Arithmetic Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator * (Multiply)"}}---- Multiplies two numeric expressions {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] ***** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgByte byte]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgByte byte]] ) [[KeyPgAs as]] [[KeyPgByte byte]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] ***** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUbyte ubyte]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUbyte ubyte]] ) [[KeyPgAs as]] [[KeyPgUbyte ubyte]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] ***** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgShort short]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgShort short]] ) [[KeyPgAs as]] [[KeyPgShort short]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] ***** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUshort ushort]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUshort ushort]] ) [[KeyPgAs as]] [[KeyPgUshort ushort]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] ***** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] ***** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUinteger uinteger]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUinteger uinteger]] ) [[KeyPgAs as]] [[KeyPgUinteger uinteger]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] ***** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgLongint longint]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgLongint longint]] ) [[KeyPgAs as]] [[KeyPgLongint longint]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] ***** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUlongint ulongint]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUlongint ulongint]] ) [[KeyPgAs as]] [[KeyPgUlongint ulongint]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] ***** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgSingle single]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgSingle single]] ) [[KeyPgAs as]] [[KeyPgSingle single]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] ***** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgDouble double]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgDouble double]] ) [[KeyPgAs as]] [[KeyPgDouble double]] ## {{fbdoc item="usage"}}## //result// = //lhs// **##*##** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The left-hand side multiplicand expression. ##//rhs//## The right-hand side multiplicand expression. {{fbdoc item="ret"}} Returns the product of two multiplicands. {{fbdoc item="desc"}} **##Operator *## (Multiply)** returns the product of two multiplicands. Neither operand is modified in any way. This operator can be overloaded to accept user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/multiply.bas"}}%%(freebasic) DIM n AS DOUBLE n = 4 * 5 PRINT n SLEEP %% Output: %% 20 %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - [[CatPgMath Mathematical Functions]] {{fbdoc item="back" value="CatPgOpArithmetic|Arithmetic Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator - (Negate)"}}---- Changes the sign of a numeric expression {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **-** ( [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **-** ( [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgSingle single]] ) [[KeyPgAs as]] [[KeyPgSingle single]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **-** ( [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgDouble double]] ) [[KeyPgAs as]] [[KeyPgDouble double]] ## {{fbdoc item="usage"}}## //result// = **-** //rhs// ## {{fbdoc item="param"}} ##//rhs//## The right-hand side numeric expression to negate. {{fbdoc item="ret"}} Returns the negative of the expression. {{fbdoc item="desc"}} **##Operator -## (Negate)** is a unary operator that negates the value of its operand. The operand is not modified in any way. This operator can be overloaded for user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/negate.bas"}}%%(freebasic) DIM n AS LONGINT PRINT -5 n = 65432568459 n = - n PRINT n SLEEP %% Output: %% -5 -65432568459 %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - [[CatPgMath Mathematical Functions]] {{fbdoc item="back" value="CatPgOpArithmetic|Arithmetic Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator New"}}---- Operator to dynamically allocate memory and construct data of a specified type {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **new** ( //size// [[KeyPgAs as]] [[KeyPgUinteger uinteger]] ) [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **new[]** ( //size// [[KeyPgAs as]] [[KeyPgUinteger uinteger]] ) [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] ## {{fbdoc item="usage"}}## //result// = **New** //[[DataType datatype]]// //or// //result// = **New** //[[DataType datatype]]// ( //initializers//, ... ) //or// //result// = **New** //[[DataType datatype]]//**[** //count// **]** ## {{fbdoc item="param"}} ##//size//## number of bytes to allocate. ##//initializers//## Initial value(s) for the variable. ##//datatype//## name of the data type to create. ##//count//## Number of elements to allocate. {{fbdoc item="ret"}} A pointer of type [[DataType datatype]] to the newly allocated data. {{fbdoc item="desc"}} The ##**New**## operator dynamically allocates memory and constructs a specified data type. For simple types, like integers, an initial value can be given. For types without constructors, initial values can be specified for each field. Types that have constructors can have their constructors called by ##**New**## as well. If no initializers are given, the default values for those types will be set. ##**New[]**## is the array-version of the ##**New**## operator and allocates enough memory for the specified number of objects. The default constructor for the type will be used to set the initial values for each item. Objects created with ##**New**## must be freed with ##[[KeyPgOpDelete Delete]]##. Memory allocated with ##**New[]**## must be freed with ##**Delete[]**##, the array-version of ##[[KeyPgOpDelete Delete]]##. You cannot mix and match the different versions of the operators. Specifying an initial value of ##[[KeyPgAny Any]]##, as in ##new datatype(any)## will allocate memory for the type, but not initialize the data. This is only valid on data types that do not have constructors. Specifying an initial value of ##[[KeyPgAny Any]]##, as in ##new datatype[count]{any}## will allocate memory for the array, but not initialize the data. This is only valid on data types that do not have constructors. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/new.bas"}}%%(freebasic) type Rational as integer numerator, denominator end type scope ' Create and initialize a Rational, and store it's address. dim p as Rational ptr = new Rational(3, 4) print p->numerator & "/" & p->denominator ' Destroy the rational and give its memory back to the system. delete p end scope scope ' Allocate memory for 100 integers, store the address of the first one. dim p as integer ptr = new integer[100] ' Assign some values to the integers in the array. for i as integer = 0 to 99 p[i] = i next ' Free the entire integer array. delete[] p end scope %% {{fbdoc item="lang"}} - Only available in the //[[CompilerOptlang -lang fb]]// dialect. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgOpDelete Delete]]## - ##[[KeyPgOpPlacementNew Placement New]]## {{fbdoc item="back" value="CatPgOpMemory|Memory Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator Next (Iteration)"}}---- Determines if a ##[[KeyPgFornext For...Next]]## loop should be terminated {{fbdoc item="syntax"}}## { [[KeyPgType Type]] | [[KeyPgClass Class]] | [[KeyPgUnion Union]] } //typename// [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Next** ( [ [[KeyPgByref byref]] | [[KeyPgByval byval]] ] //cond// [[KeyPgAs as]] //typename// ) [[KeyPgAs as]] [[KeyPgInteger Integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Next** ( [ [[KeyPgByref byref]] | [[KeyPgByval byval]] ] //cond// [[KeyPgAs as]] //typename//, [ [[KeyPgByref byref]] | [[KeyPgByval byval]] ] //stp// [[KeyPgAs as]] //typename// ) [[KeyPgAs as]] [[KeyPgInteger Integer]] //...// End { [[KeyPgType Type]] | [[KeyPgClass Class]] | [[KeyPgUnion Union]] } ## {{fbdoc item="usage"}}## [[KeyPgFornext For]] //iterator// [ As //typename// ] = //start_value// To //end_value// [ [[KeyPgFornext Step]] //step_value// ] [// ...statements... //] [[KeyPgFornext Next]] ## {{fbdoc item="param"}} ##//typename//## name of the ##[[KeyPgType Type]]##, ##[[KeyPgClass Class]]##, or ##[[KeyPgUnion Union]]## ##//cond//##, ##//end_value//## a ##//typename//## object used as a loop-terminating value ##//stp//##, ##//step_value//## a ##//typename//## object used as an incremental value ##//iterator//## a ##//typename//## object used as an iterator ##//start_value//## a ##//typename//## object used to copy construct or assign to the iterator initially {{fbdoc item="desc"}} ##[[KeyPgOpFor Operator For]]##, ##**Operator Next**## and ##[[KeyPgOpStep Operator Step]]## can be overloaded in user-defined type definitions to allow objects of that type to be used as iterators and step values in ##[[KeyPgFornext For...Next]]## loops. ##**Operator Next**## is called every time the iterator needs to be checked against the end value. This happens immediately after the call to its ##[[KeyPgOpFor Operator For]]##, and immediately after any calls to its ##[[KeyPgOpStep Operator Step]]##. ##**Operator Next**## should return zero (0) if the loop should be terminated, or non-zero if the loop should continue iterating. The first time ##**Operator Next**## is called, no statements in the ##[[KeyPgFornext For...Next]]## body, if any, have been executed yet. The first version of ##**Operator Next**## is used if no step value is given in the ##[[KeyPgFornext For...Next]]## statement. If a step value is given, the second version is used and is passed the step value. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/udt/next.bas"}}%%(freebasic) '' Example Type Type T value As Double Declare Constructor( ByVal x As Double = 0 ) Declare Operator += ( ByVal x As Double ) Declare Operator For( ByRef stp As T ) Declare Operator Step( ByRef stp As T ) Declare Operator Next( ByRef cond As T, ByRef stp As T ) As Integer Declare Operator Cast() As String End Type Constructor T ( ByVal x As Double ) value = x End Constructor Operator <= ( ByRef lhs As T, ByRef rhs As T ) As Integer Operator = ( lhs.value <= rhs.value ) End Operator Operator >= ( ByRef lhs As T, ByRef rhs As T ) As Integer Operator = ( lhs.value >= rhs.value ) End Operator Operator T.+= ( ByVal x As Double ) value += x End Operator Operator T.for( ByRef stp As T ) End Operator Operator T.step( ByRef stp As T ) This += stp.value End Operator Operator T.next( ByRef cond As T, ByRef stp As T ) As Integer if( stp.value < 0 ) then Operator = ( This >= cond ) else Operator = ( This <= cond ) end if End Operator Operator T.cast() As String Operator = Str( value ) End Operator '' Example Usage For i As T = 10 To 1 step -1 Print i Next i %% {{fbdoc item="lang"}} - Only available in the //[[CompilerOptlang -lang fb]]// dialect. {{fbdoc item="see"}} - ##[[KeyPgOpFor Operator For]]## - ##[[KeyPgOpStep Operator Step]]## - ##[[KeyPgFornext For...Next]]## {{fbdoc item="back" value="CatPgOpIterating|Iterating Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator Not (Complement)"}}---- Returns the bitwise-not (complement) of a numeric value {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Not** ( [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgByte byte]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Not** ( [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUbyte ubyte]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Not** ( [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgSingle single]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Not** ( [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgDouble double]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Not** ( [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] //T// ) [[KeyPgAs as]] //T// ## {{fbdoc item="usage"}}## //result// = **Not** //rhs// ## {{fbdoc item="param"}} ##//rhs//## The right-hand side expression. ##//T//## Any numeric type. {{fbdoc item="ret"}} Returns the bitwise-complement of its operand. {{fbdoc item="desc"}} This operator returns the bitwise-complement of its operand, a logical operation that results in a value with bits set depending on the bits of the operand. The truth table below demonstrates all combinations of a boolean-complement operation: {{table columns="2" cellpadding="2" cells="Rhs Bit;Result;0;1;1;0"}} This operator can be overloaded for user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/not-bitwise.bas"}}%%(freebasic) ' Using the NOT operator on a numeric value DIM numeric_value AS BYTE numeric_value = 15 '00001111 'Result = -16 = 11110000 PRINT NOT numeric_value %% {{fbdoc item="filename" value="examples/manual/operator/not-logical.bas"}}%%(freebasic) ' Using the NOT operator on conditional expressions DIM AS UBYTE numeric_value1, numeric_value2 numeric_value1 = 15 numeric_value2 = 25 IF NOT numeric_value1 = 10 THEN PRINT "Numeric_Value1 is not equal to 10" IF NOT numeric_value2 = 25 THEN PRINT "Numeric_Value2 is not equal to 25" ' This will output "Numeric_Value1 is not equal to 10" because ' the first IF statement is false. ' It will not output the result of the second IF statement because the ' condition is true. %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - [[TblTruth Operator Truth Tables]] {{fbdoc item="back" value="CatPgOpLogical|Logical Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator <> (Not equal)"}}---- Compares two expressions for inequality {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<>** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgByte byte]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgByte byte]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<>** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUbyte ubyte]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUbyte ubyte]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<>** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgShort short]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgShort short]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<>** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUshort ushort]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUshort ushort]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<>** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<>** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUinteger uinteger]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUinteger uinteger]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<>** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgLongint longint]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgLongint longint]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<>** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUlongint ulongint]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUlongint ulongint]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<>** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgString string]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<>** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgZstring zstring]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgZstring zstring]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<>** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgWstring wstring]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgWstring wstring]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **<>** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] //T//, [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] //T// ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = //lhs// **<>** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The left-hand side expression to compare to. ##//rhs//## The right-hand side expression to compare to. ##//T//## Any pointer type. {{fbdoc item="ret"}} Returns negative one (-1) if expressions are not equal, or zero (0) if equal. {{fbdoc item="desc"}} **##Operator <>## (Not equal)** is a binary operator that compares two expressions for inequality and returns the result - a boolean value in the form of an ##[[KeyPgInteger Integer]]##: negative one (-1) for true and zero (0) for false. The arguments are not modified in any way. This operator can be overloaded to accept user-defined types as well. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/not-equal.bas"}}%%(freebasic) Dim As String a = "hello", b = "world" Dim As Integer i = 10, j = i If (a <> b) Then Print a & " does not equal " & b End If If (i <> j) Then Print "error: " & i & " does not equal " & j End If %% ##[[KeyPgOpEqual Operator =]]## (Equal) is complement to **##Operator <>## (Not equal)**, and is functionally identical when combined with ##[[KeyPgOpNot Operator Not]]## (Bit-wise Complement). {{fbdoc item="filename" value="examples/manual/operator/not-equal2.bas"}}%%(freebasic) if (69 <> 420) then print "(420 <> 420) is true." if not (69 = 420) then print "not (69 = 420) is true." %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - none {{fbdoc item="see"}} - ##[[KeyPgOpEqual Operator =]]## (Equal) {{fbdoc item="back" value="CatPgOpConditional|Relational Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator OR (Inclusive Disjunction)"}}---- Returns the bitwise-or (inclusive disjunction) of two numeric values {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Or** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] //T1//, [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] //T2// ) [[KeyPgAs as]] //Ret// ## {{fbdoc item="usage"}}## //result// = //lhs// **Or** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The left-hand side expression. ##//T1//## Any numeric type. ##//rhs//## The right-hand side expression. ##//T2//## Any numeric type. ##//Ret//## A numeric type (varies with ##//T1//## and ##//T2//##). {{fbdoc item="ret"}} Returns the bitwise-disjunction of the two operands. {{fbdoc item="desc"}} This operator returns the bitwise-disjunction of its operands, a logical operation that results in a value with bits set depending on the bits of the operands. The truth table below demonstrates all combinations of a boolean-disjunction operation: {{table columns="3" cellpadding="2" cells="Lhs Bit;Rhs Bit;Result;0;0;0;1;0;1;0;1;1;1;1;1"}} No short-circuiting is performed - both expressions are always evaluated. The return type depends on the types of values passed. ##[[KeyPgByte Byte]]##, ##[[KeyPgUbyte Ubyte]]## and floating-point type values are first converted to ##[[KeyPgInteger Integer]]##. If the left and right-hand side types differ only in signedness, then the return type is the same as the left-hand side type (##//T1//##), otherwise, the larger of the two types is returned. This operator can be overloaded for user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/or-bitwise.bas"}}%%(freebasic) ' Using the OR operator on two numeric values DIM AS UBYTE numeric_value1, numeric_value2 numeric_value1 = 15 '00001111 numeric_value2 = 30 '00011110 'Result = 31 = 00011111 PRINT numeric_value1 OR numeric_value2 SLEEP %% {{fbdoc item="filename" value="examples/manual/operator/or-logical.bas"}}%%(freebasic) ' Using the OR operator on two conditional expressions Dim As UByte numeric_value numeric_value = 10 IF numeric_value = 5 OR numeric_value = 10 Then Print "Numeric_Value equals 5 or 10" SLEEP ' This will output "Numeric_Value equals 5 or 10" because ' while the first condition of the first IF statement is false, the second is true %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - [[TblTruth Operator Truth Tables]] {{fbdoc item="back" value="CatPgOpLogical|Logical Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator Placement New"}}---- Operator to construct an object at a specified memory address. {{fbdoc item="syntax"}}## //result// = **New(//address//)** //[[DataType datatype]]// //or// //result// = **New(//address//)** //[[DataType datatype]]// ( //initializers//, ... ) //or// //result// = **New(//address//)** //[[DataType datatype]]//**[** //count// **]** ## {{fbdoc item="param"}} ##//address//## the location in memory to construct. the parenthesis are **not** optional. ##//size//## number of bytes to allocate. ##//initializers//## Initial value(s) for the variable. ##//datatype//## name of the data type to create. ##//count//## Number of elements to allocate. {{fbdoc item="ret"}} A pointer of type [[DataType datatype]] to the newly allocated data. {{fbdoc item="desc"}} The ##**Placement New**## operator constructs a specified data type at the specified memory location. For simple types, like integers, an initial value can be given. For types without constructors, initial values can be specified for each field. Types that have constructors can have their constructors called by ##**Placement New**## as well. If no initializers are given, the default values for those types will be set. Memory is **not** allocated when using the ##**Placement New**## operator. Instead, the memory at the specified ##//address//## is used. It is incorrect to call ##[[KeyPgOpDelete Delete]]## on the address. See examples below for proper //placement new// usage. Specifying an initial value of ##[[KeyPgAny Any]]##, as in ##new(address) datatype(any)## will not initialize the data. This is only valid on data types that do not have constructors. Specifying an initial value of ##[[KeyPgAny Any]]##, as in ##new(address) datatype[count]{any}## will not initialize the data. This is only valid on data types that do not have constructors. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/placement_new.bas"}}%%(freebasic) '' "placement new" example type Rational as integer numerator, denominator end type scope '' allocate some memory to construct as a Rational dim as any ptr ap = callocate(len(Rational)) '' make the placement new call dim as Rational ptr r = new (ap) Rational( 3, 4 ) '' you can see, the addresses are the same, just having different types in the compiler print ap, r '' confirm all is okay print r->numerator & "/" & r->denominator '' destroying must be done explicitly, because delete will automatically free the memory '' and that isn't always okay when using placement new. ALWAYS explicitly call the destructor. r->destructor( ) '' we explicitly allocated, so we explicitly deallocate deallocate( ap ) end scope %% {{fbdoc item="lang"}} - Only available in the //[[CompilerOptlang -lang fb]]// dialect. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgOpDelete Delete]]## - ##[[KeyPgOpNew New]]## {{fbdoc item="back" value="CatPgOpMemory|Memory Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator ## (Preprocessor Concatenate)"}}---- Preprocessor operator to concatenate strings {{fbdoc item="syntax"}}## text**""##""**text ## {{fbdoc item="desc"}} This operator creates a new token by concatenating the texts at both sides of it. This text can be recognized by other macros and further expanded. One use, is to create a macro that expands to different macro names, variable names, and function names depending on the arguments received. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/prepro/concat.bas"}}%%(freebasic) #define Concat(t,n) t##n Print concat (12,34) Dim Concat (hello,world) as integer Concat (hello,world)=99 print helloworld %% Output: %% 1234 99 %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - [[CatPgPreProcess Preprocessor]] {{fbdoc item="back" value="CatPgOpPrepro|Preprocessor Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:55:59 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 0b014a9afb0e1676f09cdf4d952fe493 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 1919 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="Operator ! (Escaped String Literal)"}}---- Explicity indicates that a string literal should be processed for escape sequences. {{fbdoc item="syntax"}}## **!**"//text//" ## {{fbdoc item="param"}} ##**!**## The preprocessor escaped string operator ##"//text//"## The string literal containing escape characters {{fbdoc item="desc"}} This operator explicitly indicates that the string literal following it (wrapped in double quotes) should be processed for escape sequences. This a preprocessor operator and can only be used with string literals at compile time. The default behaviour for string literals is that they not be processed for escape sequences. ##[[KeyPgOptionescape Option Escape]]## can be used in the //[[CompilerOptlang -lang fblite]]// dialect to override this default behaviour causing all strings to be processed for escape sequences. Use the [[KeyPgOpPpNoescape $ operator (Non-Escaped String Literal)]] operator to explicitly indicate that a string should not be processed for escape sequences. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/prepro/escape.bas"}}%%(freebasic) print "Some escape sequence examples:" print !"1.\tsingle quote (\\\') : \'" print !"2.\tdouble quote (\\\") : \"" print !"3.\tbackslash (\\\\) : \\" print !"4.\tascii char (\\65): \65" '' OUTPUT: '' '' Some escape sequence examples: '' 1. single quote (\') : ' '' 2. double quote (\") : " '' 3. backslash (\\) : \ '' 4. ascii char (\65): A %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - [[KeyPgOpPpNoescape Operator $ (Non-Escaped String Literal)]] - ##[[KeyPgOptionescape Option Escape]]## - [[CatPgPreProcess Preprocessor]] - [[ProPgLiterals Literals]] - [[TblEscapeSequences Escape Sequences]] {{fbdoc item="back" value="CatPgOpPrepro|Preprocessor Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}} {{fbdoc item="title" value="Operator $ (Non-Escaped String Literal)"}}---- Explicity indicates that a string literal should not be processed for escape sequences. {{fbdoc item="syntax"}}## **$**"//text//" ## {{fbdoc item="param"}} ##**$**## The preprocessor non-escaped operator ##"//text//"## The string literal {{fbdoc item="desc"}} This operator explicitly indicates that the string literal following it (wrapped in double quotes) should not be processed for escape sequences. This a preprocessor operator and can only be used with string literals at compile time. The default behaviour for string literals is that they not be processed for escape sequences. However, ##[[KeyPgOptionescape Option Escape]]## in the //[[CompilerOptlang -lang fblite]]// dialect can be used to override this default behaviour causing all strings to be processed for escape sequences. Use the [[KeyPgOpPpEscape ! operator (Escaped String Literal)]] to explicitly indicate that a string should be processed for escape sequences. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/prepro/noescape.bas"}}%%(freebasic) '' Compile with -lang fblite or qb print "Default" print "Backslash : \\" print !"Backslash !: \\" print $"Backslash $: \\" print option escape print "Option Escape" print "Backslash : \\" print !"Backslash !: \\" print $"Backslash $: \\" print '' OUTPUT: '' Default '' Backslash : \\ '' Backslash !: \ '' Backslash $: \\ '' Option Escape '' Backslash : \ '' Backslash !: \ '' Backslash $: \\ %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - [[KeyPgOpPpEscape Operator ! (Escaped String Literal)]] - ##[[KeyPgOptionescape Option Escape]]## - [[CatPgPreProcess Preprocessor]] - [[ProPgLiterals Literals]] - [[TblEscapeSequences Escape Sequences]] {{fbdoc item="back" value="CatPgOpPrepro|Preprocessor Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator # (Preprocessor Stringize)"}}---- Preprocessor operator to convert macro arguments to strings {{fbdoc item="syntax"}}## **""#""**//macro_argument// ## {{fbdoc item="desc"}} This operator converts the ##//macro_argument//## into a string whose value is the name of the argument. This substitution is made during the macro expansion, previous to compilation. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/prepro/stringize.bas"}}%%(freebasic) #define SEE(x) print #x ;" = "; x dim variable as integer, another_one as integer variable=1 another_one=2 SEE(variable) SEE(another_one) %% Output: %% variable = 1 another_one = 2 %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - [[CatPgPreProcess Preprocessor]] {{fbdoc item="back" value="CatPgOpPrepro|Preprocessor Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator PROCPTR (Procedure pointer)"}}---- Returns the address of a procedure {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Procptr** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] //T// ) [[KeyPgAs as]] //T// [[KeyPgPtr ptr]] ## {{fbdoc item="usage"}}## //result// = **Procptr** ( //lhs// ) ## {{fbdoc item="param"}} ##//lhs//## A procedure. ##//T//## The type of procedure. {{fbdoc item="ret"}} Returns the address of the procedure. {{fbdoc item="desc"}} This operator returns the address of a ##[[KeyPgSub Sub]]## or ##[[KeyPgFunction Function]]## procedure. ##[[KeyPgOpAt Operator @ (Address of)]]##, when used with procedures, has identical behavior. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/procptr.bas"}}%%(freebasic) ' This example uses ProcPtr to demonstrate function pointers Declare Function Subtract( x as Integer, y as Integer) as Integer Declare Function Add( x as Integer, y as Integer) as Integer Dim myFunction as Function( x as Integer, y as Integer) as Integer ' myFunction will now be assigned to Add myFunction = Procptr( Add ) print myFunction(2, 3) ' myFunction will now be assigned to Subtract. Notice the different output. myFunction = Procptr( Subtract ) print myFunction(2, 3) Function Add( x as Integer, y as Integer) as Integer return x + y end function Function Subtract( x as Integer, y as Integer) as Integer return x - y end function %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Procptr""**##. {{fbdoc item="see"}} - ##[[KeyPgSub Sub]]## - ##[[KeyPgFunction Function]]## - [[ProPgPointers Pointers]] {{fbdoc item="back" value="CatPgOpPoint|Pointer Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator [] (Pointer index)"}}---- Returns a reference to memory offset from an address {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **[]** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] //T// [[KeyPgPointer pointer]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] //T// ## ~&//Note that **##Operator []## (Pointer index)** returns a reference. As of 02.27.07, ""FreeBASIC"" syntax does not support returning references. When it does, this syntax will need to be changed.// {{fbdoc item="usage"}}## //result// = //lhs// **[** //rhs// **]** ## {{fbdoc item="param"}} ##//lhs//## The base address. ##//rhs//## A signed offset from ##//lhs//##. ##//T//## Any data type. {{fbdoc item="desc"}} This operator returns a reference to a value some distance in memory from a base address. It is essentially shorthand for "##[[KeyPgOpValueOf *]](//lhs// [[KeyPgOpAdd +]] //rhs//)##"; both do exactly the same thing. Like pointer arithmetic, any type of ##[[KeyPgPointer POINTER]]## can be indexed except for an ##[[KeyPgAny ANY]]## ##[[KeyPgPointer POINTER]]##. Also, like pointer arithmetic, it is up to the user to make sure meaningful data is being accessed. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/pointer-index.bas"}}%%(freebasic) '' initialize a 5-element array dim array(4) as integer = { 0, 1, 2, 3, 4 } '' point to the first element dim p as integer ptr = @array(0) '' use pointer indexing to output array elements for index as integer = 0 to 4 print p[index] next %% Will give the output, %%0 1 2 3 4 %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgOpAdd Operator + (Add)]]## - ##[[KeyPgOpSubtract Operator - (Subtract)]]## - [[CatPgOpPoint Pointer Operators]] {{fbdoc item="back" value="CatPgOpIndexing|Indexing Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator -> (Pointer to member access)"}}---- Returns a reference to a member from a pointer to an object {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **->** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] //T// [[KeyPgPointer pointer]] ) [[KeyPgAs as]] //U// ## ~&//Note that **##Operator ->## (Pointer to member access)** returns a reference. As of 02.27.07, ""FreeBASIC"" syntax does not support returning references. When it does, this syntax will need to be changed.// {{fbdoc item="usage"}}## //result// = //lhs// **->** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The address of an object. ##//T//## A pointer to a user-defined type. ##//rhs//## The name of a member to access. ##//U//## The type that ##//rhs//## refers to. {{fbdoc item="ret"}} Returns a reference to the member specified by ##//rhs//##. {{fbdoc item="desc"}} **##Operator ->## (Pointer to member access)** returns a reference to a member of an object through a pointer to that object. It has the effect of dereferencing a pointer to an object, then using ##[[KeyPgOpMemberAccess Operator . (Member access)]]##. For example, ##"//p//**->**//member//"## is equivalent to ##"//x//.//member//"##, if //x// is an object of user-defined type and //p// is a pointer to an object of the same type. This operator can be overloaded for user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/udt/ptr-access.bas"}}%%(freebasic) Type rect x As Integer y As Integer End Type Dim r As rect Dim rp As rect Pointer = @r rp->x = 4 rp->y = 2 Print "x = " & rp->x & ", y = " & rp->y Sleep %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgOpMemberAccess Operator . (Member access)]]## - ##[[KeyPgOpAt Operator @ (Address of)]]## - ##[[KeyPgOpValueOf Operator * (Value of)]]## {{fbdoc item="back" value="CatPgOpTypeclass|Type or Class Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator Shl (Shift left)"}}---- Shifts the bits of a numeric expression to the left {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Shl** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Shl** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUinteger uinteger]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUinteger uinteger]] ) [[KeyPgAs as]] [[KeyPgUinteger uinteger]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Shl** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgLongint longint]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgLongint longint]] ) [[KeyPgAs as]] [[KeyPgLongint longint]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Shl** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUlongint ulongint]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUlongint ulongint]] ) [[KeyPgAs as]] [[KeyPgUlongint ulongint]] ## {{fbdoc item="usage"}}## //result// = //lhs// **Shl** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The left-hand side expression. ##//rhs//## The right-hand side shift expression. {{fbdoc item="ret"}} Returns the result of ##//lhs//## being shifted left ##//rhs//## number of times. {{fbdoc item="desc"}} **##Operator Shl## (Shift left)** shifts all of the bits in the left-hand side expression (##//lhs//##) left a number of times specified by the right-hand side expression (##//rhs//##). This has the effect of multiplying ##//lhs//## by two for each shift. For example, "##&b0101 **Shl** 1##" returns the binary number ##&b01010##, and "##5 **Shl** 1##" returns ##10##. Neither of the operands are modified in any way. This operator can be overloaded for user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/shift-left.bas"}}%%(freebasic) 'Double a number For i As Integer = 0 To 10 Print 5 Shl i, Bin(5 Shl i, 16) Next i %% Output: %% 5 0000000000000101 10 0000000000001010 20 0000000000010100 40 0000000000101000 80 0000000001010000 160 0000000010100000 320 0000000101000000 640 0000001010000000 1280 0000010100000000 2560 0000101000000000 5120 0001010000000000 %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Shl""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgOpCombineShiftLeft Operator Shl= (Shift Left and Assign)]]## - ##[[KeyPgOpShiftRight Operator Shr (Shift right)]]## - ##[[KeyPgBin Bin]]## - [[CatPgMath Mathematical Functions]] {{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator Shr (Shift right)"}}---- Shifts the bits of a numeric expression to the right {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Shr** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Shr** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUinteger uinteger]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUinteger uinteger]] ) [[KeyPgAs as]] [[KeyPgUinteger uinteger]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Shr** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgLongint longint]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgLongint longint]] ) [[KeyPgAs as]] [[KeyPgLongint longint]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Shr** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUlongint ulongint]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUlongint ulongint]] ) [[KeyPgAs as]] [[KeyPgUlongint ulongint]] ## {{fbdoc item="usage"}}## //result// = //lhs// **Shr** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The left-hand side expression. ##//rhs//## The right-hand side shift expression. {{fbdoc item="ret"}} Returns the result of ##//lhs//## being shifted right ##//rhs//## number of times. {{fbdoc item="desc"}} **##Operator Shr## (Shift right)** shifts all of the bits in the left-hand side expression (##//lhs//##) right a number of times specified by the right-hand side expression (##//rhs//##). This has the effect of dividing ##//lhs//## by two for each shift. For example, "##&b0101 **Shr** 1##" returns the binary number ##&b010##, and "##5 **Shr** 1##" returns ##2##. If the left-hand side expression is signed, the sign bit is copied in the newly created bits on the left after the shift. Neither of the operands are modified in any way. This operator can be overloaded for user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/shift-right.bas"}}%%(freebasic) 'Halve a number For i As Integer = 0 To 10 Print 1000 Shr i, Bin(1000 Shr i, 16) Next i %% Output: %% 1000 0000001111101000 500 0000000111110100 250 0000000011111010 125 0000000001111101 62 0000000000111110 31 0000000000011111 15 0000000000001111 7 0000000000000111 3 0000000000000011 1 0000000000000001 0 0000000000000000 %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Shr""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgOpCombineShiftRight Operator Shr= (Shift Right and Assign)]]## - ##[[KeyPgOpShiftLeft Operator Shl (Shift left)]]## - ##[[KeyPgBin Bin]]## - [[CatPgMath Mathematical Functions]] {{fbdoc item="back" value="CatPgOpArithmetic|Arithmetic Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator Step (Iteration)"}}---- Increments the iterator of a ##[[KeyPgFornext For...Next]]## loop {{fbdoc item="syntax"}}## { [[KeyPgType Type]] | [[KeyPgClass Class]] | [[KeyPgUnion Union]] } //typename// [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Step** () [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Step** ( [ [[KeyPgByref byref]] | [[KeyPgByval byval]] ] //stp// [[KeyPgAs as]] //typename// ) //...// End { [[KeyPgType Type]] | [[KeyPgClass Class]] | [[KeyPgUnion Union]] } ## {{fbdoc item="usage"}}## [[KeyPgFornext For]] //iterator// [ As //typename// ] = //start_value// To //end_value// [ [[KeyPgFornext Step]] //step_value// ] [// ...statements... //] [[KeyPgFornext Next]] ## {{fbdoc item="param"}} ##//typename//## name of the ##[[KeyPgType Type]]##, ##[[KeyPgClass Class]]##, or ##[[KeyPgUnion Union]]## ##//stp//##, ##//step_value//## a ##//typename//## object used as an incremental value ##//iterator//## a ##//typename//## object used as an iterator ##//end_value//## a ##//typename//## object used as a loop-terminating value ##//start_value//## a ##//typename//## object used to copy construct or assign to the iterator initially {{fbdoc item="desc"}} ##[[KeyPgOpFor Operator For]]##, ##[[KeyPgOpNext Operator Next]]## and ##**Operator Step**## can be overloaded in user-defined type definitions to allow objects of that type to be used as iterators and step values in ##[[KeyPgFornext For...Next]]## loops. ##**Operator Step**## is called to increment the iterator immediately after all statements in the ##[[KeyPgFornext For...Next]]## body are executed, if any. The first version of ##**Operator Step**## is used if no step value is given in the ##[[KeyPgFornext For...Next]]## statement. If a step value is given, the second version is used and is passed the step value. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/udt/step.bas"}}%%(freebasic) '' Example Type Type T value As Double Declare Constructor( ByVal x As Double = 0 ) Declare Operator += ( ByVal x As Double ) Declare Operator For( ByRef stp As T ) Declare Operator Step( ByRef stp As T ) Declare Operator Next( ByRef cond As T, ByRef stp As T ) As Integer Declare Operator Cast() As String End Type Constructor T ( ByVal x As Double ) value = x End Constructor Operator <= ( ByRef lhs As T, ByRef rhs As T ) As Integer Operator = ( lhs.value <= rhs.value ) End Operator Operator >= ( ByRef lhs As T, ByRef rhs As T ) As Integer Operator = ( lhs.value >= rhs.value ) End Operator Operator T.+= ( ByVal x As Double ) value += x End Operator Operator T.for( ByRef stp As T ) End Operator Operator T.step( ByRef stp As T ) This += stp.value End Operator Operator T.next( ByRef cond As T, ByRef stp As T ) As Integer if( stp.value < 0 ) then Operator = ( This >= cond ) else Operator = ( This <= cond ) end if End Operator Operator T.cast() As String Operator = Str( value ) End Operator '' Example Usage For i As T = 10 To 1 step -1 Print i Next i %% {{fbdoc item="lang"}} - Only available in the //[[CompilerOptlang -lang fb]]// dialect. {{fbdoc item="see"}} - ##[[KeyPgOpFor Operator For]]## - ##[[KeyPgOpNext Operator Next]]## - ##[[KeyPgFornext For...Next]]## {{fbdoc item="back" value="CatPgOpIterating|Iterating Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator [] (String index)"}}---- Returns a reference to a character in a string {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **[]** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgString string]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgUbyte ubyte]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **[]** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgZstring zstring]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgUbyte ubyte]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **[]** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgWstring wstring]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] //T// ## ~&//Note that **##Operator {}## (String index)** returns a reference. As of Feb 27 2007, ""FreeBASIC"" syntax does not support returning references. When it does, this syntax will need to be changed.// {{fbdoc item="usage"}}## //result// = //lhs// **[** //rhs// **]** ## {{fbdoc item="param"}} ##//lhs//## The string. ##//rhs//## A zero-based offset from the first character. ##//T//## The wide-character type (varies per platform). {{fbdoc item="desc"}} This operator returns a reference to a specific character in a string. The user must ensure that the index does not exceed the range "[0, ##[[KeyPgLen Len]](//lhs//) - 1##]". Outside this range, results are undefined. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/stringindex.bas"}}%%(freebasic) dim a as string = "Hello, world!" dim i as integer for i = 0 to len(a) - 1 print chr(a[i]); next i print %% Will print %% Hello, world! %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - [[CatPgOpString String Operators]] {{fbdoc item="back" value="CatPgOpIndexing|Indexing Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator STRPTR (String pointer)"}}---- Returns the address of a string's character data. {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Strptr** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgZstring zstring]] [[KeyPgPtr ptr]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Strptr** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgWstring wstring]] ) [[KeyPgAs as]] [[KeyPgZstring zstring]] [[KeyPgPtr ptr]] ## {{fbdoc item="usage"}}## //result// = **Strptr** ( //lhs// ) ## {{fbdoc item="param"}} ##//lhs//## A string. {{fbdoc item="ret"}} Returns a ##[[KeyPgZstring Zstring]] [[KeyPgPtr Ptr]]## to a string's character data. {{fbdoc item="desc"}} This operator returns a ##[[KeyPgZstring Zstring]] [[KeyPgPtr Ptr]]## that points to the beginning of a string's character data. ##**Operator Strptr**## is the proper method for acquiring the address of a string's character data. Note that when passed a ##[[KeyPgWstring Wstring]]##, ##**Operator Strptr**## still returns a ##[[KeyPgZstring Zstring]] [[KeyPgPtr Ptr]]##, which may not be the desired result. The related ##[[KeyPgOpVarptr Operator Varptr (Variable pointer)]]## and ##[[KeyPgOpAt Operator @ (Address of)]]##, when used with a ##[[KeyPgString String]]##, return the address of the internal string descriptor. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/strptr.bas"}}%%(freebasic) '' This example uses Strptr to demonstrate using pointers with strings Dim myString As String Dim toMyStringDesc as any ptr Dim toMyString As ZString Ptr '' Note that using standard VARPTR notation will return a pointer to the '' descriptor, not the string data itself myString = "Improper method for Strings" toMyStringDesc = @myString Print myString Print hex( toMyStringDesc ) Print '' However, using Strptr returns the proper pointer myString = "Hello World Examples Are Silly" toMyString = StrPtr(myString) Print myString Print *toMyString Print '' And the pointer acts like pointers to other types myString = "MyString has now changed" Print myString Print *toMyString Print %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - [[ProPgPointers Pointers]] {{fbdoc item="back" value="CatPgOpPoint|Pointer Operators"}}{{fbdoc item="back" value="CatPgOpString|String Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator - (Subtract)"}}---- Subtracts two expressions {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **-** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgByte byte]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgByte byte]] ) [[KeyPgAs as]] [[KeyPgByte byte]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **-** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUbyte ubyte]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUbyte ubyte]] ) [[KeyPgAs as]] [[KeyPgUbyte ubyte]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **-** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgShort short]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgShort short]] ) [[KeyPgAs as]] [[KeyPgShort short]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **-** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUshort ushort]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUshort ushort]] ) [[KeyPgAs as]] [[KeyPgUshort ushort]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **-** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **-** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUinteger uinteger]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUinteger uinteger]] ) [[KeyPgAs as]] [[KeyPgUinteger uinteger]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **-** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgLongint longint]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgLongint longint]] ) [[KeyPgAs as]] [[KeyPgLongint longint]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **-** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgUlongint ulongint]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgUlongint ulongint]] ) [[KeyPgAs as]] [[KeyPgUlongint ulongint]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **-** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgSingle single]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgSingle single]] ) [[KeyPgAs as]] [[KeyPgSingle single]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **-** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgDouble double]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgDouble double]] ) [[KeyPgAs as]] [[KeyPgDouble double]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **-** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] //T//, [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] //T// ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **-** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] //T//, [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] //T// [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **-** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] //T// ) [[KeyPgAs as]] //T// ## {{fbdoc item="usage"}}## //result// = //lhs// **##-##** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The left-hand side expression to subtract from. ##//rhs//## The right-hand side expression to subtract. ##//T//## Any pointer type. {{fbdoc item="ret"}} Returns the subtraction of two expressions. {{fbdoc item="desc"}} When the left and right-hand side expressions are numeric values, **##Operator -## (Subtract)** returns the subtraction of the two values. If either the left or right-hand side expressions is of [[KeyPgPointer Pointer]] type, **##Operator -## (Subtract)** performs pointer arithmetic on the address, returning the result. Neither operand is modified in any way. This operator can be overloaded to accept user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/subtract.bas"}}%%(freebasic) DIM n AS SINGLE n = 4 - 5 PRINT n SLEEP %% will produce the output: %% -1 %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - [[CatPgMath Mathematical Functions]] {{fbdoc item="back" value="CatPgOpArithmetic|Arithmetic Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="OPTION BASE"}}---- Specifies a default lower bound for array declarations {{fbdoc item="syntax"}}## **Option Base** //base_subscript// ## {{fbdoc item="param"}} ##//base_subscript//## an numeric literal value {{fbdoc item="desc"}} ##**Option Base**## is a statement that sets the default lower bound for any following array declarations. This default remains in effect for the rest of the module in which ##**Option Base**## is used, and can be overridden by declaring arrays with an explicit lower bound, or with another ##**Option Base**## statement. Note: initially, the default base is ##0##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/check/KeyPgOptionbase_1.bas"}}%%(freebasic) '' Compile with the "-lang qb" or "-lang fblite" compiler switches dim foo(10) as integer ' declares an array with indices 0-10 option base 5 dim bar(15) as integer ' declares an array with indices 5-15 dim baz(0 to 4) as integer ' declares an array with indices 0-4 %% {{fbdoc item="lang"}} - Only available in the //[[CompilerOptlang -lang fblite]]// and //[[CompilerOptlang -lang qb]]// dialects. - In //[[CompilerOptlang -lang fb]]//, ##**Option Base**## is not allowed, and the default lower bound is always ##0##. {{fbdoc item="diff"}} - QBASIC only supported values of ##0## or ##1## for ##//base_subscript//##. - In QBASIC the word ##**Base**## was a reserved keyword, and couldn't be used as a variable name. - Arrays must always be explicitly created in ""FreeBASIC"". QBASIC would implicitly create an array from ##//base_subscript//## to ##10## if one was used in code without being predefined. {{fbdoc item="see"}} - ##[[KeyPgDim Dim]]## - ##[[KeyPgRedim Redim]]## - ##[[KeyPgLbound LBound]]## {{fbdoc item="back" value="CatPgCompilerSwitches|Compiler Switches"}}{{fbdoc item="title" value="OPTION BYVAL"}}---- Specifies parameters are to be passed by value by default in procedure declarations {{fbdoc item="syntax"}}## **Option Byval** ## {{fbdoc item="desc"}} ##**Option Byval**## is a statement that sets the default passing convention for procedure parameters to //by value//, as if declared with ##[[KeyPgByval Byval]]##. This default remains in effect for the rest of the module in which ##**Option Byval**## is used, and can be overridden by specifying ##[[KeyPgByref Byref]]## in parameter lists. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/switches/option-byval.bas"}}%%(freebasic) '' compile with the "-lang fblite" compiler switch sub TestDefaultByref( a as integer ) '' change the value a = a * 2 end sub option byval sub TestDefaultByval( a as integer ) a = a * 2 end sub dim a as integer = 1 print "a = "; a TestDefaultByref( a ) print "After TestDefaultByref : a = "; a print print "a = "; a TestDefaultByval( a ) print "After TestDefaultByval : a = "; a print %% {{fbdoc item="lang"}} - Only available in the //[[CompilerOptlang -lang fblite]]// and //[[CompilerOptlang -lang qb]]// dialects. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDdfboptionbyval __FB_OPTION_BYVAL__]]## {{fbdoc item="back" value="CatPgCompilerSwitches|Compiler Switches"}}{{fbdoc item="title" value="OPTION DYNAMIC"}}---- Specifies variable-length array declarations {{fbdoc item="syntax"}}## **Option Dynamic** ## {{fbdoc item="desc"}} ##**Option Dynamic**## is a statement that specifies that any following array declarations are variable-length, whether they are declared with constant subscript ranges or not. This remains in effect for the rest of the module in which ##**Option Dynamic**## is used, and can be overridden with ##[[KeyPgOptionstatic Option Static]]##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/switches/option-dynamic.bas"}}%%(freebasic) '' Compile with "-lang fblite" compiler switch dim foo(99) as integer ' declares a fixed-length array option dynamic dim bar(99) as integer ' declares a variable-length array ' ... redim bar(199) as integer ' resize the array %% {{fbdoc item="lang"}} - Only available in the //[[CompilerOptlang -lang fblite]]// and //[[CompilerOptlang -lang qb]]// dialects. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDdfboptiondynamic __FB_OPTION_DYNAMIC__]]## - [[KeyPgMetaDynamic $Dynamic]] - ##[[KeyPgOptionstatic Option Static]]## - ##[[KeyPgDim Dim]]## - ##[[KeyPgRedim Redim]]## {{fbdoc item="back" value="CatPgArray|Array Functions"}}{{fbdoc item="back" value="CatPgCompilerSwitches|Compiler Switches"}}{{fbdoc item="back" value="CatPgPreProcess|Preprocessor"}}{{fbdoc item="title" value="OPTION ESCAPE"}}---- Specifies that string literals should be processed for C-like escape sequences by default {{fbdoc item="syntax"}}## **Option Escape** ## {{fbdoc item="desc"}} ##**Option Escape**## is a statement that causes string literals to be processed for C-like escape sequences by default. Normally, escape sequences have no effect in string literals unless the string is prefixed with the [[KeyPgOpPpEscape ! operator (Escaped String Literal)]]. This default remains in effect for the rest of the module in which ##**Option Escape**## is used, and can be overridden by prefixing string literals with the [[KeyPgOpPpNoescape $ operator (Non-Escaped String Literal)]]. See [[ProPgLiterals Literals]] in the Programmer's Guide to learn more about escape sequences. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/switches/option-escape.bas"}}%%(freebasic) '' Compile with the "-lang fblite" compiler switch option escape print "Warning \a\t The path is:\r\n c:\\Freebasic\\Examples" print $"This string doesn't have expanded escape sequences: \r\n\t" #include "crt.bi" dim as integer a = 2, b = 3 printf("%d * %d = %d\r\n", a, b, a * b) %% {{fbdoc item="lang"}} - Only available in the //[[CompilerOptlang -lang fblite]]// and //[[CompilerOptlang -lang qb]]// dialects. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDdfboptionescape __FB_OPTION_ESCAPE__]]## - [[KeyPgOpPpEscape Operator ! (Escaped String Literal)]] - [[KeyPgOpPpNoescape Operator $ (Non-Escaped String Literal)]] - [[ProPgLiterals Literals]] {{fbdoc item="back" value="CatPgCompilerSwitches|Compiler Switches"}} {{fbdoc item="title" value="OPTION EXPLICIT"}}---- Forces variables, objects and arrays to be declared before they are used {{fbdoc item="syntax"}}## **Option Explicit** ## {{fbdoc item="desc"}} ##**Option Explicit**## is a statement that forces any following variable, object or array usage to be preceded by a declaration, with, for example, ##[[KeyPgDim Dim]]## or ##[[KeyPgStatic Static]]##. This rule remains in effect for the rest of the module in which ##**Option Explicit**## is used, and cannot be overridden. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/switches/option-explicit.bas"}}%%(freebasic) '' Compile with the "-lang qb" or "-lang fblite" compiler switches option explicit dim a as integer ' 'a' must be declared.. a = 1 ' ..or this statement will fail to compile. %% {{fbdoc item="lang"}} - Only available in the //[[CompilerOptlang -lang fblite]]// and //[[CompilerOptlang -lang qb]]// dialects. {{fbdoc item="diff"}} -New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDdfboptionexplicit __FB_OPTION_EXPLICIT__]]## {{fbdoc item="back" value="CatPgCompilerSwitches|Compiler Switches"}}{{fbdoc item="title" value="OPTION GOSUB"}}---- Enables support for ##[[KeyPgGosub Gosub]]## and ##[[KeyPgOngosub On Gosub]]##. {{fbdoc item="syntax"}}## **Option Gosub** ## {{fbdoc item="desc"}} ##**Option Gosub**## enables support for ##[[KeyPgGosub Gosub]]## and ##[[KeyPgReturn Return]]## (from gosub). Because ##[[KeyPgReturn Return]]## could mean return-from-gosub or return-from-procedure, ##**Option Gosub**## and ##[[KeyPgOptionnogosub Option Nogosub]]## can be used to enable and disable ##[[KeyPgGosub Gosub]]## support. When ##[[KeyPgGosub Gosub]]## support is disabled, ##[[KeyPgReturn Return]]## is then recognized as return-from-procedure. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/switches/option-gosub.bas"}}%%(freebasic) '' Compile with the "-lang fblite" compiler switch '' turn on gosub support option gosub gosub there backagain: print "backagain" end there: print "there" return %% {{fbdoc item="lang"}} - Only available in the //[[CompilerOptlang -lang fblite]]// and //[[CompilerOptlang -lang qb]]// dialects. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDdfboptiongosub __FB_OPTION_GOSUB__]]## - ##[[KeyPgOptionnogosub Option Nogosub]]## - ##[[KeyPgGosub Gosub]]## - ##[[KeyPgReturn Return]]## {{fbdoc item="back" value="CatPgCompilerSwitches|Compiler Switches"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:56:15 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 6fc4c43a8058995fb146664cd8dd9c84 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 1354 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="OPTION NOGOSUB"}}---- Disables support for ##[[KeyPgGosub Gosub]]## and ##[[KeyPgOngosub On Gosub]]##. {{fbdoc item="syntax"}}## **Option Nogosub** ## {{fbdoc item="desc"}} ##**Option Nogosub**## disables support for ##[[KeyPgGosub Gosub]]## and ##[[KeyPgReturn Return]]## (from gosub). Because ##[[KeyPgReturn Return]]## could mean return-from-gosub or return-from-procedure, ##[[KeyPgOptiongosub Option Gosub]]## and ##**Option Nogosub**## can be used to enable and disable ##[[KeyPgGosub Gosub]]## support. When ##[[KeyPgGosub Gosub]]## support is disabled, ##[[KeyPgReturn Return]]## is then recognized as return-from-procedure. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/switches/option-nogosub.bas"}}%%(freebasic) '' Compile with the "-lang qb" compiler switch '' turn off gosub support option nogosub function foo() as integer return 1234 end function print foo %% {{fbdoc item="lang"}} - Only available in the //[[CompilerOptlang -lang fblite]]// and //[[CompilerOptlang -lang qb]]// dialects. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDdfboptiongosub __FB_OPTION_GOSUB__]]## - ##[[KeyPgOptiongosub Option Gosub]]## - ##[[KeyPgGosub Gosub]]## - ##[[KeyPgReturn Return]]## {{fbdoc item="back" value="CatPgCompilerSwitches|Compiler Switches"}} {{fbdoc item="title" value="OPTION NOKEYWORD"}}---- "Undefines" a reserved keyword {{fbdoc item="syntax"}}## **Option Nokeyword** //keyword// ## {{fbdoc item="param"}} ##//keyword//## the keyword to undefine {{fbdoc item="desc"}} ##**Option Nokeyword**## is a statement that undefines a ""FreeBASIC"" reserved keyword, meaning it can be used as an identifier for a variable, object, procedure or any other symbol. The keyword is undefined for the rest of the module in which ##**Option Nokeyword**## is used. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/switches/option-nokeyword.bas"}}%%(freebasic) '' Compile with the "-lang fblite" compiler switch option nokeyword int ' remove the keyword 'int' from the internal ' symbol table dim int as integer ' declare a variable with the name 'int' %% {{fbdoc item="lang"}} - Only available in the //[[CompilerOptlang -lang fblite]]// and //[[CompilerOptlang -lang qb]]// dialects. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgPpundef #undef]]## {{fbdoc item="back" value="CatPgCompilerSwitches|Compiler Switches"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:56:24 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: a9ac9b26df1deb836bf14564a627dade Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 1255 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="OPTION PRIVATE"}}---- Specifies internal linkage by default for procedure declarations {{fbdoc item="syntax"}}## **Option Private** ## {{fbdoc item="desc"}} ##**Option Private**## is a statement that gives any following procedure declarations internal linkage by default, as if declared with ##[[KeyPgPrivate Private]]##. This default remains in effect for the rest of the module in which ##**Option Private**## is used, and can be overridden by declaring procedures with ##[[KeyPgPublic Public]]##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/switches/option-private.bas"}}%%(freebasic) '' Compile with the "-lang fblite" compiler switch sub ProcWithExternalLinkage() ' ... end sub option private sub ProcWithInternalLinkage() ' ... end sub public sub AnotherProcWithExternalLinkage() ' ... end sub %% {{fbdoc item="lang"}} - Only available in the //[[CompilerOptlang -lang fblite]]// and //[[CompilerOptlang -lang qb]]// dialects. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDdfboptionprivate __FB_OPTION_PRIVATE__]]## - ##[[KeyPgPrivate Private]]## - ##[[KeyPgPublic Public]]## {{fbdoc item="back" value="CatPgCompilerSwitches|Compiler Switches"}} {{fbdoc item="title" value="OPTION STATIC"}}---- Reverts to default array declaration behavior {{fbdoc item="syntax"}}## **Option Static** ## {{fbdoc item="desc"}} ##**Option Static**## is a statement that overrides the behavior of ##[[KeyPgOptiondynamic Option Dynamic]]##, that is, arrays declared with constant subscript ranges are fixed-length. This remains in effect for the rest of the module in which ##**Option Static**## is used, and can be overridden with ##[[KeyPgOptiondynamic Option Dynamic]]##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/switches/option-static.bas"}}%%(freebasic) '' Compile with the "-lang fblite" compiler switch option dynamic dim foo(100) as integer ' declares a variable-length array option static dim bar(100) as integer ' declares a fixed-length array %% {{fbdoc item="lang"}} - Only available in the //[[CompilerOptlang -lang fblite]]// and //[[CompilerOptlang -lang qb]]// dialects. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgMetaDynamic $Dynamic]]## - ##[[KeyPgDim Dim]]## - ##[[KeyPgErase Erase]]## - ##[[KeyPgRedim Redim]]## - ##[[KeyPgOptiondynamic Option Dynamic]]## {{fbdoc item="back" value="CatPgArray|Array Functions"}}{{fbdoc item="back" value="CatPgCompilerSwitches|Compiler Switches"}}{{fbdoc item="back" value="CatPgPreProcess|Preprocessor"}}{{fbdoc item="title" value="Operator * (Value of)"}}---- Dereferences a pointer {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] ***** ( [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] //T// [[KeyPgPointer pointer]] ) [[KeyPgAs as]] //T// ## ~&//Note that **##Operator *## (Value of)** returns a reference. As of 02.27.07, ""FreeBASIC"" syntax does not support returning references. When it does, this syntax will need to be changed.// {{fbdoc item="usage"}}## //result// = * //rhs// ## {{fbdoc item="param"}} ##//rhs//## The address to dereference. ##//T//## Any [[CatPgStdDataTypes standard]], [[CatPgUserDefTypes user-defined]] or procedure type. {{fbdoc item="ret"}} Returns a reference to the value stored at the address ##//rhs//##. {{fbdoc item="desc"}} **##Operator *## (Value of)** returns a reference to the value stored at an address, and is often called the dereference operator. The operand is not modified in any way. As a reference, the result of this operator can be used on the left-hand side of assignments. This operator can be overloaded for user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/valueof.bas"}}%%(freebasic) 'This program demonstrates the use of * to utilize the value a pointer points to. Dim a As Integer Dim pa As Integer Ptr pa=@a 'Here, we use the @ operator to point our integer ptr at 'a'. ' 'a' is, in this case, a standard integer variable. a=9 'Here we give 'a' a value of 9. Print "The value of 'a' is";*pa 'Here, we display the value of 'a' using a pointer. *pa = 1 'Here we use our pointer to change the value of 'a' Print "The new value of 'a' is";a 'Here we display the new value of 'a'. %% Output: %% The value of 'a' is 9 The new value of 'a' is 1 %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgOpAt Operator @ (Address of)]]## - [[ProPgPointers Pointers]] {{fbdoc item="back" value="CatPgOpPoint|Pointer Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator VARPTR (Variable pointer)"}}---- Returns the address of a variable or object {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Varptr** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] //T// ) [[KeyPgAs as]] //T// [[KeyPgPtr ptr]] ## {{fbdoc item="syntax"}}## //result// = **Varptr** ( //lhs// ) ## {{fbdoc item="param"}} ##//lhs//## A variable or object. ##//T//## Any data type. {{fbdoc item="ret"}} Returns the address of a variable or object. {{fbdoc item="desc"}} This operator returns the address of its operand. When the operand is of type ##[[KeyPgString String]]##, the address of the internal string descriptor is returned. Use ##[[KeyPgOpStrptr Operator Strptr (String pointer)]]## to retrieve the address of the string data. The operand cannot be an array, but may be an array element. For example, ##"**Varptr**(myarray(0))"## returns the address of ##"myarray(0)"##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/varptr.bas"}}%%(freebasic) Dim a As Integer, addr As Integer a = 10 '' place the address of a in addr addr = Cint( VarPtr(a) ) '' change all 4 bytes (size of INTEGER) of a Poke Integer, addr, -1000 Print a '' place the address of a in addr (same as above) addr = Cint( @a ) '' print the least or most significant byte, depending on the CPU endianess Print Peek( addr ) %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - [[ProPgPointers Pointers]] - ##[[KeyPgPoke Peek]]## - ##[[KeyPgPoke Poke]]## {{fbdoc item="back" value="CatPgOpPoint|Pointer Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="Operator XOR (Exclusive Disjunction)"}}---- Returns the bitwise-xor (exclusive disjunction) of two numeric values {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgOperator operator]] **Xor** ( [[KeyPgByref byref]] //lhs// [[KeyPgAs as]] //T1//, [[KeyPgByref byref]] //rhs// [[KeyPgAs as]] //T2// ) [[KeyPgAs as]] //Ret// ## {{fbdoc item="usage"}}## //result// = //lhs// **Xor** //rhs// ## {{fbdoc item="param"}} ##//lhs//## The left-hand side expression. ##//T1//## Any numeric type. ##//rhs//## The right-hand side expression. ##//T2//## Any numeric type. ##//Ret//## A numeric type (varies with ##//T1//## and ##//T2//##). {{fbdoc item="ret"}} Returns the bitwise-xor of the two operands. {{fbdoc item="desc"}} This operator returns the bitwise-exclusion of its operands, a logical operation that results in a value with bits set depending on the bits of the operands. The truth table below demonstrates all combinations of a boolean-exclusion operation: {{table columns="3" cellpadding="2" cells="Lhs Bit;Rhs Bit;Result;0;0;0;1;0;1;0;1;1;1;1;0"}} No short-circuiting is performed - both expressions are always evaluated. The return type depends on the types of values passed. ##[[KeyPgByte Byte]]##, ##[[KeyPgUbyte Ubyte]]## and floating-point type values are first converted to ##[[KeyPgInteger Integer]]##. If the left and right-hand side types differ only in signedness, then the return type is the same as the left-hand side type (##//T1//##), otherwise, the larger of the two types is returned. This operator can be overloaded for user-defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/operator/xor-bitwise.bas"}}%%(freebasic) ' Using the XOR operator on two numeric values DIM AS UBYTE numeric_value1, numeric_value2 numeric_value1 = 15 '00001111 numeric_value2 = 30 '00011110 'Result = 17 = 00010001 PRINT numeric_value1 XOR numeric_value2 SLEEP %% {{fbdoc item="filename" value="examples/manual/operator/xor-logical.bas"}}%%(freebasic) ' Using the XOR operator on two conditional expressions Dim As UByte numeric_value1, numeric_value2 numeric_value1 = 10 numeric_value2 = 15 IF numeric_value1 = 10 XOR numeric_value2 = 20 Then Print "Numeric_Value1 equals 10 or Numeric_Value2 equals 20" SLEEP ' This will output "Numeric_Value1 equals 10 or Numeric_Value2 equals 20" ' because only the first condition of the IF statement is true %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - [[TblTruth Operator Truth Tables]] {{fbdoc item="back" value="CatPgOpLogical|Logical Operators"}}{{fbdoc item="back" value="CatPgOperators|Operators"}}{{fbdoc item="title" value="OR"}}---- Parameter to the ##[[KeyPgPutgraphics Put]]## graphics statement which uses a bit-wise ##[[KeyPgOpOr Or]]## as the blitting method {{fbdoc item="syntax"}}## **Put** [ //target//, ] [ STEP ] ( //x//,//y// ), //source// [ ,( //x1//,//y1// )-( //x2//,//y2// ) ], **Or** ## {{fbdoc item="param"}} ##**Or**## Required. {{fbdoc item="desc"}} The ##**Or**## method combines each source pixel with the corresponding destination pixel, using the bit-wise ##[[KeyPgOpOr Or]]## function. The result of this is output as the destination pixel. This method works in all graphics modes. There is no mask color, although color values of ##0## (##[[KeyPgRgba RGBA]](0, 0, 0, 0)## in full-color modes) will have no effect, because of the behavior of ##[[KeyPgOpOr Or]]##. In full-color modes, each component (red, green, blue and alpha) is kept in a discrete set of bits, so the operation can be made to only affect some of the channels, by making sure the all the values of the other channels are set to ##0##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/put-or.bas"}}%%(freebasic) ''open a graphics window ScreenRes 320, 200, 16 ''create 3 sprites containing red, green and blue circles Const As Integer r = 32 dim as any ptr cr, cg, cb cr = ImageCreate(r * 2 + 1, r * 2 + 1, RGBA(0, 0, 0, 0)) cg = ImageCreate(r * 2 + 1, r * 2 + 1, RGBA(0, 0, 0, 0)) cb = ImageCreate(r * 2 + 1, r * 2 + 1, RGBA(0, 0, 0, 0)) Circle cr, (r, r), r, RGB(255, 0, 0), , , 1, f Circle cg, (r, r), r, RGB(0, 255, 0), , , 1, f Circle cb, (r, r), r, RGB(0, 0, 255), , , 1, f ''put the sprite at three different multipier ''levels, overlapping each other in the middle Put (146 - r, 108 - r), cr, or Put (174 - r, 108 - r), cg, or Put (160 - r, 84 - r), cb, or ''free the memory used by the sprites ImageDestroy cr ImageDestroy cg ImageDestroy cb ''pause the program before closing Sleep %% {{image class="center" title="Put Or example output" url="/images/put-or.png"}} {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgOpOr Or]]## - ##[[KeyPgPutgraphics Put (Graphics)]]## {{fbdoc item="back" value="CatPgGfx2D|2D Drawing Functions"}}{{fbdoc item="title" value="OUT"}}---- Outputs a value to a hardware port. {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Out** ( [[KeyPgByval byval]] //port// [[KeyPgAs as]] [[KeyPgUshort ushort]] , [[KeyPgByval byval]] //data// [[KeyPgAs as]] [[KeyPgUbyte ubyte]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## **Out** //port//,//value// ## {{fbdoc item="param"}} ##//port//## Hardware port to write to. ##//data//## Data value to write. {{fbdoc item="desc"}} This function sends ##//value//## to ##//port//## and returns immediately. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/hardware/out.bas"}}%%(freebasic) 'speakersound.bas Sub Sound(ByVal freq As uInteger, dur As uInteger) Dim t As Double,f1 as unsigned short f1 = 1193181 \ freq out &h61,inp(&h61) or 3 out &h43,&hb6 out &h42,lobyte(f1) out &h42,hibyte(f1) t=timer While ((Timer - t) * 1000) < dur sleep 0,1 Wend out &h61,inp(&h61) and &hfc end sub Sound(523, 60) 'C5 Sound(587, 60) 'D5 Sound(659, 60) 'E5 Sound(698, 60) 'F5 Sound(784, 60) 'G5 Sound(880, 60) 'A5 Sound(988, 60) 'B5 Sound(1046, 60) 'C6 %% {{fbdoc item="target"}} - In the Windows and Linux versions three port numbers (&H3C7, &H3C8, &H3C9) are hooked by the graphics library when a graphics mode is in use to emulate QB's VGA palette handling. This use is deprecated; use ##[[KeyPgPalette Palette]]## to retrieve and set palette colors. - Using true port access in the Windows version requires the program to install a device driver for the present session. For that reason, Windows executables using hardware port access should be run with administrator permits each time the computer is restarted. Further runs don't require admin rights as they just use the already installed driver. The driver is only 3K in size and is embedded in the executable. {{fbdoc item="see"}} - ##[[KeyPgInp Inp]]## - ##[[KeyPgWait Wait]]## - ##[[KeyPgPalette Palette]]## {{fbdoc item="back" value="CatPgMisc|Miscellaneous"}} {{fbdoc item="title" value="OUTPUT"}}---- Specifies text file to be opened for output mode {{fbdoc item="syntax"}}## [[KeyPgOpen open]] //filename// for **Output** [[[KeyPgEncoding encoding]] //encoding_type//] [[[KeyPgLock lock]] //lock_type//] as [#]//filenum// ## {{fbdoc item="param"}} ##//filename//## file name to open for output ##//encoding_type//## indicates encoding type for the file ##//lock_type//## locking to be used while the file is open ##//filenum//## unused file number to associate with the open file {{fbdoc item="desc"}} A file mode used with ##[[KeyPgOpen Open]]## to open a text file for writing. This mode is used to write text with ##[[KeyPgPrintPp Print #]]##, or comma separated values with ##[[KeyPgWrite Write #]]##. Text files can't be simultaneously read and written in FreeBASIC, so if both functions are required on the same file, it must be opened twice. ##//filename//## must be a string expression resulting in a legal file name in the target OS, without wildcards. The file will be sought for in the present directory, unless the ##//filename//## contains a path . If the file does not exist, it is created. The pointer is set at the first character of the file. ##//Encoding_type//## indicates the Unicode ##[[KeyPgEncoding Encoding]]## of the file, so characters are correctly read. If omitted, "ascii" encoding is defaulted. Only little endian character encodings are supported at the moment. -"utf8", -"utf16" -"utf32" -"ascii" (the default) ##//Lock_type//## indicates the way the file is locked for other processes, it is one of: - **Read** - the file can be opened simultaneously by other processes, but not for reading - **Write** - the file can be opened simultaneously by other processes, but not for writing - **Read Write** - the file cannot be opened simultaneously by other processes (the default) ##//filenum//## Is a valid FreeBASIC file number (in the range 1-255) not being used for any other file presently open. The file number identifies the file for the rest of file operations. A free file number can be found using the ##[[KeyPgFreefile Freefile]]## function. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/fileio/for-output.bas"}}%%(freebasic) Dim ff As Ubyte Dim randomvar As Integer Dim name_str As String Dim age_ubyte As Ubyte ff = Freefile Input "What is your name? ",name_str Input "What is your age? ",age_ubyte Open "testfile" For Output As #ff Write #ff, Int(Rnd(0)*42),name_str,age_ubyte Close #ff randomvar=0 name_str="" age_ubyte=0 Open "testfile" For Input As #ff Input #ff, randomvar,name_str,age_ubyte Close #ff Print "Random Number was: ", randomvar Print "Your name is: " + name_str Print "Your age is: " + Str(age_ubyte) 'File outputted by this sample will look like this, 'minus the comment of course: '23,"Your Name",19 %% {{fbdoc item="diff"}} - {{fbdoc item="see"}} - ##[[KeyPgAppend Append]]## - ##[[KeyPgInputfilemode Input (File Mode)]]## - ##[[KeyPgOpen Open]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}}{{fbdoc item="title" value="OVERLOAD"}}---- Specifies that a procedure name can be overloaded {{fbdoc item="syntax"}}## [[KeyPgDeclare Declare]] [[[KeyPgStatic Static]]] [[KeyPgSub Sub]] //procedure_name// **Overload** [[[KeyPgCdecl Cdecl]]|[[KeyPgStdcall Stdcall]]|[[KeyPgPascal Pascal]]] [[[KeyPgAlias Alias]] //"""external_name"""//] [([//parameter_list//])] [[[KeyPgModuleConstructor Constructor]] [//priority//]] [[[KeyPgStatic Static]]] [[[KeyPgExport Export]]] [[KeyPgDeclare Declare]] [[[KeyPgStatic Static]]] [[KeyPgFunction Function]] //procedure_name// **Overload** [[[KeyPgCdecl Cdecl]]|[[KeyPgStdcall Stdcall]]|[[KeyPgPascal Pascal]]] [[[KeyPgAlias Alias]] //"""external_name"""//] [([//parameter_list//])] [[KeyPgAs as]] //return_type// [[[KeyPgStatic Static]]] [[[KeyPgExport Export]]] [[[KeyPgPublic Public]]|[[KeyPgPrivate Private]]] [[KeyPgSub Sub]] //procedure_name// **Overload** [[[KeyPgCdecl Cdecl]]|[[KeyPgStdcall Stdcall]]|[[KeyPgPascal Pascal]]] [[[KeyPgAlias Alias]] //"""external_name"""//] [([//parameter_list//])] [[[KeyPgModuleConstructor Constructor]] [//priority//]] [[[KeyPgStatic Static]]] [[[KeyPgExport Export]]] //..procedure body..// [[KeyPgEnd End]] [[KeyPgSub Sub]] [[[KeyPgPublic Public]]|[[KeyPgPrivate Private]]] [[KeyPgFunction Function]] //procedure_name// **Overload** [[[KeyPgCdecl Cdecl]]|[[KeyPgStdcall Stdcall]]|[[KeyPgPascal Pascal]]] [[[KeyPgAlias Alias]] //"""external_name"""//] [([//parameter_list//])] [[KeyPgAs as]] //return_type// [[[KeyPgStatic Static]]] [[[KeyPgExport Export]]] //..procedure body..// [[KeyPgEnd End]] [[KeyPgFunction Function]] ## {{fbdoc item="desc"}} In procedure declarations, **Overload** allows procedure names to be overloaded, that is, other procedures can then be declared with the same name if their parameter lists are unique. Two parameter lists are unique if they contain a different number of parameters, or have parameters of different types. Note that this means that two or more procedures cannot be declared with the same name if they differ in return type alone. Once a procedure name has been declared overloaded, further declarations using the name need not specify *Overload*, but it is allowed. **Overload** is not necessary in member procedure declarations, as they are always implicitly overloaded. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/procs/overload.bas"}}%%(freebasic) DECLARE FUNCTION SUM OVERLOAD (A AS INTEGER,B AS INTEGER) AS INTEGER DECLARE FUNCTION SUM OVERLOAD (A AS SINGLE,B AS SINGLE) AS SINGLE FUNCTION SUM (A AS INTEGER,B AS INTEGER) AS INTEGER FUNCTION=A+B END FUNCTION FUNCTION SUM (A AS SINGLE,B AS SINGLE) AS SINGLE FUNCTION=A+B END FUNCTION DIM AS INTEGER A,B DIM AS SINGLE A1,B1 A=2 B=3 A1=2. b1=3. PRINT SUM(A,B) PRINT SUM (A1,B1) SLEEP %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDeclare Declare]]## - ##[[KeyPgSub Sub]]##, ##[[KeyPgFunction Function]]## {{fbdoc item="back" value="CatPgProcedures|Procedures"}}{{fbdoc item="title" value="PAINT"}}---- Fills an area delimited by a border of a specified color {{fbdoc item="syntax"}}## **Paint** [//target//,] [STEP] (//x//, //y//)[, [//paint//][, [//border_color//]]] ## {{fbdoc item="param"}} ##//target//## specifies buffer to draw on. ##STEP## indicates that coordinates are relative ##(//x//, //y//)## coordinates of the pixel on which to start the flood fill (paint) ##//paint//## the color attribute or fill pattern a numeric value indicates a color, while a string indicates a fill pattern ##//border_color//## boundary color for the fill {{fbdoc item="desc"}} Graphics command to fill an area delimited by a border of specified color. Also known as 'flood-fill' or 'paint bucket'. ##**Paint**## can operate on the current work page as set by the ##[[KeyPgScreenset Screenset]]## statement or on the target ##[[KeyPgGetgraphics Get]]##/##[[KeyPgPutgraphics Put]]## buffer, if specified. Filling starts at specified ##(//x//,//y//)## coordinates; if ##STEP## is specified, these are relative to the last graphics cursor position. Coordinates are also affected by custom coordinates system set up by ##[[KeyPgWindow Window]]## and/or ##[[KeyPgViewgraphics View (Graphics)]]## statements; clipping set by ##[[KeyPgViewgraphics View]]## also applies. If the ##//paint//## argument is a number, it is assumed a color in the same format used by the ##[[KeyPgColor Color]]## statement, and the region is flood-filled using that color. If ##//paint//## is a ##[[KeyPgString String]]##, the region will be filled using a pattern; the pattern is always 8*8 pixels, and the passed string must hold pixels data in a format dependent on the current color depth. The string holds pattern pixels row by row, and its size should be as follows: For color depths 1, 2, 4 and 8: ##size = 8 * 8 = 64## For color depths 15 and 16: ##size = (8 * 8) * 2 = 128## For color depths 24 and 32: ##size = (8 * 8) * 4 = 256## If the passed string is smaller, missing pixels will be 0. If the ##//paint//## argument is omitted, normal filling is performed using the current foreground color set by ##[[KeyPgColor Color]]##. Flood-filling continues until pixels of the specified border color are found; if ##//border_color//## is omitted, the current background color is assumed. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/paint.bas"}}%%(freebasic) ' draws a white circle painted blue inside screen 13 circle (160, 100), 30, 15 paint (160, 100), 1, 15 sleep %% {{fbdoc item="filename" value="examples/manual/gfx/paint2.bas"}}%%(freebasic) ' draws a circle and fills it with a checkered pattern '' choose the bit depth for the Screen '' try setting this to other values: 8, 16 or 32 const bit_depth = 8 '' function for returning a pixel color, represented as a string '' returns a the string in the appropriate format for the current bit depth function paint_pixel( byval c as uinteger, byval bit_depth_ as integer ) as string if bit_depth_ <= 8 then '' 8-bit: function = chr( cubyte(c) ) elseif bit_depth_ <= 16 then '' 16-bit: function = mkshort( c shr 3 and &h1f or _ c shr 5 and &h7e0 or _ c shr 8 and &hf800 ) elseif bit_depth_ <= 32 then '' 32-bit: function = mkl(c) end if end function '' open a graphics window at the chosen bit depth screenres 320, 200, bit_depth '' declare variables for holding colors dim as uinteger c, c1, c2, cb '' declare string variable for holding the pattern used in Paint dim as string paint_pattern = "" '' set colors if bit_depth <= 8 then c1 = 7 ''pattern color 1 c2 = 8 ''pattern color 2 cb = 15 ''border color else c1 = rgb(192, 192, 192) '' pattern color 1 c2 = rgb(128, 128, 128) '' pattern color 2 cb = rgb(255, 255, 255) '' border color end if '' make the pattern to be used in Paint for y as uinteger = 0 to 7 for x as uinteger = 0 to 7 '' choose the color of the pixel (c) if (x \ 4 + y \ 4) mod 2 > 0 then c = c1 else c = c2 end if '' add the pixel to the pattern paint_pattern = paint_pattern + paint_pixel(c, bit_depth) '' the following line can be used if you want to draw the '' pattern tile in the top left hand corner of the screen: ' pset (x, y), c next x next y '' draw a circle with the border color circle (160, 100), 50, cb, , , 1.0 '' paint the circle region with paint_pattern, stopping at the border color paint (160, 100), paint_pattern, cb '' pause before ending the program sleep %% {{fbdoc item="diff"}} - The QB version could not draw onto a ##[[KeyPgGetgraphics Get]]##/##[[KeyPgPutgraphics Put]]## buffer. - In QB, the fill pattern was always 8-bits wide, and the height was the length of the string (up to 64). In FreeBASIC, the fill pattern is 8 pixels wide, independent of the color depth, and the height is always 8. - The background color parameter supported by QB is not supported by the FreeBASIC version. {{fbdoc item="see"}} - ##[[KeyPgScreengraphics Screen]]## {{fbdoc item="back" value="CatPgGfx2D|2D Drawing Functions"}}{{fbdoc item="title" value="PALETTE"}}---- Customizes colors in modes with paletted colors {{fbdoc item="syntax"}}## **Palette** [Get] [//index//, //color//] **Palette** [Get] [//index//, //r//, //g//, //b//] **Palette** [Get] Using //arrayname(idx)// ## {{fbdoc item="param"}} ##Get## indicates getting palette information rather than setting palette information ##Using## indicates using array of color values ##//index//## palette index ##//color//## color attribute ##//r//## red color component ##//g//## green color component ##//b//## blue color component ##//arrayname(idx)//## array and index to get/set color attributes {{fbdoc item="desc"}} The ##**Palette**## statement is used to retrieve or customize the current palette for graphics modes with a color depth of up to 8bpp; using ##**Palette**## while in a mode with a higher color depth will have no effect. Calling ##**Palette**## with no argument restores the default palette for current graphics mode, as set by the ##[[KeyPgScreengraphics Screen (Graphics)]]## statement. The GfxLib sets a [[GfxDefPalettes default palette]] when a [[KeyPgScreengraphics Screen]] mode is initialized. ==First form== If you specify index and color, these are dependent on the current mode: {{table columns="3" cellpadding="1" cells="Screen mode;index range;color range;1;0-3;0-15;2;0-1;0-15;7,8;0-15;0-15;9;0-15;0-63;11;0-1;see below;12;0-15;see below;13 to 21;0-255; see below"}} In screen modes 1, 2, 7, 8 and 9 you can assign to each color index one of the colors in the available range. In other screen modes, the color must be specified in the form &hBBGGRR, where BB, GG and RR are the blue, green and red components ranging &h0-&h3F in hexadecimal (0-63 in decimal). If you don't like hexadecimal form, you can use the following formula to compute the integer value to pass to this parameter: ##color = red or (green shl 8) or (blue shl 16)## Where red, green and blue must range 0-63. Please note that color values accepted by ##**Palette**## are **not** the in the same form as returned by the ##[[KeyPgRgb RGB]]## macro (the red and blue fields are inverted, and the range is different); this is for backward compatibility with QB. ==Second form== In the second form, you specify the red, green and blue components for a palette entry directly, by calling ##**Palette**## with 4 parameters. In this case ##//r//##, ##//g//## and ##//b//## must be in the range 0-255. ==Third form== Calling ##**Palette** USING## allows to set a list of color values all at once; you should pass an array holding enough elements as the color indices available for your current graphics mode color depth (2 for 1bpp, 4 for 2bpp, 16 for 4bpp or 256 for 8bpp). The array elements must be integer color values in the form described above. The colors stored into ##//arrayname//## starting with given ##//idx//## index are then assigned to each palette index, starting with index 0. Form 1 and 3 are for backward compatibility with QB; form 2 is meant to ease palette handling. Any change to the palette is immediately visible on screen. If the ##GET## option is specified, ##**Palette**## retrieves instead of setting color values for the current palette. The parameters have the same meaning as specified for the form being used, but in this case color, ##//r//##, ##//g//## and ##//b//## must be variables passed by reference that will hold the color RGB values on function exit. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/palette.bas"}}%%(freebasic) ' Setting a single color, form 1. screen 15 locate 1,1: color 15 print "Press any key to change my color!" sleep ' Now change color 15 hues to bright red palette 15, &h00003F sleep %% {{fbdoc item="filename" value="examples/manual/gfx/palette2.bas"}}%%(freebasic) ' Getting a single color, form 2. dim as integer r, g, b screen 13 palette get 32, r, g, b print "Color 32 hues:" print using "Red:### Green:### Blue:###"; r; g; b sleep %% {{fbdoc item="filename" value="examples/manual/gfx/palette3.bas"}}%%(freebasic) ' Getting whole palette, form 3. dim pal(1 to 256) as integer dim i as integer screen 13 palette get using pal for i = 1 to 16 print "Color"; i; " ="; hex(pal(i)) next i sleep %% {{fbdoc item="diff"}} - QB version did not support palette retrieval. {{fbdoc item="see"}} - ##[[KeyPgScreengraphics Screen (Graphics)]]## - ##[[KeyPgColor Color]]## - ##[[GfxInternalFormats Internal Pixel Formats]]## {{fbdoc item="back" value="CatPgGfx2D|2D Drawing Functions"}}{{fbdoc item="title" value="PASCAL"}}---- Specifies a //Pascal//-style calling convention in a procedure declaration {{fbdoc item="syntax"}}## [[KeyPgDeclare Declare]] [[[KeyPgStatic Static]]] [[KeyPgSub Sub]] //procedure_name// [[[KeyPgOverload Overload]]] **Pascal** [[[KeyPgAlias Alias]] //"""external_name"""//] [([//parameter_list//])] [[[KeyPgModuleConstructor Constructor]] [//priority//]] [[[KeyPgStatic Static]]] [[[KeyPgExport Export]]] [[KeyPgDeclare Declare]] [[[KeyPgStatic Static]]] [[KeyPgFunction Function]] //procedure_name// [[[KeyPgOverload Overload]]] **Pascal** [[[KeyPgAlias Alias]] //"""external_name"""//] [([//parameter_list//])] [[KeyPgAs as]] //return_type// [[[KeyPgStatic Static]]] [[[KeyPgExport Export]]] [[[KeyPgPublic Public]]|[[KeyPgPrivate Private]]] [[KeyPgSub Sub]] //procedure_name// [[[KeyPgOverload Overload]]] **Pascal** [[[KeyPgAlias Alias]] //"""external_name"""//] [([//parameter_list//])] [[[KeyPgModuleConstructor Constructor]] [//priority//]] [[[KeyPgStatic Static]]] [[[KeyPgExport Export]]] //..procedure body..// [[KeyPgEnd End]] [[KeyPgSub Sub]] [[[KeyPgPublic Public]]|[[KeyPgPrivate Private]]] [[KeyPgFunction Function]] //procedure_name// [[[KeyPgOverload Overload]]] **Pascal** [[[KeyPgAlias Alias]] //"""external_name"""//] [([//parameter_list//])] [[KeyPgAs as]] //return_type// [[[KeyPgStatic Static]]] [[[KeyPgExport Export]]] //..procedure body..// [[KeyPgEnd End]] [[KeyPgFunction Function]] ## {{fbdoc item="desc"}} In procedure declarations, ##**Pascal**## specifies that a procedure will use the //Pascal// calling convention. In the //Pascal// calling convention, any parameters are to be passed (pushed onto the stack) in the same order in which they are listed, that is, from left to right. The procedures need not preserve the ##EAX##, ##ECX## or ##EDX## registers, and must clean up the stack (pop any parameters) before it returns. //Pascal// is the default calling convention for Microsoft ""QuickBASIC"" procedures, and is the standard convention used in the Windows 3.1 API. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/procs/pascal.bas"}}%%(freebasic) Declare Function MyFunc pascal Alias "MyFunc" (MyParm As Integer) As Integer %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - [[KeyPgCdecl Cdecl]], [[KeyPgStdcall Stdcall]] - [[KeyPgDeclare Declare]] - [[KeyPgSub Sub]], [[KeyPgFunction Function]] {{fbdoc item="back" value="CatPgProcedures|Procedures"}}{{fbdoc item="title" value="PCOPY"}}---- Copies one graphical or text page onto another {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Pcopy** ( [[KeyPgByval byval]] //source// [[KeyPgAs as]] [[KeyPgInteger integer]] = -1, [[KeyPgByval byval]] //destination// [[KeyPgAs as]] [[KeyPgInteger integer]] = -1 ) ## {{fbdoc item="usage"}}## **Pcopy** [ //source// ] [, //destination// ] ## {{fbdoc item="param"}} ##//source//## page to copy from ##//destination//## page to copy to {{fbdoc item="desc"}} Copies one graphical or text video page to another. Useful for drawing all graphics on one invisible page and copying it to the active visible page - creating smooth graphics and animation. Known as 'double buffering' or 'page flipping'. ##//source//## and ##//destination//## refer to page numbers. The 'source' page is copied over the 'destination' page when pcopy is called. If the ##//source//## argument is omitted, the current working page is assumed. If the ##//destination//## page is omitted, the current visible page is assumed. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/pcopy.bas"}}%%(freebasic) screenres 320, 240, 32, 2 'Sets up the screen to be 320x240 in 32-bit color with 2 video pages. dim as integer max_x_value = 270, x_value = 50 'Dimension our working variables. do while x_value < max_x_value 'Loop while x_value is less than the max screenset 2,1 'Sets the working page to 2 and the displayed page to 1 cls 'Clears the screen so we can start fresh circle (x_value,50),50,&h00FFFF00 'Draws a circle with a 50 pixel radius in yellow on page 2 screenset 1,1 'Sets the working page to 1 and the displayed page to 1 screensync 'Waits for vertical refresh pcopy 2,1 'Copies our circle from page 2 to page 1 x_value += 1 'Increments x_value so it will move. sleep 25 'Waits for 25 milliseconds. loop 'Goes back to do as long as x_value is less than x_max_value sleep 'Waits for any key to be pressed so you can see the work done. %% {{fbdoc item="target"}} - Maximum number of text pages in Windows is 4. - Maximum number of text pages in DOS is 8. - Maximum number of text pages in all other targets is 1. - Maximum number of graphics pages depends on what was specified when the ##[[KeyPgScreengraphics Screen]]## or ##[[KeyPgScreenres Screenres]]## statement was called. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgFlip Flip]]## - ##[[KeyPgScreencopy Screencopy]]## {{fbdoc item="back" value="CatPgGfxScreen|Screen Functions"}}{{fbdoc item="title" value="PEEK"}}---- Gets the value of an arbitrary type at an address in memory {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Peek** ( [[KeyPgByval byval]] //address// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] ) [[KeyPgAs as]] [[KeyPgUbyte ubyte]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Peek** ( //datatype//, [[KeyPgByval byval]] //address// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] ) [[KeyPgAs as]] //datatype// ## ~&//Note: ##**Peek**## returns a reference to the value at the specified address. As of version 0.17b, there is no way to specify returning a reference, although this will change in future versions. At that time, this syntax should be changed to accommodate returning a reference.// {{fbdoc item="usage"}}## **Peek**( [ //datatype//, ] //address// ) ## {{fbdoc item="param"}} ##//address//## The address in memory to get the value from. ##//datatype//## The type of value to get. {{fbdoc item="desc"}} This procedure returns a reference to the value in memory given by a memory address, and is equivalent to ##*cast(ubyte ptr, //address//)## or ##*cast(//datatype// ptr, //address//)## {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/memory/peek.bas"}}%%(freebasic) Dim i As Integer, p As Integer Ptr p = @i Poke Integer, p, 420 Print Peek(Integer, p) %% will produce the output: %%420 %% {{fbdoc item="diff"}} - Only the byte form were supported in QB. - ##DEF SEG## isn't needed anymore because the address space is 32-bit flat in FreeBASIC. {{fbdoc item="see"}} - ##[[KeyPgPoke Poke]]## {{fbdoc item="back" value="CatPgMemory|Memory Functions"}}{{fbdoc item="title" value="PMAP"}}---- Maps coordinates between view and physical mapping. {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **PMap** ( [[KeyPgByval byval]] //coord// [[KeyPgAs as]] [[KeyPgSingle single]], [[KeyPgByval byval]] //func// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgSingle single]] ## {{fbdoc item="usage"}}## //result// = **PMap**( //coord//, //func// ) ## {{fbdoc item="param"}} ##//coord//## An expression indicating the coordinate to be mapped. ##//func//## The mapping function number to be applied to given coordinate. {{fbdoc item="ret"}} The mapped coordinate value. {{fbdoc item="desc"}} This function converts a coordinate between view (as defined by the ##[[KeyPgWindow Window]]## statement) and physical (as set by the ##[[KeyPgViewgraphics View (Graphics)]]## statement) mappings. Depending on the value of ##//func//##, ##//expr//## is used to compute a different mapping to be returned by PMAP: {{table columns="2" cellpadding="1" cells="func value:;return value:;0;Treats expr as x view coordinate and returns corresponding x physical coordinate.;1;Treats expr as y view coordinate and returns corresponding y physical coordinate.;2;Treats expr as x physical coordinate and returns corresponding x view coordinate.;3;Treats expr as y physical coordinate and returns corresponding y view coordinate."}} {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/pmap.bas"}}%%(freebasic) screen 12 window screen (0, 0)-(100, 100) print "Logical x=50, Physical x="; pmap(50, 0) print "Logical y=50, Physical y="; pmap(50, 1) print "Physical x=160, Logical x="; pmap(160, 2) print "Physical y=60, Logical y="; pmap(60, 3) sleep %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgWindow Window]]## - ##[[KeyPgViewgraphics View (Graphics)]]## {{fbdoc item="back" value="CatPgGfxScreen|Screen Functions"}}{{fbdoc item="title" value="POINT"}}---- Returns the color attribute of a specified pixel coordinate {{fbdoc item="syntax"}}## //result// = **Point**( //coord_x//, //coord_y// [,//buffer//] ) ## {{fbdoc item="usage"}}## ##//coord_x//## x coordinate of the pixel ##//coord_y//## y coordinate of the pixel ##//buffer//## the image buffer to read from {{fbdoc item="ret"}}## The color attribute at the specified coordinates {{fbdoc item="desc"}} GfxLib Function that reads the color of the pixel at the coordinate ##//coord_x//##, ##//coord_y//## of the screen, or of ##//buffer//##, if supplied. The value return is a color index in a 256 or less color ##[[KeyPgScreengraphics Screen]]##, and a RGB value in true color modes. If the coordinates are off-screen, -1 is returned The function ##**Point**## does not work in text modes. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/point.bas"}}%%(freebasic) screen 13 line (10,10)-(100,100),12 print point(20,20) %% **Output:** %% 12 %% {{fbdoc item="diff"}} - None, in the VGA compatible SCREEN modes. In SVGA modes, it returns a RGB value {{fbdoc item="see"}} - ##[[KeyPgPset Pset]]## - ##[[KeyPgPmap Pmap]]## - ##[[KeyPgColor Color]]## - ##[[KeyPgViewgraphics View (Grpahics)]]## - ##[[KeyPgWindow Window]]## {{fbdoc item="back" value="CatPgGfx2D|2D Drawing Functions"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:56:40 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: d596b79119b0fc92a8cf64d16a569a72 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 853 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="POINTER"}}---- A variable declaration type modifier {{fbdoc item="syntax"}}## [[KeyPgDim dim]] //symbolname// [[KeyPgAs as]] [[DataType DataType]] {**Pointer** | [[KeyPgPtr ptr]]} ## {{fbdoc item="desc"}} Declares a pointer variable. The same as ##[[KeyPgPtr Ptr]]##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/datatype/pointer.bas"}}%%(freebasic) dim p as zstring pointer dim text as string text = "Hello World!" p = strptr(text) + 6 print text print *p '' Output: '' Hello World! '' World! %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Pointer""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgPtr Ptr]]## {{fbdoc item="back" value="CatPgStdDataTypes|Standard Data Types"}} {{fbdoc item="title" value="POKE"}}---- Assigns a value to a location in memory. {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Poke** ( [[KeyPgByval byval]] //address// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]], [[KeyPgByref byref]] //value// [[KeyPgAs as]] [[KeyPgUbyte ubyte]] ) [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Poke** ( //datatype//, [[KeyPgByval byval]] //address// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]], [[KeyPgByref byref]] //value// [[KeyPgAs as]] //datatype// ) ## {{fbdoc item="usage"}}## **Poke**( [ //datatype//, ] //address//, //value// ) ## {{fbdoc item="param"}} ##//datatype//## The type of data at the specified address. ##//address//## The location in memory to assign to. ##//value//## The value to assign. {{fbdoc item="desc"}} ##**Poke**## assigns a value to a location in memory. It is equivalent to ##*cast(ubyte ptr, //address//) = //value//## or ##*cast(//datatype// ptr, //address//) = //value//## When ##//datatype//## is a user-defined type, ##**Poke**## assigns ##//value//## using the type's ##[[KeyPgOpLet Operator Let]]##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/memory/poke.bas"}}%%(freebasic) Dim i As Integer, p As Integer Ptr p = @i Poke Integer, p, 420 Print Peek(Integer, p) %% Will produce the output: %%420 %% {{fbdoc item="diff"}} - Only the byte form were supported in QB. - ##DEF SEG## isn't needed anymore because the address space is 32-bit flat in FreeBASIC. {{fbdoc item="see"}} - ##[[KeyPgPeek Peek]]## {{fbdoc item="back" value="CatPgMemory|Memory Functions"}} {{fbdoc item="title" value="POS"}}---- Returns the horizontal (left-right) position of the text cursor {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Pos** [[KeyPgOverload overload]] ( ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Pos** ( [[KeyPgByval byval]] //dummy// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = POS( //dummy// ) ## {{fbdoc item="param"}} ##//dummy//## An unused parameter retained for backward compatibility with QB. {{fbdoc item="ret"}} Returns the horizontal position of the text cursor. {{fbdoc item="desc"}} Returns the horizontal (left-right) position of the text cursor. 1 means the very left. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/console/pos.bas"}}%%(freebasic) print "position: "; pos print "hello world"; print "position: "; pos %% {{fbdoc item="diff"}} - None. {{fbdoc item="see"}} - ##[[KeyPgLocate Locate]]## {{fbdoc item="back" value="CatPgConsole|Console Functions"}}{{fbdoc item="title" value="#DEFINE"}}---- Preprocessor directive to define a macro {{fbdoc item="syntax"}}## #define //identifier// #define //identifier// //text// #define //identifier//([//parameters//]) //macro_text// ## {{fbdoc item="desc"}} Preprocessor keyword that defines an identifier with a custom meaning: - Empty defines (without //text//) can be checked for existence with ##[[KeyPgPpifdef #ifdef]]## and ##[[KeyPgPpifndef #ifndef]]## to hide parts of code to the compiler (conditional compiling). - Non-empty defines (with //text//) are substituted by its //text// when the source is parsed, allowing a sort of "shorthand". - Defines with parameters are substituted by the //macro_text//, that will contain all the arguments passed replaced. **Note:** The open parentheses character ('(') must immediately follow the //identifier//, there should be no white-spaces between them. - Defines are visible only in the scope where they are defined. If defined at module level, the define is visible throughout the module. If the ##//identifier//## is defined inside a compound statement having scope (##[[KeyPgSub Sub]]##, ##[[KeyPgFornext For..Next]]##, ##[[KeyPgWhilewend While..Wend]]##, ##[[KeyPgDoloop Do..Loop]]##, ##[[KeyPgScope Scope..End Scope]]##, etc), the ##//identifier//## is visible only within that scope. - Namespaces do not have any effect on the visibility of a define. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/prepro/define.bas"}}%%(freebasic) '' Definition and check #define DEBUGGING #ifdef DEBUGGING ' ... statements #endif '' Simple definition/text replacement #define FALSE 0 #define TRUE (not FALSE) '' Function like definition #define MyRGB(R,G,B) (((R)SHL 16) OR ((G)SHL 8) OR (B)) print hex( MyRGB(&hff, &h00, &hff) ) '' Line continuation and statements in a definition #define printval(bar) _ print #bar; " ="; bar '' #defines are visible only in the scope where they are defined scope #define LOCALDEF 1 end scope #ifndef LOCALDEF # print LOCALDEF is not defined #endif '' namespaces have no effect on the visibility of a define namespace foo # define NSDEF end namespace #ifdef NSDEF # print NSDEF is defined #endif %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgPpmacro #macro]]## - ##[[KeyPgPpif #if]]## - ##[[KeyPgPpelse #else]]## - ##[[KeyPgPpelseif #elseif]]## - ##[[KeyPgPpendif #endif]]## - ##[[KeyPgPpifdef #ifdef]]## - ##[[KeyPgPpifndef #ifndef]]## - ##[[KeyPgPpundef #undef]]## - ##[[KeyPgDefined defined]]## {{fbdoc item="back" value="CatPgPreProcess|Preprocessor"}}{{fbdoc item="title" value="#ELSE"}}---- Preprocessor conditional directive {{fbdoc item="syntax"}}## [[KeyPgPpif #if]] (expression) ' Conditionally included statements if expression is True **#else** ' Conditionally included statements if expression is False [[KeyPgPpendif #endif]] ## {{fbdoc item="desc"}} **#else** can be added to an ##[[KeyPgPpif #if]]##, ##[[KeyPgPpifdef #ifdef]]##, or ##[[KeyPgPpifndef #ifndef]]## block to provide an alternate result to the conditional expression. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/prepro/else.bas"}}%%(freebasic) #DEFINE MODULE_VERSION 1 Dim a as String #IF (MODULE_VERSION > 0) a = "Release" #ELSE a = "Beta" #ENDIF Print "Program is "; a %% {{fbdoc item="diff"}} - New to Freebasic {{fbdoc item="see"}} - ##[[KeyPgPpdefine #define]]## - ##[[KeyPgPpmacro #macro]]## - ##[[KeyPgPpif #if]]## - ##[[KeyPgPpelseif #elseif]]## - ##[[KeyPgPpendif #endif]]## - ##[[KeyPgPpifdef #ifdef]]## - ##[[KeyPgPpifndef #ifndef]]## - ##[[KeyPgPpundef #undef]]## - ##[[KeyPgDefined defined]]## {{fbdoc item="back" value="CatPgPreProcess|Preprocessor"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:56:49 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 9363b547513203d6a1017cd70cce8a11 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 1232 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="#ELSEIF"}}---- Preprocessor conditional directive {{fbdoc item="syntax"}}## [[KeyPgPpif #if]] (expression1) ' Conditionally included statements if expression1 is True **#elseif** (expression2) ' Conditionally included statements if expression2 is True [[KeyPgPpelse #else]] ' Conditionally included statements if both ' expression1 and expression2 are False [[KeyPgPpendif #endif]] ## {{fbdoc item="desc"}} **#elseif** can be added to an ##[[KeyPgPpif #if]]## block to provide an additional conditions. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/prepro/elseif.bas"}}%%(freebasic) #DEFINE WORDSIZE 16 #IF (WORDSIZE = 16) ' Do some some 16 bit stuff #ELSEIF (WORDSIZE = 32) ' Do some some 32 bit stuff #ELSE #ERROR WORDSIZE must be set to 16 or 32 #ENDIF %% {{fbdoc item="diff"}} - New to Freebasic {{fbdoc item="see"}} - ##[[KeyPgPpdefine #define]]## - ##[[KeyPgPpmacro #macro]]## - ##[[KeyPgPpif #if]]## - ##[[KeyPgPpelse #else]]## - ##[[KeyPgPpendif #endif]]## - ##[[KeyPgPpifdef #ifdef]]## - ##[[KeyPgPpifndef #ifndef]]## - ##[[KeyPgPpundef #undef]]## - ##[[KeyPgDefined defined]]## {{fbdoc item="back" value="CatPgPreProcess|Preprocessor"}} {{fbdoc item="title" value="#ENDIF"}}---- Preprocessor conditional directive {{fbdoc item="syntax"}}## **#endif** ## {{fbdoc item="desc"}} Ends a group of conditional directives See ##[[KeyPgPpif #if]]##, ##[[KeyPgPpifdef #ifdef]]##, or ##[[KeyPgPpifndef #ifndef]]## for examples of usage. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/prepro/endif.bas"}}%%(freebasic) #DEFINE DEBUG_LEVEL 1 #IF (DEBUG_LEVEL = 1) 'Conditional statements #ENDIF %% {{fbdoc item="diff"}} - New to Freebasic {{fbdoc item="see"}} - ##[[KeyPgPpdefine #define]]## - ##[[KeyPgPpmacro #macro]]## - ##[[KeyPgPpif #if]]## - ##[[KeyPgPpelse #else]]## - ##[[KeyPgPpelseif #elseIf]]## - ##[[KeyPgPpifdef #ifdef]]## - ##[[KeyPgPpifndef #ifndef]]## - ##[[KeyPgPpundef #undef]]## - ##[[KeyPgDefined defined]]## {{fbdoc item="back" value="CatPgPreProcess|Preprocessor"}}{{fbdoc item="title" value=" #ERROR"}}---- Preprocessor diagnostic directive {{fbdoc item="syntax"}}## **#error** //error_text// ## {{fbdoc item="param"}} ##//error_text//## The display message {{fbdoc item="desc"}} ##**#error**## stops compiling and displays ##//error_text//## when compiler finds it. This keyword must be surrounded by an ##[[KeyPgPpif #if]]## ...##[[KeyPgPpendif #endif]]## so compiler can reach ##**#error**## only if is meet. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/prepro/error.bas"}}%%(freebasic) #define c 1 #if c = 1 #error Bad value of c #endif %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgPpif #if]]## - ##[[KeyPgPpprint #print]]## {{fbdoc item="back" value="CatPgPreProcess|Preprocessor"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:56:58 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 6e277944526b779af5538e141ee363f3 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 1326 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="#IF"}}---- Preprocessor conditional directive {{fbdoc item="syntax"}}## **#if** (expression) ' Conditionally included statements [[KeyPgPpendif #endif]] ## {{fbdoc item="desc"}} Conditionally includes statements at compile time. Statements contained within the ##**#if**## / ##[[KeyPgPpendif #endif]]## block are included if ##//expression//## evaluates to True (non-zero) and excluded (ignored) if ##//expression//## evaluates to False (0). This conditional directive differs from the ##[[KeyPgIfthen If]]## conditional statement in that ##**#if**## is evaluated at compile-time and ##[[KeyPgIfthen If]]## is evaluated at run-time. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/prepro/if.bas"}}%%(freebasic) #define DEBUG_LEVEL 1 #IF (DEBUG_LEVEL >= 2) ' This line is not compiled since the expression is False Print "Starting application" #ENDIF %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgPpdefine #define]]## - ##[[KeyPgPpmacro #macro]]## - ##[[KeyPgPpelse #else]]## - ##[[KeyPgPpelseif #elseIf]]## - ##[[KeyPgPpendif #endif]]## - ##[[KeyPgPpifdef #ifdef]]## - ##[[KeyPgPpifndef #ifndef]]## - ##[[KeyPgPpundef #undef]]## - ##[[KeyPgDefined defined]]## {{fbdoc item="back" value="CatPgPreProcess|Preprocessor"}} {{fbdoc item="title" value="#IFDEF"}}---- Preprocessor conditional directive {{fbdoc item="syntax"}}## **#ifdef** //symbol// ' Conditionally included statements [[KeyPgPpendif #endif]] ## {{fbdoc item="desc"}} Conditionally includes statements at compile time. Statements within the ##**#ifdef**...[[KeyPgPpendif #endif]]## block are included if ##//symbol//## is defined and excluded (ignored) if ##//symbol//## is not defined. ##**#ifdef** //symbol//## is equivalent to ##[[KeyPgPpif #if]] [[KeyPgDefined defined]] (//symbol//)## {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/prepro/ifdef.bas"}}%%(freebasic) #DEFINE _DEBUG #IFDEF _DEBUG ' Special statements for debugging #ENDIF %% {{fbdoc item="diff"}} - New to Freebasic {{fbdoc item="see"}} - ##[[KeyPgPpdefine #define]]## - ##[[KeyPgPpmacro #macro]]## - ##[[KeyPgPpif #if]]## - ##[[KeyPgPpelse #else]]## - ##[[KeyPgPpelseif #elseif]]## - ##[[KeyPgPpendif #endif]]## - ##[[KeyPgPpifndef #ifndef]]## - ##[[KeyPgPpundef #undef]]## - ##[[KeyPgDefined defined]]## {{fbdoc item="back" value="CatPgPreProcess|Preprocessor"}}{{fbdoc item="title" value="#IFNDEF"}}---- Preprocessor conditional directive {{fbdoc item="syntax"}}## **#ifndef** //symbol// ' Conditionally included statements [[KeyPgPpendif endif]] ## {{fbdoc item="desc"}} Conditionally includes statements at compile time. Statements within the ##**#ifndef**...[[KeyPgPpendif #endif]]## block are included if //symbol// is not defined and excluded (ignored) if //symbol// is defined. ##**#ifndef** //symbol//## is equivalent to ##[[KeyPgPpif #if]] Not [[KeyPgDefined defined]](//symbol//)## {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/prepro/ifndef.bas"}}%%(freebasic) #IFNDEF __MYFILE_BI__ #DEFINE __MYFILE_BI__ ' Declarations #ENDIF %% {{fbdoc item="diff"}} - New to Freebasic {{fbdoc item="see"}} - ##[[KeyPgPpdefine #define]]## - ##[[KeyPgPpmacro #macro]]## - ##[[KeyPgPpif #if]]## - ##[[KeyPgPpelse #else]]## - ##[[KeyPgPpelseif #elseif]]## - ##[[KeyPgPpendif #endif]]## - ##[[KeyPgPpifdef #ifdef]]## - ##[[KeyPgPpundef #undef]]## - ##[[KeyPgDefined defined]]## {{fbdoc item="back" value="CatPgPreProcess|Preprocessor"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:57:07 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 68b9becfe173a57e4f8e0f4238a2221c Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 930 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="#LIBPATH"}}---- Preprocessor statement to add a search path for libraries {{fbdoc item="syntax"}}## **#libpath** "//path//" ## {{fbdoc item="desc"}} Adds a library search path to the linker's list of search paths as if it had been specified on the command line with the '-p' option. Paths are relative to the working directory where fbc was invoked and not relative to the directory of the source file. No error is generated if the path does not exist and compilation and linking will continue. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/prepro/libpath.bas"}}%%(freebasic) ' search the lib directory for external libraries #libpath "lib" %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgInclude #inclib]]## - ##[[KeyPgInclude #include]]## - [[CompilerOptp Compiler Option: -p]] {{fbdoc item="back" value="CatPgPreProcess|Preprocessor"}} {{fbdoc item="title" value="#LINE"}}---- Preprocessor directive to set the current line number and file name {{fbdoc item="syntax"}}## **#line** //number// [ "//name//" ] ## {{fbdoc item="param"}} ##//number// ## new line number ##"//name//"## new file name (optional) {{fbdoc item="desc"}} Informs the compiler of a change in line number and file name and updates the ##[[KeyPgDdfile __FILE__]]## and ##[[KeyPgDdline __LINE__]]## macro values accordingly. Both compile time messages and run-time messages are affected by this directive. This directive allows other programs to generate source code for the FreeBASIC compiler and have it return warning and/or error messages that refer to the original source used by the other program. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/prepro/line.bas"}}%%(freebasic) #line 155 "outside.src" error 1000 '' Output is: '' Aborting due to runtime error 1000 at line 157 of outside.src() %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDdfile __FILE__]]## - ##[[KeyPgDdline __LINE__]]## {{fbdoc item="back" value="CatPgPreProcess|Preprocessor"}}{{fbdoc item="title" value="#MACRO...#ENDMACRO"}}---- Preprocessor directive to define a multiline macro {{fbdoc item="syntax"}}## **#macro** //macro_name//( [ //param1// [, //param_list//] ] ) //macro body// **#endmacro** ## {{fbdoc item="desc"}} ##**#macro**## defines a function like macro where ##//macro body//## may span multiple lines. Parameters supplied to the function like macro are substituted where they occur in the ##//macro body//##. The entire ##//macro body//## is substituted where ever ##//macro_name//## appears in the source code. The number of parameters supplied to a macro must match the number of parameters in its ##**#macro**## definition. The ##[[KeyPgPpifdef #ifdef]]## and ##[[KeyPgPpifndef #ifndef]]## preprocessor conditionals can test if ##//macro_name//## exists or does not exist. The ##[[KeyPgPpundef #undef]]## preprocessor directive will undefine a macro so that it may be redefined with another definition. Macro substitution can be checked by using the -g -r switches. The compiler doesn't erase the intermediate .asm file where the code actually sent to the compiler can be seen close to its translation into assembler. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/prepro/macro.bas"}}%%(freebasic) '' macro as an expression value #macro Print1( a, b ) a + b #endmacro print Print1( "Hello", "World" ) '' Output : '' Hello World! %% {{fbdoc item="filename" value="examples/manual/prepro/macro2.bas"}}%%(freebasic) '' macro as multiple statements #macro Print2( a, b ) print a; print " "; print b; print "!" #endmacro Print2( "Hello", "World" ) '' Output : '' Hello World! %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgPpdefine #define]]## - ##[[KeyPgPpif #if]]## - ##[[KeyPgPpelse #else]]## - ##[[KeyPgPpelseif #elseif]]## - ##[[KeyPgPpendif #endif]]## - ##[[KeyPgPpifdef #ifdef]]## - ##[[KeyPgPpifndef #ifndef]]## - ##[[KeyPgPpundef #undef]]## - ##[[KeyPgDefined defined]]## {{fbdoc item="back" value="CatPgPreProcess|Preprocessor"}}{{fbdoc item="title" value=" #PRINT"}}---- Preprocessor diagnostic directive {{fbdoc item="syntax"}}## **#print** //text// ## {{fbdoc item="desc"}} Causes compiler to output ##//text//## to screen during compilation. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/prepro/print.bas"}}%%(freebasic) #PRINT Now compiling module foo %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgPperror #error]]## {{fbdoc item="back" value="CatPgPreProcess|Preprocessor"}}{{fbdoc item="title" value="#UNDEF"}}---- Preprocessor directive to undefine a macro {{fbdoc item="syntax"}}## **#undef** //symbol// ## {{fbdoc item="desc"}} Undefines a symbol previously defined with ##[[KeyPgPpdefine #define]]##. Can be used to ensure that a macro or symbol has a limited lifespan and does not conflict with a similar macro definition that may be defined later in the source code. (Note: ###undef## should not be used to undefine variable or function names used in the current function scope. The names are needed internally by the compiler and removing them can cause strange and unexpected results.) {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/prepro/undef.bas"}}%%(freebasic) #DEFINE ADD2(a_, b_) ((a_) + (b_)) Print ADD2(1, 2) ' Macro no longer needed so get rid of it ... #UNDEF ADD2 %% {{fbdoc item="diff"}} - New to Freebasic {{fbdoc item="see"}} - ##[[KeyPgPpdefine #define]]## - ##[[KeyPgPpmacro #macro]]## - ##[[KeyPgPpif #if]]## - ##[[KeyPgPpelse #else]]## - ##[[KeyPgPpelseif #elseif]]## - ##[[KeyPgPpendif #endif]]## - ##[[KeyPgPpifdef #ifdef]]## - ##[[KeyPgPpifndef #ifndef]]## - ##[[KeyPgDefined defined]]## {{fbdoc item="back" value="CatPgPreProcess|Preprocessor"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:57:37 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 5729ece37a5531bdf37b54e8deac6a42 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 1243 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="#PRAGMA"}}---- Preprocessor directive {{fbdoc item="syntax"}}## **#pragma** //option// [ =//value// ] ##//Or//## **#pragma** **push** ( //option// ) ##//Or//## **#pragma** **pop** ( //option// ) ## {{fbdoc item="param"}} Possible values for ##//option//## and related ##//value//##s: {{table columns="3" cellpadding="1" cells="Option; Value; Description; msbitfields; 0; Use bitfields compatible with gcc (default);###; (nonzero); Use bitfields compatible with those used in Microsoft C compilers; once; N/A; cause the source file in which the pragma appears to behave as though it was included with #include once ..."}} {{fbdoc item="desc"}} Allows the setting of compiler options inside the source code. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/prepro/pragma.bas"}}%%(freebasic) '' save the current pragma setting #pragma push(msbitfields) '' switch to MSVC-compatible bitfields #pragma msbitfields=1 '' do something that requires MS-compatible bitfields here '' restore original setting #pragma pop(msbitfields) %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgInclude #include]]## {{fbdoc item="back" value="CatPgPreProcess|Preprocessor"}} {{fbdoc item="title" value="PRESERVE"}}---- Used with ##[[KeyPgRedim Redim]]## to preserve contents will resizing an array {{fbdoc item="syntax"}}## [[KeyPgRedim redim]] **Preserve** //array//(...) [[KeyPgAs as]] [[DataType datatype]] ## {{fbdoc item="desc"}} Used with ##[[KeyPgRedim Redim]]## so that when an array is resized, data is not reset but is preserved. This means when the array is enlarged that only new data is reset, while the old data remains the same. In arrays with more than one dimension, only the first subscription can be redimensioned (arrays are stored in row-major order, so it's the first, not the last subscription). {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/array/preserve.bas"}}%%(freebasic) redim array(1 to 3) as integer Dim i as integer array(1) = 10 array(2) = 5 array(3) = 8 redim preserve array(2 to 10) for i = 2 to 10 print "array("; i; ") = "; array(i) next %% {{fbdoc item="diff"}} - PRESERVE wasn't supported until PDS 7.1 {{fbdoc item="see"}} - ##[[KeyPgDim Dim]]## - ##[[KeyPgLbound Lbound]]## - ##[[KeyPgRedim Redim]]## - ##[[KeyPgUbound Ubound]]## {{fbdoc item="back" value="CatPgArray|Array Functions"}}{{fbdoc item="title" value="PRESET"}}---- Plots a single pixel {{fbdoc item="syntax"}}## **PReset** [//target// ,] [STEP] (//x//, //y//) [,//color//] ## {{fbdoc item="param"}} ##//target//## specifies buffer to draw on. ##STEP## indicates that coordinates are relative ##(//x, y//)## coordinates of the pixel. ##//color//## the color attribute. {{fbdoc item="desc"}} ##//target//## specifies buffer to draw on. ##//target//## may be an image created with ##[[KeyPgImagecreate ImageCreate]]## or ##[[KeyPgGetgraphics Get (Graphics)]]##. If omitted, //target// defaults to the screen's current work page. ##(//x, y//)## are the coordinates of the pixel. STEP if present, indicates that ##(//x, y//)## coordinates are relative to the graphics cursor position. If omitted, ##(//x, y//)## are relative to the upper left-hand corner of ##//target//##. The x and y coordinates are affected by the last call to the ##[[KeyPgViewgraphics View (Graphics)]]## and ##[[KeyPgWindow Window]]## statements, and respect the current clipping region as set by the ##[[KeyPgViewgraphics View (Graphics)]]## statement. ##//color//## specifies the color attribute. If omitted, ##//color//## defaults to the current background color. See ##[[KeyPgColor Color]]##. ##//color//## is graphics mode specific, see ##[[KeyPgColor Color]]## and ##[[KeyPgScreengraphics Screen (Graphics)]]## for details. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/preset.bas"}}%%(freebasic) SCREEN 13 'Set background color to 15 COLOR , 15 'Draw a pixel with the background color at 10, 10 PRESET (10,10) 'Draw a pixel with the background color at Last x cord +10, Last y cord +10 PRESET Step (10,10) SLEEP %% {{fbdoc item="diff"}} - ##//target//## new to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgPset PSet]]## {{fbdoc item="back" value="CatPgGfx2D|2D Drawing Functions"}}{{fbdoc item="title" value="PRINT"}}---- Writes text to the screen {{fbdoc item="syntax"}}## **Print** [ //expressionlist// ] [ , | ; ] ## {{fbdoc item="param"}} ##//expressionlist//## list of items to print {{fbdoc item="desc"}} ##**Print**## outputs a list of values to the screen. Numeric values are converted to their string representation, with left padding for the sign. Objects of user-defined types must overload ##Operator Cast () As String##. Consecutive values in the expression list are separated either by a comma (,) or semicolon (;). A comma indicates printing should take place at the next 14 column boundary, while a semicolon indicates values are printed with no space between them. A new-line character is printed after the values in the expression list unless the expression list is followed by a comma or semicolon. For more control over character style and text position in graphics modes, consider using ##[[KeyPgDrawString Draw String]]##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/console/print.bas"}}%%(freebasic) '' new-line PRINT "Hello World!" '' no new-line PRINT "Hello"; "World"; "!"; PRINT '' column separator PRINT "Hello!", "World!" %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, an extra space is printed after numbers. {{fbdoc item="diff"}} - None, when using QBASIC's variable types in //[[CompilerOptlang -lang qb]]//. - Unsigned numbers are printed without a space before them. - QB did not support casting for UDTs, so didn't allow them to be ##**Print**##ed. {{fbdoc item="see"}} - ##[[KeyPgPrintPp Print #]]## - ##[[KeyPgPrintusing Print Using]]## - ##[[KeyPgInput Input]]## - ##[[KeyPgWrite Write]]## - ##[[KeyPgDrawString Draw String]]## {{fbdoc item="back" value="CatPgConsole|Console Functions"}}{{fbdoc item="title" value="PRINT #"}}---- Writes a list of values to a file or device {{fbdoc item="syntax"}}## **Print #** //filenum//**,** [ //expressionlist// ] [ , | ; ] ## {{fbdoc item="param"}} ##//filenum//## The file number of a file or device. ##//expressionlist//## List of values to write. {{fbdoc item="desc"}} ##**Print #**## outputs a list of values to a text file or device. Numeric values are converted to their string representation, with left padding for the sign. Objects of user-defined types must overload ##Operator Cast () As String##. Consecutive values in the expression list are separated either by a comma (,) or semicolon (;). A comma indicates printing should take place at the next 14 column boundary, while a semicolon indicates values are printed with no space between them. Note that the comma (,) following the file number is still necessary, even if no expression list is given. A new-line character is printed after the values in the expression list unless the expression list is followed by a comma or semicolon. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/fileio/print.bas"}}%%(freebasic) open "bleh.dat" for output as #1 print #1, "abc def" print #1, 1234, 5678.901, "xyz zzz" close #1 %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, an extra space is printed after numbers. {{fbdoc item="diff"}} - None, when using QBASIC's variable types in //[[CompilerOptlang -lang qb]]//. - Unsigned numbers are printed without a space before them. - QB did not support casting for UDTs, so didn't allow them to be ##**Print**##ed. {{fbdoc item="see"}} - ##[[KeyPgPrintusingPp Print # Using]]## - ##[[KeyPgPrint Print]]## - ##[[KeyPgWrite Write #]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}}{{fbdoc item="title" value="PRINT USING"}}---- Outputs formatted text to the screen {{fbdoc item="syntax"}}## **Print Using** //formatstring// **;** [ //expressionlist// ] ## {{fbdoc item="param"}} ##//formatstring//## Format string to use. ##//expressionlist//## List of items to print. {{fbdoc item="desc"}} Print to screen various expressions using a format determined by the ##//formatstring//## parameter. Internally, ##**Print Using**## uses a buffer size of 2048 bytes, while it is highly unlikely that this buffer would be filled, it should be noted that output would be truncated should this limit be reached. If no expression list is given, nothing will be output (note that the semi-colon after the format string is still necessary, even if no expression list is given). The format string dictates how the expressions are to be formatted when output to the screen, indicated by the use of special marker characters. There are markers for formatting both string and numeric output: {{fbdoc item="section" value="String formatting"}} {{table columns="2" cellpadding="2" cells="Marker;Formatting;!;prints the first character of a string;\ \;prints as many characters of a string as occuppied between the pair \ \;&;prints the entire string"}} {{fbdoc item="section" value="Numeric formatting"}} {{table columns="2" cellpadding="2" cells="Marker;Formatting;#;placeholder for a digit;.; placed near # indicates place for the decimal point;+;prints the sign of the number when placed to the left of numeric formatting;^^^^;prints exponential notation when placed to the right of numeric formatting"}} All of the special marker characters can be escaped, or preceded, with the underscore character ##"_"##, allowing them to be printed directly (##"_!"## prints ##"!"##). If a numerical value can't be formatted in the form indicated by the format string, the formatting is ignored and the number is printed preceded by the percent ##"%"## character. E.g., the number ##2E+200## with a ##//formatstring//## of " ""##"".""##"" " would be printed as ##"%2E+200"##. All other characters within the format string are printed as they appear. The ##**Using**## keyword is used with a different meaning with the ##[[KeyPgPalette Palette]]## graphics command {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/console/print-using.bas"}}%%(freebasic) Print Using "The value is #.## seconds"; 1.019 Print Using "The ASCII code for the pound sign (_#) is ###"; asc("#") Print Using "The last day in the year is ## \ \"; 31, "December" %% will produce the output: %%The value is 1.02 seconds Number sign is # and its ASCII code is 35 The last day in the year is 31 Dec%% {{fbdoc item="diff"}} - In QB a not-to-be-formatted ##//expressionlist//## could be entered before the USING clause; {{fbdoc item="see"}} - ##[[KeyPgPrint Print]]## - ##[[KeyPgPrintusingPp Print # Using]]## - ##[[KeyPgPalette Palette]]## {{fbdoc item="back" value="CatPgConsole|Console Functions"}}{{fbdoc item="title" value="PRINT # USING"}}---- Outputs formatted text to a file or device {{fbdoc item="syntax"}}## **Print #** //filenum// **,** **Using** //formatstring// **;** [ //expressionlist// ] ## {{fbdoc item="param"}} ##//filenum//## A file number of an open file or device. ##//formatstring//## Format string to use. ##//expressionlist//## List of items to print, separated by commas or semi-colons. {{fbdoc item="desc"}} Output various expressions to a text file or device using a format determined by the ##//formatstring//## parameter. Internally, ##**Print Using**## uses a buffer size of 2048 bytes, while it is highly unlikely that this buffer would be filled, it should be noted that output would be truncated should this limit be reached. If no expression list is given, nothing will be output (note that the semi-colon after the format string is still necessary, even if no expression list is given). The format string dictates how the expressions are to be formatted when output, indicated by the use of special marker characters. There are markers for formatting both string and numeric output: {{fbdoc item="section" value="String formatting"}} {{table columns="2" cellpadding="2" cells="Marker;Formatting;!;prints the first character of a string;\ \;prints as many characters of a string as occuppied between the pair \ \;&;prints the entire string"}} {{fbdoc item="section" value="Numeric formatting"}} {{table columns="2" cellpadding="2" cells="Marker;Formatting;#;placeholder for a digit;.; placed near # indicates place for the decimal point;+;prints the sign of the number when placed to the left of numeric formatting;^^^^;prints exponential notation when placed to the right of numeric formatting"}} All of the special marker characters can be escaped, or preceded, with the underscore character ##"_"##, allowing them to be printed directly (##"_!"## prints ##"!"##). If a numerical value can't be formatted in the form indicated by the format string, the formatting is ignored and the number is printed preceded by the percent ##"%"## character. E.g., the number ##2E+200## with a ##//formatstring//## of " ""##"".""##"" " would be printed as ##"%2E+200"##. All other characters within the format string are printed as they appear. The ##**Using**## keyword is used with a different meaning with the ##[[KeyPgPalette Palette]]## graphics command {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/fileio/print-using.bas"}}%%(freebasic) const filename as string = "file.txt" dim filenum as integer = freefile() if 0 <> open(filename, for output, as filenum) then print "error opening " & filename & " for output." end -1 end if print #filenum, using "This file is called '&'"; filename print #filenum, "Some numerical values are:" print #filenum, using "'###', '+###.###'"; 123.456, -123.456 close(filenum) %% will produce the file: %% This file is called "file.txt" Some numerical values are: '123', '-123.456' %% {{fbdoc item="diff"}} - In QB a not-to-be-formatted ##//expressionlist//## could be entered before the ##**Using**## clause; {{fbdoc item="see"}} - ##[[KeyPgPrintPp Print #]]## - ##[[KeyPgLprint Lprint]]## - ##[[KeyPgPrintusing Print Using]]## - ##[[KeyPgPalette Palette]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}}{{fbdoc item="title" value="PRIVATE"}}---- Specifies a procedure having internal linkage {{fbdoc item="syntax"}}## **Private** [[KeyPgSub Sub]] //procedure_name// [[[KeyPgOverload Overload]]] [[[KeyPgCdecl Cdecl]]|[[KeyPgStdcall Stdcall]]|[[KeyPgPascal Pascal]]] [[[KeyPgAlias Alias]] //"""external_name"""//] [([//parameter_list//])] [[[KeyPgModuleConstructor Constructor]] [//priority//]] [[[KeyPgStatic Static]]] [[[KeyPgExport Export]]] //..procedure body..// [[KeyPgEnd End]] [[KeyPgSub Sub]] **Private** [[KeyPgFunction Function]] //procedure_name// [[[KeyPgOverload Overload]]] [[[KeyPgCdecl Cdecl]]|[[KeyPgStdcall Stdcall]]|[[KeyPgPascal Pascal]]] [[[KeyPgAlias Alias]] //"""external_name"""//] [([//parameter_list//])] [[KeyPgAs as]] //return_type// [[[KeyPgStatic Static]]] [[[KeyPgExport Export]]] //..procedure body..// [[KeyPgEnd End]] [[KeyPgFunction Function]] ## {{fbdoc item="desc"}} In procedure definitions, ##**Private**## specifies that a procedure has internal linkage, meaning it's name is not visible to external modules. The ##[[KeyPgOptionprivate Option Private]]## statement allows procedures to be defined with internal linkage by default. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/module/sub-private.bas"}}%%(freebasic) 'e.g. Private Sub i_am_private End Sub Sub i_am_public End Sub %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgPublic Public]]## - ##[[KeyPgOptionprivate Option Private]]## - ##[[KeyPgSub Sub]]## - ##[[KeyPgFunction Function]]## {{fbdoc item="back" value="CatPgModularizing|Modularizing"}}{{fbdoc item="back" value="CatPgProcedures|Procedures"}}{{fbdoc item="title" value="PROPERTY"}}---- Declares or defines a property in a type or class {{fbdoc item="syntax"}}## { [[KeyPgType Type]] | [[KeyPgClass Class]] } //typename// [[KeyPgDeclare declare]] **Property** //fieldname// () [[KeyPgAs as]] [[DataType datatype]] [[KeyPgDeclare declare]] **Property** //fieldname// ( [ [[KeyPgByref byref]] | [[KeyPgByval byval]] ] //new_value// [[KeyPgAs as]] [[DataType datatype]] ) [[KeyPgDeclare declare]] **Property** //fieldname// ( [ [[KeyPgByref byref]] | [[KeyPgByval byval]] ] //index// [[KeyPgAs as]] [[DataType datatype]] ) [[KeyPgAs as]] [[DataType datatype]] [[KeyPgDeclare declare]] **Property** //fieldname// ( [ [[KeyPgByref byref]] | [[KeyPgByval byval]] ] //index// [[KeyPgAs as]] [[DataType datatype]], [ [[KeyPgByref byref]] | [[KeyPgByval byval]] ] //new_value// [[KeyPgAs as]] [[DataType datatype]] ) End { [[KeyPgType Type]] | [[KeyPgClass Class]] } **Property** //typename//.//fieldname// () [[KeyPgAs as]] [[DataType datatype]] //statements// **End Property** **Property** //typename//.//fieldname// ( [ [[KeyPgByref byref]] | [[KeyPgByval byval]] ] //new_value// [[KeyPgAs as]] [[DataType datatype]] ) //statements// **End Property** **Property** //typename//.//fieldname// ( [ [[KeyPgByref byref]] | [[KeyPgByval byval]] ] //index// [[KeyPgAs as]] [[DataType datatype]] ) [[KeyPgAs as]] [[DataType datatype]] //statements// **End Property** **Property** //typename//.//fieldname// ( [ [[KeyPgByref byref]] | [[KeyPgByval byval]] ] //index// [[KeyPgAs as]] [[DataType datatype]], [ [[KeyPgByref byref]] | [[KeyPgByval byval]] ] //new_value// [[KeyPgAs as]] [[DataType datatype]] ) //statements// **End Property** ## {{fbdoc item="param"}} ##//typename//## name of the ##[[KeyPgType Type]]## or ##[[KeyPgClass Class]]## ##//fieldname//## name of the property ##//new_value//## the value passed to property to be assigned ##//index//## the property index value {{fbdoc item="desc"}} ##**Property**## fields are used to get and set values of a ##[[KeyPgType Type]]## or ##[[KeyPgClass Class]]## in the same way as other data fields except instead of a simple assignment to a field or a value retrieved from field, a procedure is executed. ##//typename//## is the name of the type for which the ##**Property**## method is declared and defined. Name resolution for ##//typename//## follows the same rules as procedures when used in a ##[[KeyPgNamespace Namespace]]##. A **Property** may optionally have one index parameter. When indexed, properties are accessed as Property(Index) = Value. A hidden ##[[KeyPgThis this]]## parameter having the same type as ##//typename//## is passed to the property procedure. ##[[KeyPgThis this]]## is used to access the fields of the ##[[KeyPgType Type]]## or ##[[KeyPgClass Class]]##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/udt/property.bas"}}%%(freebasic) type Vector2D as single x, y declare operator cast() as string declare property Length() as single declare property Length( byval new_length as single ) end type operator Vector2D.cast () as string return "(" + str(x) + ", " + str(y) + ")" end operator property Vector2D.Length() as single Length = sqr( x * x + y * y ) end property property Vector2D.Length( byval new_length as single ) dim m as single = Length if m <> 0 then '' new vector = old / length * new_length x *= new_length / m y *= new_length / m end if end property Dim a as Vector2D = ( 3, 4 ) print "a = "; a print "a.length = "; a.length print a.length = 10 print "a = "; a print "a.length = "; a.length %% Output: %% a = (3, 4) a.length = 5 a = (6, 8) a.length = 10 %% Property Indexing: {{fbdoc item="filename" value="examples/manual/udt/property2.bas"}}%%(freebasic) '' True/False Namespace BOOL Const FALSE = 0 Const TRUE = NOT FALSE End Namespace Type BitNum Num as uInteger '' Get/Set Properties each with an Index. Declare Property NumBit( ByVal Index as Integer ) as Integer Declare Property NumBit( ByVal Index as Integer, ByVal Value as Byte ) End Type '' Get a bit by it's index. Property BitNum.NumBit( ByVal Index as Integer ) as Integer Return Bit( This.Num, Index ) End Property '' Set a bit by it's index. Property BitNum.NumBit( ByVal Index as Integer, ByVal Value as Byte ) '' Make sure index is in Integer range. If Index >= ( Sizeof(This.Num) * 8 ) then Print "Out of uInteger Range!" exit property else If Index < 0 then exit property End if If Value = BOOL.FALSE then This.Num = BitReSet( This.Num, Index ) End if If Value = BOOL.TRUE then This.Num = BitSet( This.Num, Index ) End if End Property Dim as BitNum Foo Print "Testing property indexing with data types:" Print "FOO Number's Value: " & Foo.Num '' Set the bit in the number as true. Foo.NumBit(31) = BOOL.TRUE Print "Set the 31st bit of FOO" '' Print to see if our bit has been changed. Print "FOO Number's Value: " & Foo.Num Print "FOO 31st Bit Set? " & Foo.NumBit(31) sleep Print "" %% Output: %% Testing property indexing with data types: FOO Number's Value: 0 Set the 31st bit of FOO FOO Number's Value: 2147483648 FOO 31st Bit Set? -1 %% {{fbdoc item="see"}} - ##[[KeyPgType Class]]## - ##[[KeyPgType Type]]## {{fbdoc item="back" value="CatPgUserDefTypes|User Defined Types"}}{{fbdoc item="title" value="PSET"}}---- Plots a single pixel {{fbdoc item="syntax"}}## **PSet** [//target// ,] [STEP] (//x//, //y//) [,//color//] ## {{fbdoc item="param"}} ##//target//## specifies buffer to draw on. ##STEP## indicates that coordinates are relative ##(//x, y//)## coordinates of the pixel. ##//color//## the color attribute. {{fbdoc item="desc"}} ##//target//## specifies buffer to draw on. ##//target//## may be an image created with ##[[KeyPgImagecreate ImageCreate]]## or ##[[KeyPgGetgraphics Get (Graphics)]]##. If omitted, ##//target//## defaults to the screen's current work page. ##(//x, y//)## are the coordinates of the pixel. ##STEP## if present, indicates that ##(//x, y//)## coordinates are relative to the graphics cursor position. If omitted, ##(//x, y//)## are relative to the upper left-hand corner of ##//target//##. The x and y coordinates are affected by the last call to the ##[[KeyPgViewgraphics View (Graphics)]]## and ##[[KeyPgWindow Window]]## statements, and respect the current clipping region as set by the ##[[KeyPgViewgraphics View (Graphics)]]## statement. ##//color//## specifies the color attribute. If omitted, ##//color//## defaults to the current foreground color. See ##[[KeyPgColor Color]]##. ##//color//## is graphics mode specific, see ##[[KeyPgColor Color]]## and ##[[KeyPgScreengraphics Screen (Graphics)]]## for details. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/pset.bas"}}%%(freebasic) ' Set an appropriate Screen mode. Screen 14 ' Plot a pixel at the coordinates 100, 100, Color 15. (white) Pset (100, 100), 15 ' Confirm the operation. Locate 1: Print "Pixel plotted at 100, 100" ' Wait for a keypress. Sleep ' Plot another pixel at the coordinates 150, 150, Color 4. (red) Pset (150, 150), 4 ' Confirm the operation. Locate 1: Print "Pixel plotted at 150, 150" ' Wait for a keypress. Sleep ' Plot a third pixel relative to the second, Color 15. (white) ' This pixel is given the coordinates 60, 60. It will be placed ' at 60, 60 plus the previous coordinates (150, 150), thus plotting at 210, 210. Pset Step (60, 60), 15 ' Confirm the operation. Locate 1: Print "Pixel plotted at 150 + 60, 150 + 60" ' Wait for a keypress Sleep ' Close the program End %% {{fbdoc item="diff"}} - ##//target//## new to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgPoint Point]]## - ##[[KeyPgPreset PReset]]## - ##[[KeyPgViewgraphics View (Graphics)]]## - ##[[KeyPgWindow Window]]## {{fbdoc item="back" value="CatPgGfx2D|2D Drawing Functions"}}{{fbdoc item="title" value="PSET"}}---- Parameter to the ##[[KeyPgPutgraphics Put]]## graphics statement which selects ##[[KeyPgPset PSet]]## as the blitting method {{fbdoc item="syntax"}}## **Put** [ //target//, ] [ STEP ] ( //x//,//y// ), //source// [ ,( //x1//,//y1// )-( //x2//,//y2// ) ], **Pset** ## {{fbdoc item="param"}} ##**PSet**## Required. {{fbdoc item="desc"}} The ##**PSet**## method copies the source pixel values onto the destination pixels. This is the simplest ##[[KeyPgPutgraphics Put]]## method. The pixels in the destination buffer are directly overwritten with the pixels in the source buffer. No additional operations are done, and there are no color values that are treated as transparent. It has the same effect as ##[[KeyPgPset PSet]]ting## each pixel individually. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/put-pset.bas"}}%%(freebasic) '' set up a screen: 320 * 200, 16 bits per pixel screenres 320, 200, 16 line (0, 0)-(319, 199), rgb(0, 128, 255), bf '' set up an image with the mask color as the background. dim img as any ptr = imagecreate( 33, 33, rgb(255, 0, 255) ) circle img, (16, 16), 15, rgb(255, 255, 0), , , 1, f circle img, (10, 10), 3, rgb( 0, 0, 0), , , 2, f circle img, (23, 10), 3, rgb( 0, 0, 0), , , 2, f circle img, (16, 18), 10, rgb( 0, 0, 0), 3.14, 6.28 dim as integer x = 160 - 16, y = 100 - 16 '' Put the image with PSET put (x, y), img, pset '' free the image memory imagedestroy img '' wait for a keypress sleep %% {{image class="center" title="Put PSet example output" url="/images/putpset.png"}} {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgPset PSet]]## - ##[[KeyPgPutgraphics Put (Graphics)]]## {{fbdoc item="back" value="CatPgGfx2D|2D Drawing Functions"}}{{fbdoc item="title" value="PTR"}}---- A variable declaration type modifier {{fbdoc item="syntax"}}## [[KeyPgDim dim]] //symbolname// [[KeyPgAs as]] [[DataType DataType]] {**Ptr** | [[KeyPgPointer pointer]]} ## {{fbdoc item="desc"}} Declares a pointer variable. The same as ##[[KeyPgPointer Pointer]]##. ##[[KeyPgOpAt Operator @ (Address of)]]## operator or ##[[KeyPgOpVarptr Varptr]]## are used to take the address of a variable. The ##[[KeyPgOpValueOf Operator * (Value of)]]## operator is used to dereference the pointer, that is, access the actual value stored in the memory location the pointer is pointing at. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/datatype/ptr.bas"}}%%(freebasic) ' Create the pointer. Dim p As Integer Ptr ' Create an integer value that we will point to using pointer "p" Dim num As Integer = 98845 ' Point p towards the memory address that variable "num" occupies. p = @num ' Print the value stored in memory pointed to by pointer "p" Print "Pointer 'p' ="; *p Print ' Print the actual location in memory that pointer "p" points at. Print "Pointer 'p' points to memory location:" Print p %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Ptr""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgPointer Pointer]]## - ##[[KeyPgAllocate Allocate]]## {{fbdoc item="back" value="CatPgStdDataTypes|Standard Data Types"}}{{fbdoc item="title" value="PUBLIC"}}---- Specifies a procedure having external linkage. {{fbdoc item="syntax"}}## **Public** [[KeyPgSub Sub]] //procedure_name// [[[KeyPgOverload Overload]]] [[[KeyPgCdecl Cdecl]]|[[KeyPgStdcall Stdcall]]|[[KeyPgPascal Pascal]]] [[[KeyPgAlias Alias]] //"""external_name"""//] [([//parameter_list//])] [[[KeyPgModuleConstructor Constructor]] [//priority//]] [[[KeyPgStatic Static]]] [[[KeyPgExport Export]]] //..procedure body..// [[KeyPgEnd End]] [[KeyPgSub Sub]] **Public** [[KeyPgFunction Function]] //procedure_name// [[[KeyPgOverload Overload]]] [[[KeyPgCdecl Cdecl]]|[[KeyPgStdcall Stdcall]]|[[KeyPgPascal Pascal]]] [[[KeyPgAlias Alias]] //"""external_name"""//] [([//parameter_list//])] [[KeyPgAs as]] //return_type// [[[KeyPgStatic Static]]] [[[KeyPgExport Export]]] //..procedure body..// [[KeyPgEnd End]] [[KeyPgFunction Function]] ## {{fbdoc item="desc"}} In procedure definitions, ##**Public**## specifies that a procedure has external linkage, meaning it's name is visible to external modules. If ##**Public**## or ##[[KeyPgPrivate Private]]## is not specified, a procedure is defined as if ##**Public**## was specified. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/module/sub-public.bas"}}%%(freebasic) Private Sub i_am_private End Sub Public Sub i_am_public End Sub %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgPrivate Private]]## - ##[[KeyPgOptionprivate Option Private]]## - ##[[KeyPgSub Sub]]## - ##[[KeyPgFunction Function]]## {{fbdoc item="back" value="CatPgModularizing|Modularizing"}}{{fbdoc item="back" value="CatPgProcedures|Procedures"}}{{fbdoc item="title" value="PUT (File I/O)"}}---- Writes data from a buffer to a file {{fbdoc item="syntax"}}## **Put** #//filenum// [[KeyPgAs As]] [[KeyPgInteger integer]], [//position// [[KeyPgAs As]] [[KeyPgLongint longint]]], //data// [[KeyPgAs As]] [[KeyPgAny Any]] [, //amount// [[KeyPgAs As]] [[KeyPgInteger Integer]]] **Put** #//filenum// [[KeyPgAs As]] [[KeyPgInteger Integer]], [//position// [[KeyPgAs As]] [[KeyPgLongint longint]]], //data()// [[KeyPgAs As]] [[KeyPgAny Any]] ## {{fbdoc item="usage"}}## **Put** #//filenum//, //position//, //data// [, //amount//] varres = **Put** (#//filenum//, //position//, //data// [, //amount//]) ## {{fbdoc item="param"}} ##//filenum//## The value passed to ##[[KeyPgOpen Open]]## when the file was opened. ##//position//## Is the position where ##Put## must start in the file. If the file was opened ##For Random##, the position is in records, else it is given in bytes. If omitted, writing starts at the present file pointer position. The position is 1 based: the first record or byte of a file is at position 1. ##//data//## Is the buffer where data is written from. It can be a numeric variable, a string, an array or a user-defined type. The operation will try to transfer to disk the complete variable, unless ##//amount//## is given. When putting arrays, ##//data//## should be followed by an empty pair of brackets: "()". Put will write all of the data in the array. ##//amount//## is not allowed. ##//amount//## Makes ##Put## write to file ##//amount// * [[KeyPgSizeof Sizeof]](//buffer_datatype//)## bytes of data. If ##//amount//## is omitted, ##Put## just writes a single variable. {{fbdoc item="ret"}} 0 on success; nonzero on error. {{fbdoc item="desc"}} Writes binary data from a buffer variable to a file. ##**Put**## can be used as a function, and will return 0 on success or an error code on failure. For files opened in ##[[KeyPgRandom Random]]## mode, the size in bytes of the data to write must match the specified record size. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/fileio/put.bas"}}%%(freebasic) ' Create a integer variable Dim buffer As Integer, f as integer ' Find the first free file file number. f = Freefile ' Open the file "file.ext" for binary usage, using the file number "f". Open "file.ext" For Binary As #f buffer=10 ' Write 4 bytes from the buffer into the file, using file number "f" ' starting at the beginning of the file (1). Put #f, 1, buffer ' Close the file. Close #f ' End the program. End %% {{fbdoc item="filename" value="examples/manual/fileio/put-array.bas"}}%%(freebasic) ' Create an integer array Dim buffer(1 To 10) As Integer Dim i As Integer For i = 1 To 10 buffer(i) = i Next ' Find the first free file file number. Dim f As Integer f = Freefile ' Open the file "file.ext" for binary usage, using the file number "f". Open "file.ext" For Binary As #f ' Write the array into the file, using file number "f" ' starting at the beginning of the file (1). Put #f, 1, buffer() ' Close the file. Close #f ' End the program. End %% {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/fileio/put-buffer.bas"}}%%(freebasic) Dim As Byte Ptr lpBuffer Dim As Integer hFile, Counter, Size Size=256 lpBuffer=Allocate(Size) For Counter=0 to Size-1 lpBuffer[Counter]=(Counter and &HFF) Next ' Get free file file number. hFile = Freefile() ' Open the file "test.bin" in binary writing mode. Open "test.bin" For Binary Access Write As #hFile ' Write 256 bytes from the memory pointened by lpBuffer. Put #hFile, , lpBuffer[0],Size ' Close the file. Close #hFile ' Free the allocated memory. Deallocate lpBuffer ' End the program. End %% {{fbdoc item="diff"}} - PUT can write full arrays as in VB or, alternatively, write a multiple of the data size from //buffer//'s memory location. - PUT can now be used as a function. {{fbdoc item="see"}} - ##[[KeyPgOpen Open]]## - ##[[KeyPgClose Close]]## - ##[[KeyPgGetfileio Get (File I/O)]]## - ##[[KeyPgFreefile Freefile]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}}{{fbdoc item="title" value="PUT (GRAPHICS)"}}---- Copies an image on to another image or screen {{fbdoc item="syntax"}}## **Put** [ //target//, ] [ STEP ] ( //x//,//y// ), //source// [ ,( //x1//,//y1// )-[ STEP ]( //x2//,//y2// ) ] [ ,//method// [ ,( //alphaval//|//value//|//blender// [ ,//param//]) ] ] ## {{fbdoc item="param"}} ##//target//## is the address of the buffer where the image is to be drawn. If it's omitted, the image gets blitted to screen. See below. ##STEP## indicates that ##(//x//, //y//)## offsets are relative to the current graphics cursor position. ##(//x//, //y//)## specify offsets from the upper-left corner of the destination buffer, or screen, that the image gets drawn to. ##//source//## is the address of the buffer of the image to be drawn. See below. ##(//x1//, //y1//)-[ STEP ](//x2//, //y2//)## specify a rectangular area in the source buffer to draw. If omitted, the entire buffer is drawn. ##STEP## indicates that ##//x2//## and ##//y2//## are relative to ##//x1//## and ##//y1//##, respectively. ##//method//## specifies the method used to draw the image to the destination buffer, and can be any one of the following (the default method is ##XOR##): Background-independent methods ##[[KeyPgPsetGfx PSET]]## : Source pixel values are copied without modification. ##PRESET## : Source pixel values are 1's-complement negated before being copied. ##[[KeyPgTransGfx TRANS]]## : Source pixel values are copied without modification. Does not draw source pixels of mask color. See below. Background-dependent methods ##[[KeyPgAndGfx AND]]## : Destination pixels are bitwise ANDed with source pixels. See below. ##[[KeyPgOrGfx OR]]## : Destination pixels are bitwise ORed with source pixels. See below. ##[[KeyPgXorGfx XOR]]## : Destination pixels are bitwise XORed with source pixels. See below. ##[[KeyPgAlphaGfx ALPHA]]## : Source is blended with a transparency factor specified either in the ##//value//## parameter, or in the image's individual pixels. See below. ##[[KeyPgAddGfx ADD]]##: Source is multiplied by a value and added with saturation to the destination. See below. ##[[KeyPgCustomgfx CUSTOM]]## : Uses a user-defined function to perform blending the source with the destination. See below. ##//value//## is a 0-255 value specifying the transparency value for an ##ADD## or ##ALPHA## method blit. ##//blender//## specifies the address of a user-defined function to be called in a ##CUSTOM## method blit. See below. ##//param//## specifies a parameter to pass to the custom blender. {{fbdoc item="desc"}} The ##**Put**## statement can be used to draw an image onto another image. The ##//x//## and ##//y//## coordinates are affected by the last call to the ##[[KeyPgViewgraphics View]]## and ##[[KeyPgWindow Window]]## statements, and plotted image respects the current clipping region set by last call to the ##[[KeyPgViewgraphics View]]## statement. The source image is clipped if it is drawn outside the destination buffer. **Valid Image Buffers** The ##//source//## and ##//target//## image buffers must be valid image buffers. Valid image buffers are created using the ##[[KeyPgGetgraphics Get]]## or ##[[KeyPgImagecreate ImageCreate]]## statements. Valid image buffers can be specified in a ##**Put**## statement using an array name with optional index, or a pointer with optional index. **Drawing methods** Depending on the method used, the existing pixel values in the destination buffer are used to calculate the pixel values that are actually drawn. The ##PSET##, ##PRESET## and ##TRANS## methods do not use the destination buffer for calculating final pixel values, while the ##AND##, ##OR##, ##XOR##, ##ALPHA## and ##ADD## methods do. Images that are drawn with these latter methods will look differently depending on the content of the destination buffer. **Different pixel formats** The pixel format of an image buffer must be compatible with the current graphics mode color depth; that is, if you acquire an image using ##[[KeyPgGetgraphics Get]]## and you later change screen mode via the ##[[KeyPgScreengraphics Screen]]## statement, the image data may not be valid in the new graphics mode, and you may not be able to draw it on the screen. You should note however that you will always be able to draw image buffers onto other image buffers via ##**Put**## as long as these buffers were created with the same depth. The ##AND##, ##OR## and ##XOR## methods produce different results depending on the current color depth, as pixels are stored in different formats; see [[GfxInternalFormats Internal pixel formats]] for details. **Mask Color** The ##TRANS##, ##ALPHA## and ##ADD## methods do not draw pixels in the source image that use the mask color. The mask color depends on target (being it an image buffer or the screen) depth: in depths up to 8 bpp (paletted modes) it is equal to color index 0, while in hi/truecolor depths (15, 16, 24 and 32 bpp) it is equal to magenta, which is ##[[KeyPgRgb RGB]](255, 0, 255)##. Note that in 24/32 bpp modes the alpha value of a color does not affect the identification of the transparent color; only the lower 24 bits are used to identify it. See [[GfxInternalFormats Internal pixel formats]] for details. **Alpha drawing** The ##ALPHA## method can be used in two modes. If the ##//value//## parameter is specified, this is used to specify the level of transparency for the whole image to be drawn; a value of 0 will draw a completely transparent image, whereas a value of 255 will draw a completely solid one. This mode works only when drawing onto hi/truecolor targets (15, 16, 24 and 32 bpp). If the ##//value//## parameter is omitted, the ##ALPHA## method will take the alpha level value on a per-pixel basis, allowing to draw images with an alpha channel (certain parts of the image can be made more or less transparent than others). This mode works only with 32 bpp image buffers, as this is the only color depth that allows for an embedded alpha value in each pixel. **Dealing with the alpha channel** Normally ##**Put**## only allows to draw image buffers onto targets with the same depth, but there is an exception. When drawing an 8 bpp image buffer onto a 32 bpp target and the ##ALPHA## method is used, the 8 bpp source image is drawn into the alpha channel of the 32 bpp target. This allows to easily set the whole alpha channel of an image without having to deal with low level access of its pixel data. **Custom Blend Function** The ##CUSTOM## method uses a user-defined function to calculate the final pixel values to be drawn to the destination buffer. This function will be called once for every pixel of the source image, and will receive the source and destination pixel values, and a data pointer passed by the ##**Put**## function. The pixel value returned will be the value used to draw to the destination buffer. The function has the form: ##[[KeyPgDeclare declare]] [[KeyPgFunction function]] //identifier// ( [[KeyPgByval byval]] //source_pixel// [[KeyPgAs as]] [[KeyPgUinteger uinteger]], [[KeyPgByval byval]] //destination_pixel// [[KeyPgAs as]] [[KeyPgUinteger uinteger]], [[KeyPgByval byval]] //parameter// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]]) [[KeyPgAs as]] [[KeyPgUinteger uinteger]]## ##//identifier//## is the name of the function. Can be anything. ##//source_pixel//## is the current pixel value of the source image. ##//destination_pixel//## is the current pixel value of the destination image. ##//parameter//## is the parameter that is passed by the ##**Put**## command. It should be a data ##[[KeyPgPtr Pointer]]##. If omitted, its value will be zero. {{fbdoc item="ex"}} The following program gives a simple example of how to ##**Put**## an image to the screen, including setting up an image buffer, and freeing its memory after. {{fbdoc item="filename" value="examples/manual/gfx/put.bas"}}%%(freebasic) '' set up the screen and fill the background with a color screenres 320, 200, 32 paint (0, 0), rgb(64, 128, 255) '' set up an image and draw something in it dim img as any ptr = imagecreate( 32, 32, rgb(255, 0, 255) ) circle img, (16, 16), 15, rgb(255, 255, 0), , , 1, f circle img, (10, 10), 3, rgb( 0, 0, 0), , , 2, f circle img, (23, 10), 3, rgb( 0, 0, 0), , , 2, f circle img, (16, 18), 10, rgb( 0, 0, 0), 3.14, 6.28 '' PUT the image in the center of the screen put (160 - 16, 100 - 16), img, trans '' free the image memory imagedestroy img '' wait for a keypress sleep %% {{image class="center" title="Simple Put example output" url="/images/putgfx1.png"}} The following example shows how to allocate memory for an image, draw that image using various methods, including a custom blender, and free the memory for the image: {{fbdoc item="filename" value="examples/manual/gfx/put-all.bas"}}%%(freebasic) declare function checkered_blend( byval src as uinteger, byval dest as uinteger, byval param as any ptr ) as uinteger screen 14, 32 '' set 320*240*32 gfx mode dim as any ptr sprite dim as integer counter = 0 sprite = ImageCreate( 32, 32 ) '' allocate memory for 32x32 sprite line sprite, ( 0, 0 )-( 31, 31 ), rgba(255, 0, 0, 64), bf '' draw a sprite ... line sprite, ( 4, 4 )-( 27, 27 ), rgba(255, 0, 0, 192), bf line sprite, ( 0, 0 )-( 31, 31 ), rgb(0, 255, 0), b line sprite, ( 8, 8 )-( 23, 23 ), rgba(255, 0, 255, 64), bf line sprite, ( 1, 1 )-( 30, 30 ), rgba(0, 0, 255, 192) line sprite, ( 30, 1 )-( 1, 30 ), rgba(0, 0, 255, 192) cls dim as integer i : for i = 0 to 63 '' draw the background line( i,0 )-( i,240 ), rgb( i * 4, i * 4, i * 4 ) next i '' demonstrate all drawing methods ... put( 8,14 ), sprite, pset put step( 16,20 ), sprite, preset put step( -16,20 ), sprite, and put step( 16,20 ), sprite, or put step( -16,20 ), sprite, xor put step( 16,20 ), sprite, trans put step( -16,20 ), sprite, alpha, 96 put step( 16,20 ), sprite, alpha put step( -16,20 ), sprite, add, 192 put step( 16,20 ), sprite, custom, @checkered_blend, @counter '' print a description near each demo draw string (100, 26), "<- pset" draw string step (0, 20), "<- preset" draw string step (0, 20), "<- and" draw string step (0, 20), "<- or" draw string step (0, 20), "<- xor" draw string step (0, 20), "<- trans" draw string step (0, 20), "<- alpha (uniform)" draw string step (0, 20), "<- alpha (per pixel)" draw string step (0, 20), "<- add" draw string step (0, 20), "<- custom" ImageDestroy( sprite ) '' free allocated memory for sprite sleep : end 0 '' custom blender function: chequered put function checkered_blend( byval src as uinteger, byval dest as uinteger, byval param as any ptr ) as uinteger dim as integer ptr counter dim as uinteger pixel counter = cast(integer ptr, param) pixel = iif(((*counter and 4) shr 2) xor ((*counter and 128) shr 7), src, dest) *counter += 1 return pixel end function %% {{image class="center" title="Put example output" url="/images/putgfx2.png"}} {{fbdoc item="diff"}} - The ##TRANS##, ##ALPHA##, ##ADD## and ##CUSTOM## methods are new to FreeBASIC. - In QB, the destination was always the screen. - QB throws a run-time error instead of clipping out of bounds images. - In QB, only arrays can be specified as source images. {{fbdoc item="see"}} - ##[[KeyPgPutfileio Put (File I/O)]]## - ##[[KeyPgGetgraphics Get (Graphics)]]## - ##[[KeyPgImagecreate ImageCreate]]## - ##[[KeyPgAlphaGfx Alpha]]## - [[GfxInternalFormats Internal pixel formats]] {{fbdoc item="back" value="CatPgGfx2D|2D Drawing Functions"}}{{fbdoc item="title" value="RANDOM"}}---- Specifies file or device to be opened for binary mode {{fbdoc item="syntax"}}## [[KeyPgOpen Open]] //filename// for **Random** [[[KeyPgAccess Access]] //access_type//] [[[KeyPgLock Lock]] //lock_type//] as [#]//filenum// [Len = //record_length//] ## {{fbdoc item="param"}} ##//filename//## file name to open ##//access_type//## indicates whether the file may be read from, written to or both ##//lock_type//## locking to be used while the file is open ##//filenum//## unused file number to associate with the open file ##//record_length//## the size of the record used for the file {{fbdoc item="desc"}} Opens a file or device for reading and/or writing binary data in the given file ##//filenum//##, with records of size ##//record_length//##. If the file does not exist, a new file will be created. The file pointer is initialized by ##[[KeyPgOpen Open]]## at record number 1. File operations move the file pointer in ##//record_length//## steps. The data existing in the file is preserved by ##[[KeyPgOpen Open]]##. This file mode uses an user-defined ##[[KeyPgType Type]]## buffer variable to read/write full records in a file. The buffer variable uses to include several fields. The data is saved in binary mode, in the same internal format FreeBASIC uses, by means of ##[[KeyPgGetfileio Get #]]## and ##[[KeyPgPutfileio Put #]]##. ##//filename//## must be string expression resulting in a legal file name in the target OS, without wildcards. The file will be sought for in the present directory, unless a path is given. ##//Access_type//## - By default ##**Random**## mode allows to both read and write the file, unless an ##[[KeyPgAccess Access]]## type is specified, it must be one of: - ##**Read**## - the file is opened for input only - ##**Write**## - the file is opened for output only - ##**Read Write**## - the file is opened for input and output (the default) ##//Lock_type//## indicates the way the file is locked for other processes (users or threads), it is one of: - ##**Shared**## - The file can be freely accessed by other processes - ##**Lock Read**## - The file can't be opened simultaneously for reading - ##**Lock Write**## - The file can't be opened simultaneously for writing - ##**Lock Read Write**## - The file cannot be opened simultaneously by other processes. If no lock type is stated, the file will be ##**Shared**## for other threads of the program and ##**Lock Read Write**## for other programs. ##[[KeyPgLock Lock]]## and ##[[KeyPgUnlock Unlock]]## can be used to restrict temporally access to parts of a file. ##//filenum//## is a valid FreeBASIC file number (in the range 1-255) not being used for any other file presently open. This number identifies the file for the rest of file operations. A free file number can be found using the [[KeyPgFreefile FREEFILE]] function. ##//record_length//## is the amount of bytes the file pointer will move for each individual ##[[KeyPgGetfileio Get]]## and ##[[KeyPgPutfileio Put]]##, it must match the size of the buffer variable used when ##[[KeyPgGetfileio Get]]##ting and ##[[KeyPgPutfileio Put]]##ting data. If omitted, it defaults to 128. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/math/random.bas"}}%%(freebasic) dim ff as ubyte dim randomvar as integer ff = freefile open "testfile" for random as #ff write #ff, int(rnd * 42) close #ff open "testfile" for random as #ff input #ff, randomvar close #ff print "Random Number was: ", randomvar %% {{fbdoc item="diff"}} - In QB, String-contained runtime user defined types (UDT) are not implemented in FreeBASIC. - The keyword ##[[KeyPgField Field]]## is used with ##[[KeyPgType TYPE]]## to specify the packing of the UDT. {{fbdoc item="see"}} - ##[[KeyPgOpen Open]]## - ##[[KeyPgBinary Binary]]## - ##[[KeyPgPutfileio Put #]]## - ##[[KeyPgGetfileio Get #]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}}{{fbdoc item="title" value="RANDOMIZE"}}---- Seeds the random number generator {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Randomize** ( [[KeyPgByval byval]] //seed// [[KeyPgAs as]] [[KeyPgDouble double]] = -1.0, [[KeyPgByval byval]] //algorithm// [[KeyPgAs as]] [[KeyPgInteger integer]] = 0 ) ## {{fbdoc item="usage"}}## **Randomize** [ //seed// ][, //algorithm// ] ## {{fbdoc item="param"}} ##//seed//## A ##[[KeyPgDouble double]]## seed value for the random number generator. If omitted or set to ##-1.0##, the ##[[KeyPgTimer Timer]]## value will be used instead. ##//algorithm//## An ##[[KeyPgInteger integer]]## value to select the algorithm used. If omitted, the default algorithm for the current [[CompilerDialects language dialect]] is used. {{fbdoc item="desc"}} Sets the random seed that helps ##[[KeyPgRnd Rnd]]## generate random numbers, and selects the algorithm to use. Valid values for ##//algorithm//## are: ##**0**## - Default for current [[CompilerDialects language dialect]]. This is algorithm ##3## in the //[[CompilerOptlang -lang fb]]// dialect, ##4## in the //[[CompilerOptlang -lang qb]]// dialect and ##1## in the //[[CompilerOptlang -lang fblite]]// dialect. ##**1**## - Uses the C runtime library's ##rand()## function. This will give different results depending on the platform. ##**2**## - Uses a fast implementation. This should be stable across all platforms, and provides 32-bit granularity, reasonable degree of randomness. ##**3**## - Uses the Mersenne Twister. This should be stable across all platforms, provides 32-bit granularity, and gives a high degree of randomness. ##**4**## - Uses a QB compatible function. This should be stable across all platforms, and provides 24-bit precision, with a low degree of randomness. For good results, using a seed that is not quite predictable should be used - for example, the value returned from ##[[KeyPgTimer Timer]]##. This should not be done too frequently though, because for the non-QB algorithms the integer value is used, so the seed will only change once a second, and calling ##**Randomize**## with the same seed will reset the sequence. When you call ##**Randomize**## in QB compatible mode, part of the old seed is retained. This means that if you call ##**Randomize**## several times with the same seed, you will **not** get the same sequence each time. To get a specific sequence in QB compatible mode, set the seed by calling ##[[KeyPgRnd Rnd]]## with a negative parameter. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/math/randomize.bas"}}%%(freebasic) '' Seed the RNG, which is set to C's rand(). randomize timer, 1 %% {{fbdoc item="diff"}} - Second parameter new to ""FreeBASIC"". {{fbdoc item="see"}} - ##[[KeyPgRnd Rnd]]## - ##[[KeyPgTimer Timer]]## - [[CompilerDialects Language dialects]] {{fbdoc item="back" value="CatPgMath|Mathematical Functions"}}{{fbdoc item="title" value="READ"}}---- Reads values stored with the ##[[KeyPgData Data]]## statement. {{fbdoc item="syntax"}}## **Read** //variable_list// ## {{fbdoc item="desc"}} Reads data stored in the application with the ##[[KeyPgData Data]]## command. The elements of the ##//variable_list//## must be of basic types, numeric, strings or elements of arrays and user defined types. All the ##[[KeyPgData Data]]## statements in the program behave as a single list, after the last element of a ##[[KeyPgData Data]]## statement is read, the first element of the following ##[[KeyPgData Data]]## statement will be read. If a ##**Read**## is attempted after the last element of the last data element, an error will occur. Data constants can only be of simple types (numeric or string). Alphanumeric string constants must be enclosed in quotes. A numeric value can be read as a numeric literal into a string. A string read into a numeric variable will be evaluated by the ##[[KeyPgVal Val]]## function. The ##[[KeyPgRestore Restore]]## statement resets the next-element pointer to the start of the ##[[KeyPgData Data]]## following the label. This allows to alter the order in which the data is read. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/data/read.bas"}}%%(freebasic) ' Create an array of 5 integers and a string to hold the data. DIM h(4) AS INTEGER DIM hs AS STRING DIM read_data as INTEGER ' Set up to loop 5 times (for 5 numbers... check the data) FOR read_data = 0 TO 4 ' Read in an integer. READ h(read_data) ' Display it. PRINT "Number"; read_data;" = "; h(read_data) NEXT ' Spacer. PRINT ' Read in a string. READ hs ' Print it. PRINT "String = " + hs ' Await a keypress. SLEEP ' Exit program. END ' Block of data. DATA 3, 234, 4354, 23433, 87643, "Bye!" %% {{fbdoc item="lang"}} - The //[[CompilerOptlang -lang fb]]// and //[[CompilerOptlang -lang fblite]]// dialects consider data items as constant expressions that are evaluated during compilation and its result stored in the program. - The //[[CompilerOptlang -lang qb]]// dialect considers data items as literals and stores then without change, as in QB. {{fbdoc item="diff"}} - In FreeBASIC, alphabetic string literals now **must** be enclosed within quotation marks, in QB this was optional. - In QB, empty constant expressions evaluated to number 0 or to empty strings, in FreeBASIC they give a compile error. {{fbdoc item="see"}} - ##[[KeyPgData Data]]## - ##[[KeyPgRestore Restore]]## {{fbdoc item="back" value="CatPgMisc|Miscellaneous"}}{{fbdoc item="title" value="READ (File Access)"}}---- File access specifier {{fbdoc item="syntax"}}## Open //filename// As String For Binary Access **Read** As #//filenum// As Integer ## {{fbdoc item="desc"}} Specifier for the ##[[KeyPgAccess Access]]## clause in the ##[[KeyPgOpen Open]]## statement. ##**Read**## specifies that the file is accessible for input. {{fbdoc item="ex"}} See example at ##[[KeyPgAccess Access]]## {{fbdoc item="diff"}} - None known. {{fbdoc item="see"}} - ##[[KeyPgAccess Access]]## - ##[[KeyPgOpen Open]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:57:54 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 5651dd720568eb14b7a17f6395bc6ee8 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 641 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="READ WRITE (File Access)"}}---- File access specifier {{fbdoc item="syntax"}}## Open //filename// As String For Binary Access **Read Write** As #//filenum// As Integer ## {{fbdoc item="desc"}} Specifier for the ##[[KeyPgAccess Access]]## clause in the ##[[KeyPgOpen Open]]## statement. ##**Read Write**## specifies that the file is accessible for both input and output. {{fbdoc item="ex"}} See example at ##[[KeyPgAccess Access]]## {{fbdoc item="diff"}} - None known. {{fbdoc item="see"}} - ##[[KeyPgAccess Access]]## - ##[[KeyPgOpen Open]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}} {{fbdoc item="title" value="REALLOCATE"}}---- Reallocates storage for an existing reserved block of memory {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Reallocate**( //pointer// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]], //count// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] ## {{fbdoc item="usage"}}## //result// = **Reallocate**( //pointer//, //count// ) ## {{fbdoc item="param"}} ##//pointer//## The address of allocated memory to be reallocated. ##//count//## The number of bytes, in total, to be reallocated. {{fbdoc item="ret"}} The address of the reallocated memory. A null (0) pointer is returned if reallocation was unsuccessful, and the original memory pointed to by ##//pointer//## remains unchanged. {{fbdoc item="desc"}} Attempts to reallocate, or resize, memory previously allocated with ##[[KeyPgAllocate Allocate]]##. The contents of the buffer are preserved, although if ##//count//## is less than the original size of the memory block, the buffer will be truncated. If ##//pointer//## is null (0), then ##""ReAllocate""## behaves identically to ##[[KeyPgAllocate Allocate]]##. Reallocated memory must be deallocated, or freed, with ##[[KeyPgDeallocate Deallocate]]## when no longer needed. This function is not part of the FreeBASIC runtime library, it is an alias for the C runtime library's ##//realloc//##, so it's not guaranteed to be thread safe in all platforms. **NOTE**: Reallocating a pointer inside an object function, when that pointer contains the parent object of the function, is undefined, and will likely result in horrible crashes. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/memory/reallocate.bas"}}%%(freebasic) Dim a as Integer Ptr, b as Integer Ptr, i As Integer a = Allocate( 5 * len(Integer) ) ' Allocate memory for 5 integers For i = 0 to 4 a[i] = (i + 1) * 2 ' Assign integers to the buffer Next i b = ReAllocate( a, 10 * len(Integer) ) ' Reallocate memory for 5 additional integers For i = 5 to 9 b[i] = (i + 1) * 2 ' Assign more integers to the buffer Next i For i = 0 to 9 ' Print the integers Print b[i]; Next i Print Deallocate b ' Clean up %% ~Output is: ~<< 2 4 6 8 10 12 14 16 18 20>> ::c:: {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Reallocate""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgAllocate Allocate]]## - ##[[KeyPgCallocate Callocate]]## - ##[[KeyPgDeallocate Deallocate]]## {{fbdoc item="back" value="CatPgMemory|Memory Functions"}}{{fbdoc item="title" value="REDIM"}}---- Defines or resizes a variable-length array {{fbdoc item="syntax"}}## **Redim** [ [[KeyPgShared Shared]] ] [ [[KeyPgPreserve Preserve]] ] //symbolname//([//subscript// [, ...]]) As [[DataType datatype]] [, ...] **Redim** [ [[KeyPgShared Shared]] ] [ [[KeyPgPreserve Preserve]] ] As [[DataType datatype]] //symbolname//([//subscript// [, ...]]) [, ...] ## {{fbdoc item="param"}} ##[[KeyPgShared Shared]]## Specifies shared (file-scope) access to the array throughout the module. ##[[KeyPgPreserve Preserve]]## When used with an existing array, the contents of the array will be preserved during the resize. Note that ##[[KeyPgPreserve Preserve]]## will not work with multi-dimensional arrays. ##//symbolname//## A new or existing array id. ##//subscript//##: [ ##//lowerbound//## TO ] ##//upperbound//## The lower and upper bound range for a dimension of the array. Lower bound defaults to zero (0) if not specified. ##[[DataType datatype]]## The type of elements contained in the array. {{fbdoc item="desc"}} ##**Redim**## can be used to define new variable-length arrays, or resize existing variable-length arrays. ##**Redim**## always produces variable-length arrays, so, unlike ##[[KeyPgDim Dim]]##, variable-length arrays can be defined with constant subscripts. When defining a new variable-length array, its elements are default constructed. For simple data types like ##[[KeyPgInteger Integer]]## or ##[[KeyPgDouble Double]]##, the elements are initialized to zero (0). For user-defined types with a default constructor, that will be called. When a variable-length array is resized without the ##[[KeyPgPreserve Preserve]]## clause, it's elements are destroyed, and new elements are default constructed. The ##[[KeyPgPreserve Preserve]]## clause does not destroy existing elements unless the new size of the variable-length array is smaller than it was previously. When resizing an array larger, the new elements are default constructed at the end of the array. ##**Redim**## cannot be used on arrays contained in UDTs (user-defined ##[[KeyPgType Type]]##s), because currently only fixed-size arrays are supported in UDTs. **NOTE**: Using ##**Redim**## within a member procedure with an array that contains an instance of the object class is undefined, and will [hopefully] result in horrible crashes. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/array/redim.bas"}}%%(freebasic) '' Define a variable-length array with 5 elements '' ReDim array(1 To 5) As Integer For index As Integer = LBound(array) To UBound(array) array(index) = index Next '' Resize a variable-length array with 10 elements '' ReDim Preserve array(9) As Integer Print "index", "value" For index As Integer = LBound(array) To UBound(array) Print index, array(index) Next %% The previous program will produce the following output: %%index value 0 1 1 2 2 3 3 4 4 5 5 0 6 0 7 0 8 0 9 0 %% {{fbdoc item="diff"}} - ##[[KeyPgPreserve Preserve]]## is new to FreeBASIC. {{fbdoc item="see"}} - ##[[KeyPgCommon Common]]## - ##[[KeyPgDim Dim]]## - ##[[KeyPgErase Erase]]## - ##[[KeyPgExtern Extern]]## - ##[[KeyPgLbound Lbound]]## - ##[[KeyPgRedim Redim]]## - ##[[KeyPgPreserve Preserve]]## - ##[[KeyPgShared Shared]]## - ##[[KeyPgStatic Static]]## - ##[[KeyPgUbound Ubound]]## - ##[[KeyPgVar Var]]## {{fbdoc item="back" value="CatPgArray|Array Functions"}}{{fbdoc item="title" value="REM"}}---- Indicates comments in the source code. {{fbdoc item="syntax"}}## **Rem** comment ' Comment /' Multi-line comment '/ ## {{fbdoc item="desc"}} A source code line beginning with ##**Rem**## indicates that the line is a comment and will not be compiled. The single quote character (') may also be used to indicate a comment and may appear after other keywords on a source line. Multi-line comments are marked with the tokens ##**/'**## and ##**'/**##. All text between the two markers is considered comment text and is not compiled. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/misc/rem.bas"}}%%(freebasic) /' this is a multi line comment as a header of this example '/ Rem This Is a Single Line comment ' this is a single line comment ? "Hello" : Rem comment following a statement Dim a As Integer ' comment following a statement ? "FreeBASIC" : ' also acceptable Dim b As /' can comment in here also '/ Integer #if 0 This way of commenting Out code was required before version 0.16 #endif %% {{fbdoc item="diff"}} - Multiline comments new to FreeBASIC version 0.16 {{fbdoc item="see"}} - ##[[KeyPgPpif #if]]## {{fbdoc item="back" value="CatPgMisc|Miscellaneous"}}{{fbdoc item="title" value="RESET"}}---- Closes all open files, or resets standard I/O handles. {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Reset** ( ) [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Reset** ( [[KeyPgByval byval]] //streamno// [[KeyPgAs as]] [[KeyPgInteger integer]] ) ## {{fbdoc item="usage"}}## **Reset** //or// **Reset**( //streamno// ) ## {{fbdoc item="param"}} ##//streamno//## The stream number, 0 for stdin or 1 for stdout to reset. {{fbdoc item="desc"}} ##**Reset**##, when called with no arguments, closes all disk files. ##**Reset**##, when called with the ##//streamno//## argument, will reset the redirected or piped streams associated with stdin (0), or stdout (1). Passing any value for ##//streamno//## other than 0 or 1 has no effect. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/fileio/reset.bas"}}%%(freebasic) open "test.txt" for output as #1 print #1, "testing 123" reset %% {{fbdoc item="filename" value="examples/manual/fileio/resetio.bas"}}%%(freebasic) dim x as string '' Read from STDIN from piped input open cons for input as #1 while eof(1) = 0 input #1, x print """"; x; """" wend close #1 '' Reset to read from the keyboard Reset(0) print "Enter some text:" input x '' Read from STDIN (now from keyboard) open cons for input as #1 while eof(1) = 0 input #1, x print """"; x; """" wend close #1 %% {{fbdoc item="diff"}} - None for ##**Reset**()##. - The ##**Reset**(//streamno//)## usage is new to FreeBASIC. {{fbdoc item="see"}} - ##[[KeyPgClose Close]]## - ##[[KeyPgOpen Open]]## - ##[[KeyPgOpenCons Open Cons]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}}{{fbdoc item="title" value="RESTORE"}}---- Changes the next read location for values stored with the ##[[KeyPgData Data]]## statement. {{fbdoc item="syntax"}}## **Restore** //label// ## {{fbdoc item="desc"}} Sets the next-data-to-read pointer to the first element of the first ##[[KeyPgData Data]]## statement after the label. The label must be contained in the same module as the currently-executing code. ##Restore## alters the normal top to bottom order in which ##Data## are ##[[KeyPgRead Read]]##. It allows re-reading some ##Data## or using multiple sets of ##Data## in a single module. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/data/restore.bas"}}%%(freebasic) ' Create an 2 arrays of integers and a 2 strings to hold the data. Dim h(4) As Integer Dim h2(4) As Integer Dim hs As String Dim hs2 As String Dim read_data1 as integer Dim read_data2 as integer ' Set the data read to the label 'dat2:' Restore dat2 ' Set up to loop 5 times (for 5 numbers... check the data) For read_data1 = 0 To 4 ' Read in an integer. Read h(read_data1) ' Display it. Print "Bloc 1, number"; read_data1;" = "; h(read_data1) Next ' Spacer. Print ' Read in a string. Read hs ' Print it. Print "Bloc 1 string = " + hs ' Spacers. Print Print ' Set the data read to the label 'dat1:' Restore dat1 ' Set up to loop 5 times (for 5 numbers... check the data) For read_data2 = 0 To 4 ' Read in an integer. Read h2(read_data2) ' Display it. Print "Bloc 2, number"; read_data2;" = "; h2(read_data2) Next ' Spacer. Print ' Read in a string. Read hs2 ' Print it. Print "Bloc 2 string = " + hs2 ' Await a keypress. Sleep ' Exit program. End ' First block of data. dat1: Data 3, 234, 4354, 23433, 87643, "Bye!" ' Second block of data. dat2: Data 546, 7894, 4589, 64657, 34554, "Hi!" %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgData Data]]## - ##[[KeyPgRead Read]]## {{fbdoc item="back" value="CatPgMisc|Miscellaneous"}}{{fbdoc item="title" value="RESUME"}}---- Error handling statement to resume execution after a jump to an error handler {{fbdoc item="syntax"}}## **Resume** ## {{fbdoc item="desc"}} ##**Resume**## is used in the traditional QB error handling mechanism within an error handler (called by ##[[KeyPgOnerror On Error]]##) to return execution to the line that caused the error. Usually this is used after the error has been handled gracefully in order to try the previously erroneous operation again with corrected data. ##**Resume**## resets the ##[[KeyPgErr Err]]## value to 0 {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/error/resume.bas"}}%%(freebasic) '' Compile with -lang fblite or qb Dim As Single i, j On Error Goto ErrHandler i = 0 j = 1 / i ' this line causes a divide-by-zero error on the first try; execution jumps to ErrHandler label Print j ' after the value of i is corrected, prints 0.5 End ' end the program so that execution does not fall through to the error handler again ErrHandler: i = 2 Resume ' execution jumps back to 'j = 1 / i' line, which does not cause an error this time %% {{fbdoc item="lang"}} - ON ERROR is not supported in the //[[CompilerOptlang -lang fb]]// dialect. Statements can be used in its function form to return an error code {{fbdoc item="filename" value="examples/manual/check/KeyPgResume_1.bas"}}%%(freebasic) If Open( "text" For Input As #1 ) <> 0 Then Print "Unable to open file" End If %% {{fbdoc item="diff"}} - Does not accept line numbers or labels - Must compile with //[[CompilerOptex -ex]]// option {{fbdoc item="see"}} - ##[[KeyPgErr Err]]## - ##[[KeyPgResumenext Resume Next]]## - [[ProPgErrorHandling Error Handling]] {{fbdoc item="back" value="CatPgError|Error Handling Functions"}}{{fbdoc item="title" value="RESUME NEXT"}}---- Error handling statement to resume execution after a jump to an error handler {{fbdoc item="syntax"}}## **Resume Next** ## {{fbdoc item="desc"}} ##**Resume Next**## is used in the traditional QB error handling mechanism within an error handler (called by ##[[KeyPgOnerror On Error]]##) to return execution to the line after the one that caused the error. Usually this is used to avoid executing the same line and causing the error again. ##**Resume Next**## resets the ##[[KeyPgErr Err]]## value to 0 {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/error/resume-next.bas"}}%%(freebasic) '' Compile with -lang fblite or qb Dim As Single i, j On Error Goto ErrHandler i = 0 j = 5 j = 1 / i ' this line causes a divide-by-zero error; execution jumps to ErrHandler label Print "ending..." End ' end the program so that execution does not fall through to the error handler again ErrHandler: Resume Next ' execution jumps to 'Print "ending..."' line, but j is now in an undefined state %% {{fbdoc item="lang"}} - ON ERROR is not supported in the //[[CompilerOptlang -lang fb]]// dialect. Statements can be used in its function form to return an error code {{fbdoc item="filename" value="examples/manual/check/KeyPgResumenext_1.bas"}}%%(freebasic) If Open( "text" For Input As #1 ) <> 0 Then Print "Unable to open file" End If %% {{fbdoc item="diff"}} - Must compile with //[[CompilerOptex -ex]]// option {{fbdoc item="see"}} - ##[[KeyPgErr Err]]## - ##[[KeyPgResume Resume]]## - [[ProPgErrorHandling Error Handling]] {{fbdoc item="back" value="CatPgError|Error Handling Functions"}}{{fbdoc item="title" value="RETURN"}}---- Control flow statement to return from a procedure or ##[[KeyPgGosub Gosub]]##. {{fbdoc item="syntax"}}## **Return** [ //expression// ] //or// **Return** [ //label// ] ## {{fbdoc item="desc"}} ##**Return**## is used to return from a procedure or return from a gosub ##[[KeyPgGosub Gosub]]##. Because ##[[KeyPgReturn Return]]## could mean return-from-gosub or return-from-procedure, ##[[KeyPgOptiongosub Option Gosub]]## and ##[[KeyPgOptionnogosub Option Nogosub]]## can be used to enable and disable ##[[KeyPgGosub Gosub]]## support. When ##[[KeyPgGosub Gosub]]## support is disabled, ##[[KeyPgReturn Return]]## is then recognized as return-from-procedure. When ##[[KeyPgGosub Gosub]]## support is enabled, ##[[KeyPgReturn Return]]## is then recognized as return-from-gosub. ##**Return**## (from procedure) is used inside a procedure to exit the procedure possibly with a return value. A ##[[KeyPgSub Sub]]## cannot specify a return return value. In a ##[[KeyPgFunction Function]]##, ##**Return**## must specify its return value. ##**Return** //expression//## is equivalent to the ##Function = //expression// : [[KeyPgExit Exit]] Function## idiom. ##**Return**## (from gosub) is used to return control back to the statement immediately following a previous ##[[KeyPgGosub Gosub]]## call. When used in combination with ##[[KeyPgGosub Gosub]]##, no return value can be specified. If the optional ##//label//## is specified, execution continues at the specified label. If no ##[[KeyPgGosub Gosub]]## was made, a runtime error is generated, and execution continues immediately after ##**Return**##. A ##[[KeyPgGosub Gosub]]## should always have a matching ##**Return**## statement. However, if ##**Return**## (from gosub) is used where no ##[[KeyPgGosub Gosub]]## was made, a run-time error is generated. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/control/return.bas"}}%%(freebasic) '' Compile with -lang qb print "Let's Gosub!" gosub MyGosub print "Back from Gosub!" sleep end MyGosub: print "In Gosub!" return %% {{fbdoc item="filename" value="examples/manual/control/return2.bas"}}%%(freebasic) type rational_number '' simple rational number type numerator as integer denominator as integer end type type rational as rational_number '' type alias for clearer code '' multiplies two rational types (note: r1 remains unchanged due to the BYVAL option) function rational_multiply( r1 as rational, r2 as rational ) as rational r1.numerator *= r2.numerator '' multiply the divisors ... r1.denominator *= r2.denominator return r1 '' ... and return the rational end function dim as rational r1 = ( 6, 105 ) '' define some rationals r1 and r2 dim as rational r2 = ( 70, 4 ) dim as rational r3 r3 = rational_multiply( r1, r2 ) '' multiply and store the result in r3 '' display the expression (using STR to eliminate leading space when printing numeric types) print str( r1.numerator ) ; "/" ; str( r1.denominator ) ; " * " ; print str( r2.numerator ) ; "/" ; str( r2.denominator ) ; " = " ; print str( r3.numerator ) ; "/" ; str( r3.denominator ) sleep end 0 %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang fb]]// dialect ##**Return**## always means return-from-procedure. - In the //[[CompilerOptlang -lang qb]]// dialect, ##**Return**## means return-from-gosub by default unless changed with ##[[KeyPgOptionnogosub Option Nogosub]]##, in which case the compiler will recognize ##**Return**## as return-from-procedure. - In the //[[CompilerOptlang -lang fblite]]// dialect, ##**Return**## means return-from-procedure by default unless changed with ##[[KeyPgOptiongosub Option Gosub]]##, in which case the compiler will recognize ##**Return**## as return-from-gosub. {{fbdoc item="diff"}} - None when using the //[[CompilerOptlang -lang qb]]// dialect. {{fbdoc item="see"}} - ##[[KeyPgSub Sub]]## - ##[[KeyPgFunction Function]]## - ##[[KeyPgGosub Gosub]]## - ##[[KeyPgOptiongosub Option Gosub]]## - ##[[KeyPgOptionnogosub Option Nogosub]]## {{fbdoc item="back" value="CatPgControlFlow|Control Flow"}}{{fbdoc item="title" value="RGB"}}---- Computes a valid color value for hi/truecolor modes {{fbdoc item="syntax"}}## [[KeyPgPpdefine #define]] **RGB**(//r//,//g//,//b//) (([[KeyPgCuint cuint]](r) [[KeyPgOpShiftLeft shl]] 16) [[KeyPgOpOr or]] ([[KeyPgCuint cuint]](g) [[KeyPgOpShiftLeft shl]] 8) [[KeyPgOpOr or]] [[KeyPgCuint cuint]](b) [[KeyPgOpOr or]] &hFF000000) ## {{fbdoc item="usage"}}## //result// = **RGB**(//red//, //green//, //blue//) ## {{fbdoc item="param"}} ##//red//## red color component value ##//green//## green color component value ##//blue//## blue color component value {{fbdoc item="ret"}} The combined color. {{fbdoc item="desc"}} ##//red//##, ##//green//## and ##//blue//## are components ranging 0-255. The ##**RGB**## function can be used to compute a valid color value for use while in hi/truecolor modes. It returns an unsigned integer in the format ##&hAARRGGBB##, where ##RR##, ##GG## and ##BB## equal the values passed to this function, in hexadecimal format. ##AA## is the implicit alpha value and is automatically set to ##&hFF## (opaque). **Note for Windows API programmers**: The macro named RGB in the Windows references has been renamed BGR in the FB headers for Windows to avoid collisions. {{fbdoc item="ex"}} See ##[[KeyPgPutgraphics Put (Graphics)]]## example in addition. {{fbdoc item="filename" value="examples/manual/gfx/rgb.bas"}}%%(freebasic) ScreenRes 640,480,32 '32 bit color Line(0,0)-(319,479), Rgb(255,0,0) 'draws a bright red box on the left side of the window Line(639,0)-(320,479), Rgb(0,0,255) 'draws a bright blue box on the right side of the window Sleep 'wait before exiting %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgRgba RGBA]]## - ##[[KeyPgColor Color]]## {{fbdoc item="back" value="CatPgGfx2D|2D Drawing Functions"}} {{fbdoc item="title" value="RGBA"}}---- Computes a valid color value including alpha (transparency) for hi/truecolor modes {{fbdoc item="syntax"}}## [[KeyPgPpdefine #define]] **RGBA**(//r//,//g//,//b//,//a//) (([[KeyPgCuint cuint]](r) [[KeyPgOpShiftLeft shl]] 16) [[KeyPgOpOr or]] ([[KeyPgCuint cuint]](g) [[KeyPgOpShiftLeft shl]] 8) [[KeyPgOpOr or]] [[KeyPgCuint cuint]](b) [[KeyPgOpOr or]] ([[KeyPgCuint cuint]](a) [[KeyPgOpShiftLeft shl]] 24)) ## {{fbdoc item="usage"}}## //result// = **RGBA**(//red//, //green//, //blue//, //alpha//) ## {{fbdoc item="param"}} ##//red//## red color component value ##//green//## green color component value ##//blue//## blue color component value ##//alpha//## alpha component value {{fbdoc item="ret"}} the combined color {{fbdoc item="desc"}} ##//red//##, ##//green//##, ##//blue//## and ##//alpha//## are components ranging 0-255. The ##**RGBA**## function can be used to compute a valid color value including an alpha channel for use while in hi/truecolor modes. It returns an unsigned integer in the format ##&hAARRGGBB##, where ##RR##, ##GG##, ##BB##, ##AA## equal the values passed to this function, in hexadecimal format. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/rgba.bas"}}%%(freebasic) screenres 640,480,32 dim as any ptr img dim as integer x,y 'make an image that varies in transparency and color img = imagecreate(128,128,0) for x = 0 to 127 for y = 0 to 127 pset img,(x,y),rgba(x*2,0,y*2,x+y) next y next x circle img,(64,64),50,rgba(0,127,192,192),,,,f line img,(50,40)-(78,88),rgba(255,255,255,0),bf 'draw a background for x=-480 to 639 step 20 line (x,0)-(x+480,480),rgb(255,255,255) next line (10,10)-(630,86),rgb(127,0,0),bf line (10,290)-(630,438),rgb(0,127,0),bf 'draw the image and some text with PSET draw string(96,64),"PUT AN IMAGE WITH PSET" put(96,96),img,pset put(96,300),img,pset 'draw the image and some text with ALPHA draw string (416,64),"PUT AN IMAGE WITH ALPHA" put(416,96),img,alpha put(416,300),img,alpha sleep imagedestroy img %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgColor Color]]## - ##[[KeyPgRgb RGB]]## {{fbdoc item="back" value="CatPgGfx2D|2D Drawing Functions"}}{{fbdoc item="title" value="RIGHT"}}---- Returns the rightmost substring of a string {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Right** [[KeyPgOverload overload]] ( [[KeyPgByref byref]] //str// [[KeyPgAs as]] [[KeyPgString string]], [[KeyPgByval byval]] //n// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Right** ( [[KeyPgByref byref]] //str// [[KeyPgAs as]] [[KeyPgWstring wstring]], [[KeyPgByval byval]] //n// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] ## {{fbdoc item="usage"}}## //result// = **Right**[$]( //str//, //n// ) ## {{fbdoc item="param"}} ##//str//## The source string. ##//n//## The substring length, in characters. {{fbdoc item="ret"}} Returns the rightmost substring from ##//str//##. {{fbdoc item="desc"}} Returns the rightmost ##//n//## characters starting from the right (end) of ##//str//##. If ##//str//## is empty, then the null string (##"####"##) is returned. If ##//n// <= 0## then the null string (##"####"##) is returned. If ##//n// > len(//str//)## then the entire source string is returned. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/right.bas"}}%%(freebasic) dim text as string = "hello world" print right(text, 5) %% will produce the output: %%world %% An Unicode example: << dim text as wstring*20 text = "Привет, мир!" print right(text, 5) 'displays " мир!" <<::c:: {{fbdoc item="target"}} - DOS does not support the wide-character string version of **##Right##**. {{fbdoc item="lang"}} - The string type suffix "$" is obligatory in the //[[CompilerOptlang -lang qb]]// dialect. - The string type suffix "$" is optional in the //[[CompilerOptlang -lang fblite]]// and //[[CompilerOptlang -lang fb]]// dialects. {{fbdoc item="diff"}} - QB does not support Unicode. {{fbdoc item="see"}} - ##[[KeyPgLeft Left]]## - ##[[KeyPgMidfunction Mid (Function)]]## {{fbdoc item="back" value="CatPgString|String Functions"}}{{fbdoc item="title" value="RMDIR"}}---- Removes a folder/directory from the file system {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Rmdir** ( [[KeyPgByref byref]] //folder// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **Rmdir**( //folder// ) ## {{fbdoc item="param"}} ##//folder//## The folder/directory to be removed. {{fbdoc item="ret"}} Returns zero (0) on success, and negative one (-1) on failure. {{fbdoc item="desc"}} Removes a folder from the file system. The function will fail if the folder is not empty. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/system/rmdir.bas"}}%%(freebasic) Dim pathname As String = "foo\bar\baz" Dim result As Integer = RmDir( pathname ) If 0 <> result Then Print "error: unable to remove folder " & pathname & " in the current path." %% {{fbdoc item="target"}} - Linux requires the //folder// case matches the real name of the file. Windows and DOS are case insensitive. - Path separators in Linux are forward slashes / . Windows uses backward slashes \ but it allows for forward slashes . DOS uses backward \ slashes. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgShell Shell]]## - ##[[KeyPgChdir Chdir]]## - ##[[KeyPgMkdir Mkdir]]## {{fbdoc item="back" value="CatPgOpsys|Operating System Functions"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:58:07 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 7a5025ef0ad9665248ef54d98a1bafc4 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 3342 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="RND"}}---- Returns a random [[KeyPgDouble double]] precision number in the range ##[0, 1)## {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Rnd** ( [[KeyPgByval byval]] //seed// [[KeyPgAs as]] [[KeyPgSingle single]] = 1.0 ) [[KeyPgAs as]] [[KeyPgDouble double]] ## {{fbdoc item="usage"}}## //result// = **Rnd** ( //seed// ) ## {{fbdoc item="param"}} ##//number//## Optional ##[[KeyPgSingle single]]## argument. If ##//seed//## has a value of zero, the last random number generated is repeated, for any other number a new random number is returned. With the QB-compatible algorithm, a negative number fully reseeds the generator. The default for no argument is to return a new random number. {{fbdoc item="ret"}} Returns the random number generated. {{fbdoc item="desc"}} Returns a number of type ##[[KeyPgDouble double]]## in the range ##[0, 1)## (i.e. ##0 <= **Rnd** < 1##), based on a random seed (see ##[[KeyPgRandomize Randomize]]##). ##**Rnd**## can use a variety of different algorithms - see ##[[KeyPgRandomize Randomize]]## for details of the default and selectable algorithms. ##**Rnd**## will return the same sequence of numbers every time a program is run. This sequence can be changed by reseeding the generator. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/math/rnd.bas"}}%%(freebasic) '' Function to a random number in the range [first, last), or {first <= x < last}. function rnd_range (first as double, last as double) as double function = rnd * (last - first) + first end function '' seed the random number generator, so the sequence is not the same each time randomize '' prints a random number in the range [0, 1), or {0 <= x < 1}. print rnd '' prints a random number in the range [0, 10), or {0 <= x < 10}. print rnd * 10 '' prints a random integral number in the range [1, 11), or {1 <= x < 11}. '' with integers, this is equivalent to [1, 10], or {1 <= n <= 10}. print int(rnd * 10) + 1 '' prints a random integral number in the range [69, 421), or {69 <= x < 421}. '' this is equivalent to [69, 420], or {69 <= n <= 420}. print int(rnd_range(69, 421)) %% {{fbdoc item="lang"}} The default algorithm used depends on the current dialect in use: - With the //[[CompilerOptlang -lang fb]]// dialect, a 32 bit Mersenne Twister function with a granularity of 32 bits is used. - With the //[[CompilerOptlang -lang qb]]// dialect, a function giving the same output as ##**Rnd**## in QB is used. The granularity is 24 bits. - With the //[[CompilerOptlang -lang deprecated]]// and //[[CompilerOptlang -lang fblite]]// dialects, the function in the C runtime available in the system is used. The function available in Win32 has a granularity of 15 bits, and 32 bits in Linux and DOS. {{fbdoc item="diff"}} - None, if compiled in the //[[CompilerOptlang -lang qb]]// dialect. Other dialects can also use the same seeding and generating algorithms by calling ##[[KeyPgRandomize Randomize]]## with the appropriate parameter. - For the non-QB-compatible algorithms, if the optional argument is less than 0, it has the same meaning as passing an argument of 1. {{fbdoc item="see"}} - ##[[KeyPgRandomize Randomize]]## - ##[[KeyPgTimer Timer]]## - ##[[KeyPgInt Int]]## {{fbdoc item="back" value="CatPgMath|Math"}} {{fbdoc item="title" value="RSET"}}---- Right justifies a string in a string buffer {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Rset** [[KeyPgOverload overload]] ( [[KeyPgByref byref]] //dst// [[KeyPgAs as]] [[KeyPgString string]] , [[KeyPgByref byref]] //src// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Rset** ( [[KeyPgByval byval]] //dst// [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgPtr ptr]] , [[KeyPgByval byval]] //src// [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgPtr ptr]] ) ## {{fbdoc item="usage"}}## **Rset** //dst//, //src// ## {{fbdoc item="param"}} ##//dst//## A ##[[KeyPgString string]]## or ##[[KeyPgWstring wstring]]## buffer to copy the text into. ##//src//## The source ##[[KeyPgString string]]## or ##[[KeyPgWstring wstring]]## to be right justified. {{fbdoc item="desc"}} ##**Rset**## right justifies text into the string buffer ##//dst//##, filling the right part of the string with ##//src//## and the left part with spaces. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/rset.bas"}}%%(freebasic) dim buffer as string buffer = space(10) rset buffer, "91.5" print "-[" & buffer & "]-" %% {{fbdoc item="diff"}} - In QBasic the syntax was ##**Rset** //dst// = //src//## {{fbdoc item="see"}} - ##[[KeyPgLset Lset]]## - ##[[KeyPgSpace Space]]## - ##[[KeyPgPutfileio Put (File I/O)]]## - ##[[KeyPgMkd Mkd]]## - ##[[KeyPgMki Mki]]## - ##[[KeyPgMkl Mkl]]## - ##[[KeyPgMks Mks]]## {{fbdoc item="back" value="CatPgString|String Functions"}}{{fbdoc item="title" value="RTRIM"}}---- Removes surrounding substrings or characters on the right side of a string {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Rtrim** [[KeyPgOverload overload]] ( [[KeyPgByref byref]] //str// [[KeyPgAs as]] [[KeyPgString string]], [ **Any** ] [[KeyPgByref byref]] //trimset// [[KeyPgAs as]] [[KeyPgString string]] = " " ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Rtrim** ( [[KeyPgByref byref]] //str// [[KeyPgAs as]] [[KeyPgWstring wstring]], [ **Any** ] [[KeyPgByref byref]] //trimset// [[KeyPgAs as]] [[KeyPgWstring wstring]] = [[KeyPgWstr Wstr]](" ") ) [[KeyPgAs as]] [[KeyPgWstring wstring]] ## {{fbdoc item="usage"}}## //result// = **Rtrim**[$]( //str// [, [ **Any** ] //trimset// ] ) ## {{fbdoc item="param"}} ##//str//## The source string. ##//trimset//## The substring to trim. {{fbdoc item="ret"}} Returns the trimmed string. {{fbdoc item="desc"}} This procedure trims surrounding characters from the right (end) of a source string. Substrings matching ##//trimset//## will be trimmed if specified, otherwise spaces ([[CptAscii ASCII]] code 32) are trimmed. If the ##**Any**## keyword is used, any character matching a character in ##//trimset//## will be trimmed. All comparisons are case-sensitive. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/rtrim.bas"}}%%(freebasic) dim s1 as string = "Article 101 " print "'" + rtrim(s1) + "'" print "'" + rtrim(s1, " 01") + "'" print "'" + rtrim(s1, any " 10") + "'" dim s2 as string = "Test Pattern aaBBaaBaa" print "'" + rtrim(s2, "Baa") + "'" print "'" + rtrim(s2, any "Ba") + "'" %% will produce the output: %% 'Article 101' 'Article 101 ' 'Article' 'Test Pattern aaB' 'Test Pattern ' %% {{fbdoc item="lang"}} - DOS does not support the wide-character version of ##**Rtrim**##. - The string type suffix "$" is obligatory in the //[[CompilerOptlang -lang qb]]// dialect. - The string type suffix "$" is optional in the //[[CompilerOptlang -lang fblite]]// and //[[CompilerOptlang -lang fb]]// dialects. {{fbdoc item="diff"}} - QB does not support specifying a ##//trimset//## string or the ##ANY## clause. {{fbdoc item="see"}} - ##[[KeyPgLtrim Ltrim]]## - ##[[KeyPgTrim Trim]]## {{fbdoc item="back" value="CatPgString|String Functions"}}{{fbdoc item="title" value="RUN"}}---- Transfers execution to an external program {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub function]] **Run** ( [[KeyPgByref byref]] //program// [[KeyPgAs as]] [[KeyPgString string]], [[KeyPgByref byref]] //arguments// [[KeyPgAs as]] [[KeyPgString string]] = ##"####"## ) [[KeyPgAs as]] [[KeyPgString integer]] ## {{fbdoc item="usage"}}## //result// = **Run**( //program// [, //arguments// ] ) ## {{fbdoc item="param"}} ##//program//## The file name (including file path) of the program (executable) to transfer control to. ##//arguments//## The command-line arguments to be passed to the program. {{fbdoc item="ret"}} Returns negative one (-1) if the program could not be executed. {{fbdoc item="desc"}} Transfers control over to an external program. When the program exits, execution will return to the system. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/system/run.bas"}}%%(freebasic) '' Attempt to transfer control to "program.exe" in the current directory. Dim result As Integer = Run("program.exe") '' at this point, "program.exe" has failed to execute, and '' result will be set to -1. %% {{fbdoc item="target"}} - Linux requires the //program// case matches the real name of the file. Windows and DOS are case insensitive. The program being run may be case sensitive for its command line parameters. - Path separators in Linux are forward slashes / . Windows uses backward slashes \ but it allows for forward slashes . DOS uses backward \ slashes. {{fbdoc item="diff"}} - ##**Run**## needs the full executable name, including extension (##.exe##) on platforms that have one (Win32, DOS). - Returning an error code is new to FreeBASIC. {{fbdoc item="see"}} - ##[[KeyPgChain Chain]]## - ##[[KeyPgExec Exec]]## {{fbdoc item="back" value="CatPgOpsys|Operating System Functions"}}{{fbdoc item="title" value="SADD"}}---- Returns a pointer to a string variable's data {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] [[KeyPgOverload overload]] **Sadd** ( [[KeyPgByref byref]] //str// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Sadd** ( [[KeyPgByref byref]] //str// [[KeyPgAs as]] [[KeyPgWstring Wstring]] ) [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Sadd** ( [[KeyPgByref byref]] //str// [[KeyPgAs as]] [[KeyPgZstring Zstring]] ) [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] ## {{fbdoc item="usage"}}## //result// = **Sadd** ( //str// ) ## {{fbdoc item="param"}} ##//str//## the string expression or variable to get the address of {{fbdoc item="ret"}} A pointer to the data associated with ##//str//##. {{fbdoc item="desc"}} Returns the memory offset of the string data in the string variable. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/memory/sadd.bas"}}%%(freebasic) '' Compile with -lang qb or fblite Print SAdd(s$) s$ = "hello" Print SAdd(s$) s$ = "abcdefg, 1234567, 54321" Print SAdd(s$) Sleep %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgOpVarptr Varptr]]## {{fbdoc item="back" value="CatPgMemory|Memory Functions"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:58:16 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 2238fd8084b6aba86b2e7f031e859e73 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 1597 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="SCOPE...END SCOPE"}}---- Statement to begin a new scope block {{fbdoc item="syntax"}}## **Scope** [//statements//] **End Scope** ## {{fbdoc item="desc"}} The Scope block allows variables to be temporarily (re)defined and used in a program. When a variable is defined with ##[[KeyPgDim Dim]]## within a scope structure, that variable can be used until the end of the scope. During this time, any variables outside the scope that have the same name will be ignored, and will not be accessible by that name. Any statements in the Scope block before the variable is dimensioned will use the variable as defined outside the Scope. ##**Scope..End Scope**## is not permitted when compiling with in the //[[CompilerOptlang -lang qb]]// dialect. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/variable/scope.bas"}}%%(freebasic) Dim As Integer x = 5, y = 2 Print "x ="; x; ", "; "y ="; y Scope dim x as integer = 3 Print "x ="; x; ", "; "y ="; y Scope Dim y As Integer = 4 Print "x ="; x; ", "; "y ="; y End Scope End Scope Print "x ="; x; ", "; "y ="; y %% {{fbdoc item="lang"}} - Explicit SCOPE..END SCOPE blocks are available only in the //[[CompilerOptlang -lang fb]]// and //[[CompilerOptlang -lang deprecated]]// dialects. - Explicit SCOPE..END SCOPE blocks are not available in the //[[CompilerOptlang -lang fblite]]// and //[[CompilerOptlang -lang qb]]// dialects. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDim Dim]]## {{fbdoc item="back" value="CatPgVariables|Variable Declarations"}} {{fbdoc item="title" value="SCREEN (Console)"}}---- Gets the character or color attribute at a given location {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Screen** ( [[KeyPgByval byval]] row [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByval byval]] column [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByval byval]] colorflag [[KeyPgAs as]] [[KeyPgInteger integer]] = 0 ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **Screen**( //row//, //column// [, //colorflag// ] ) ## {{fbdoc item="param"}} ##//row//## 1-based offset from the top left corner of the console. ##//column//## 1-based offset from the top left corner of the console. ##//colorflag//## If equal to 0, the [[CptAscii ASCII]] code is returned, otherwise the color attribute is returned. If omitted, it defaults to 0. {{fbdoc item="ret"}} The [[CptAscii ASCII]] or color attribute of the character. {{fbdoc item="desc"}} ##**Screen**## returns the character or the color attribute found at a given position of a console output. It works in console mode and in graphics mode. The format of the color attribute depends on the current color depth: If the color type is a palette type with up to 4 bits per pixel (such as the Win32 console), then the color attribute is an 8-bit value, where the higher four bits hold the cell background color and the lower four bits hold the foreground (character) color. If the color type is an 8-bit palette, then the color attribute is a 16-bit value, where the high byte holds the background color and the low byte holds the foreground color. If the color type is full color, then the color attribute is a 32-bit integer, holding a single color value. If ##//colorflag//## is equal to 1, then the foreground color is returned; if ##//colorflag//## is equal to 2, then the background color is returned. The color values for the standard 16 color palette are: {{table columns="4" cellpadding="2" cells="Value;Color;Value;Color;0;Black;8;Gray;1;Blue;9;Bright Blue;2;Green;10;Bright Green;3;Cyan;11;Bright Cyan;4;Red;12;Bright Red;5;Magenta;13;Pink;6;Brown;14;Yellow;7;White;15;Bright White"}} {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/console/screen-func.bas"}}%%(freebasic) dim character_ascii_value as integer dim attribute as integer dim background as integer dim cell_color as integer dim row as integer, col as integer character_ascii_value = Screen( row, col ) attribute = Screen( row, col, 1 ) background = attribute shr 4 cell_color = attribute and &hf %% {{fbdoc item="filename" value="examples/manual/gfx/screen-func1.bas"}}%%(freebasic) '' open a graphics screen with 4 bits per pixel '' (alternatively, omit this line to use the console) screenres 320, 200, 4 '' print a character color 7, 1 print "A" dim as uinteger char, col, fg, bg '' get the ASCII value of the character we've just printed char = screen(1, 1, 0) ''get the color attributes col = screen(1, 1, 1) fg = col and &HF bg = (col shr 4) and &HF print using "ASCII value: ### (""!"")"; char; chr(char) print using "Foreground color: ##"; fg print using "Background color: ##"; bg sleep %% {{fbdoc item="filename" value="examples/manual/gfx/screen-func2.bas"}}%%(freebasic) '' open a graphics screen with 8 bits per pixel screenres 320, 200, 8 '' print a character color 30, 16 print "Z" dim as uinteger char, col, fg, bg '' get the ASCII value of the character we've just printed char = screen(1, 1, 0) ''get the color attributes col = screen(1, 1, 1) fg = col and &HFF bg = (col shr 8) and &HFF print using "ASCII value: ### (""!"")"; char; chr(char) print using "Foreground color: ###"; fg print using "Background color: ###"; bg sleep %% {{fbdoc item="filename" value="examples/manual/gfx/screen-func3.bas"}}%%(freebasic) '' open a full-color graphics screen screenres 320, 200, 32 '' print a character color rgb(255, 255, 0), rgb(0, 0, 255) 'yellow on blue print "M" dim as integer char, fg, bg '' get the ASCII value of the character we've just printed char = screen(1, 1, 0) ''get the color attributes fg = screen(1, 1, 1) bg = screen(1, 1, 2) print using "ASCII value: ### (""!"")"; char; chr(char) print using "Foreground color: &"; hex(fg, 8) print using "Background color: &"; hex(bg, 8) sleep %% {{fbdoc item="diff"}} {{fbdoc item="see"}} - ##[[KeyPgScreengraphics Screen (Graphics)]]## - ##[[KeyPgColor Color]]## {{fbdoc item="back" value="CatPgConsole|Console Functions"}}{{fbdoc item="title" value="SCREENCONTROL"}}---- Sets or gets internal graphics library settings {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **""ScreenControl""** ( [[KeyPgByval byval]] what [[KeyPgAs as]] [[KeyPgInteger integer]] [, [[KeyPgByref byref]] param1 [[KeyPgAs as]] [[KeyPgInteger integer]] [, [[KeyPgByref byref]] param2 [[KeyPgAs as]] [[KeyPgInteger integer]] [, [[KeyPgByref byref]] param3 [[KeyPgAs as]] [[KeyPgInteger integer]] [, [[KeyPgByref byref]] param4 [[KeyPgAs as]] [[KeyPgInteger integer]]]]]] ) [[KeyPgDeclare declare]] [[KeyPgSub sub]] **""ScreenControl""** ( [[KeyPgByval byval]] what [[KeyPgAs as]] [[KeyPgInteger integer]] [, [[KeyPgByref byref]] param [[KeyPgAs as]] [[KeyPgString string]]] ) ## {{fbdoc item="param"}} ##//what//## specifies the function to perform ##//param1//## optional first integer parameter, contains value to be set on entry or value got on exit ##//param2//## optional second integer parameter, contains value to be set on entry or value got on exit ##//param3//## optional third integer parameter, contains value to be set on entry or value got on exit ##//param4//## optional fourth integer parameter, contains value to be set on entry or value got on exit ##//param//## optional string parameter, contains text to be set on entry or text got on exit {{fbdoc item="desc"}} This function can be used to set or get internal GfxLib states. The ##//what//## parameter specifies which operation to perform. On operations that set states, the ##//param*//## parameters must contain the values to be set. On operations that get states, ##//param*//## will hold the values returned by GfxLib when the function returns. The meaning of the ##//param*//## parameters depend on the ##//what//## parameter, whose possible values are defined as constants in fbgfx.bi; below is a list of the supported ##//what//## values, along with the parameters associated with them. __Supported operations__ Note: * denotes operations that are allowed while a graphics mode has not yet been set via [[KeyPgScreengraphics Screen (Graphics)]] or [[KeyPgScreenres ScreenRes]]. For all other operations, return values are zero(0) or the empty string and the operation has no effect if a graphics mode is not available at call time. **Get operations** - ##GET_WINDOW_POS## (0) Returns the current window position, in desktop coordinates. [OUT] ##//param1//## x [OUT] ##//param2//## y - * ##GET_WINDOW_TITLE## (1) Returns the title of the program window. [OUT] ##//param//## title - ##GET_WINDOW_HANDLE## (2) Returns a handle to the program window. [OUT] ##//param1//## handle; this is a ##HWND## in Windows, a "Window" XID in X11 - * ##GET_DESKTOP_SIZE## (3) Returns the desktop size, in pixels. [OUT] ##//param1//## width [OUT] ##//param2//## height - ##GET_SCREEN_SIZE## (4) Returns the current screen size in pixels. [OUT] ##//param1//## width [OUT] ##//param2//## height - ##GET_SCREEN_DEPTH## (5) Returns current graphics mode screen depth. [OUT] ##//param1//## bits per pixel - ##GET_SCREEN_BPP## (6) Returns current graphics mode BPP. [OUT] ##//param1//## bytes per pixel - ##GET_SCREEN_PITCH## (7) Returns the current graphics mode framebuffer pitch, in bytes. [OUT] ##//param1//## pitch - ##GET_SCREEN_REFRESH## (8) Returns the current graphics mode refresh rate, in hertz. [OUT] ##//param1//## rate - ##GET_DRIVER_NAME## (9) Returns the current graphics mode driver name. [OUT] ##//param//## name - ##GET_TRANSPARENT_COLOR## (10) Returns the transparent color value for the current graphics mode depth. [OUT] ##//param1//## value - ##GET_VIEWPORT## (11) Returns the current viewport as set by the [[KeyPgViewgraphics View (Graphics)]] statement, in screen coordinates. [OUT] ##//param1//## x1 [OUT] ##//param2//## y1 [OUT] ##//param3//## x2 [OUT] ##//param4//## y2 - ##GET_PEN_POS## (12) Returns the last graphical pen position, in screen coordinates. This position is used in graphics functions supporting relative coordinates using the [[KeyPgStep Step]] keyword. [OUT] ##//param1//## x [OUT] ##//param2//## y - ##GET_COLOR## (13) Returns the current graphics mode color. [OUT] ##//param1//## foreground [OUT] ##//param2//## background - ##GET_ALPHA_PRIMITIVES## (14) Returns if primitives drawing support for alpha channel is enabled. [OUT] ##//param1//## TRUE (-1) if alpha primitives is enabled, FALSE (0) otherwise - ##GET_GL_EXTENSIONS## (15) Returns a string holding all supported GL extensions, or the empty string if not in OpenGL mode. [OUT] ##//param//## supported GL extensions - ##GET_HIGH_PRIORITY## (16) Returns if GFX_HIGH_PRIORITY was specified in the flags passed to ##[[KeyPgScreengraphics Screen]]## or ##[[KeyPgScreenres Screenres]]##. [OUT] ##//param1//## higher priority graphics processing enabled **Set operations** - ##SET_WINDOW_POS## (100) Sets the current program window position, in desktop coordinates. [IN] ##//param1//## x [IN] ##//param2//## y - * ##SET_WINDOW_TITLE## (101) Sets the current program window title. This is equivalent to calling ##[[KeyPgWindowtitle WindowTitle]]( //param// )##. [IN] ##//param//## title - ##SET_PEN_POS## (102) Sets the current graphical pen position, in screen coordinates. This position is used in graphics functions supporting relative coordinates using the [[KeyPgStep Step]] keyword. [IN] ##//param1//## x [IN] ##//param2//## y - * ##SET_DRIVER_NAME## (103) Sets the name of the internal graphics driver to be used in subsequent calls to ##[[KeyPgScreengraphics Screen]]## or ##[[KeyPgScreenres ScreenRes]]##. [IN] ##//param//## driver name - ##SET_ALPHA_PRIMITIVES## (104) Sets if primitives drawing should honor alpha channel. [IN] ##//param1//## enabled - * ##SET_GL_COLOR_BITS## (105) Sets the number of bits dedicated to the OpenGL color buffer [IN] ##//param1//## bits - * ##SET_GL_COLOR_RED_BITS## (106) Sets the number of bits dedicated to the red component of the OpenGL color buffer [IN] ##//param1//## bits - * ##SET_GL_COLOR_GREEN_BITS## (107) Sets the number of bits dedicated to the green component of the OpenGL color buffer [IN] ##//param1//## bits - * ##SET_GL_COLOR_BLUE_BITS## (108) Sets the number of bits dedicated to the blue component of the OpenGL color buffer [IN] ##//param1//## bits - * ##SET_GL_COLOR_ALPHA_BITS## (109) Sets the number of bits dedicated to the alpha component of the OpenGL color buffer [IN] ##//param1//## bits - * ##SET_GL_DEPTH_BITS## (110) Sets the number of bits dedicated to the OpenGL depth buffer [IN] ##//param1//## bits - * ##SET_GL_STENCIL_BITS## (111) Sets the number of bits dedicated to the OpenGL stencil buffer [IN] ##//param1//## bits - * ##SET_GL_ACCUM_BITS## (112) Sets the number of bits dedicated to the OpenGL accumulation buffer [IN] ##//param1//## bits - * ##SET_GL_ACCUM_RED_BITS## (113) Sets the number of bits dedicated to the red component of the OpenGL accumulation buffer [IN] ##//param1//## bits - * ##SET_GL_ACCUM_GREEN_BITS## (114) Sets the number of bits dedicated to the green component of the OpenGL accumulation buffer [IN] ##//param1//## bits - * ##SET_GL_ACCUM_BLUE_BITS## (115) Sets the number of bits dedicated to the blue component of the OpenGL accumulation buffer [IN] ##//param1//## bits - * ##SET_GL_ACCUM_ALPHA_BITS## (116) Sets the number of bits dedicated to the alpha component of the OpenGL accumulation buffer [IN] ##//param1//## bits - * ##SET_GL_NUM_SAMPLES## (117) Sets the number of samples to be used for OpenGL multisampling [IN] ##//param1//## samples **Other operations** - ##POLL_EVENTS## (200) Cause the library to poll all events, ie to check the system event queue, specifically used for retrieving keyboard and mouse events. This is most useful for OpenGL code where FLIP is not used, as normally FLIP will cause these events to be polled. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/screencontrol.bas"}}%%(freebasic) '' include fbgfx.bi for some useful definitions #include "fbgfx.bi" using fb dim e as EVENT dim as integer x, y, pressed, col dim as any ptr img screenres 384, 64, 32,, GFX_SHAPED_WINDOW '' create a fancy window shape img = imagecreate(48,8) draw string img, (0, 0), "GfxLib" for y = 0 to 63 for x = 0 to 383 col = point(x \ 8, y \ 8, img) if (col <> rgb(255, 0, 255)) then col = rgb((x + y) and &hFF, (x + y) and &hFF, (x + y) and &hFF) end if pset (x, y), col next x next y pressed = 0 do if (screenevent(@e)) then select case e.type case EVENT_MOUSE_BUTTON_PRESS pressed = -1 case EVENT_MOUSE_BUTTON_RELEASE pressed = 0 case EVENT_MOUSE_MOVE if (pressed) then screencontrol GET_WINDOW_POS, x, y screencontrol SET_WINDOW_POS, x + e.dx, y + e.dy end if end select end if sleep 5 loop while not multikey(1) %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Screencontrol""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgScreengraphics Screen (Graphics)]]## - ##[[KeyPgScreenevent ScreenEvent]]## - ##[[KeyPgScreeninfo ScreenInfo]]## - ##[[KeyPgWindowtitle WindowTitle]]## - ##[[KeyPgViewgraphics View (Graphics)]]## {{fbdoc item="back" value="CatPgGfxScreen|Screen Functions"}}{{fbdoc item="title" value="SCREENCOPY"}}---- Copies the contents of a graphical page into another graphical page {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Screencopy** ( [[KeyPgByval byval]] //frompage// [[KeyPgAs as]] [[KeyPgInteger integer]] = -1, [[KeyPgByval byval]] //topage// [[KeyPgAs as]] [[KeyPgInteger integer]] = -1 ) ## {{fbdoc item="usage"}}## **Screencopy** [ //from_page// ] [, //to_page// ] ## {{fbdoc item="param"}} ##//frompage//## page to copy from ##//topage//## page to copy to {{fbdoc item="desc"}} ##//from_page//## is the page to copy from. If this argument is omitted, the current work page is assumed. ##//to_page//## is the page to copy to. If this argument is omitted, the currently visible page is assumed. Page numbers range from 0 to the num_pages specified when setting the graphics mode minus 1 You can use this function to add a double buffer to your graphics. Any SCREEN mode supports this function; you must supply valid page numbers otherwise ##**Screencopy**## will have no effect. This function has two aliases: ##[[KeyPgFlip Flip]]## and ##[[KeyPgPcopy PCopy]]##. Example: See ##[[KeyPgScreenset Screenset]]## example. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/screencopy.bas"}}%%(freebasic) '' 320x200x8, with 3 pages screen 13,,3 '' image for page #1 screenset 1, 0 cls circle( 160, 100 ), 90, 1 ,,,, f circle( 160, 100 ), 90, 15 print "Press 2 to copy page #2 to visible page" print "Press escape to exit" '' image for page #2 screenset 2, 0 cls line( 50, 50 )-( 270, 150 ), 2, bf line( 50, 50 )-( 270, 150 ), 15, b print "Press 1 to copy page #1 to visible page" print "Press escape to exit" '' page #0 is the visible page screenset 0, 0 cls print "Press 1 to copy page #1 to visible page" print "Press 2 to copy page #2 to visible page" print "Press escape to exit" dim k as string do k = inkey select case k case chr(27) exit do case "1" screencopy 1, 0 case "2" screencopy 2, 0 end select sleep 25 loop %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Screencopy""**##. {{fbdoc item="diff"}} - New to FreeBASIC. QB had ##[[KeyPgPcopy Pcopy]]## to do the same function. {{fbdoc item="see"}} - ##[[KeyPgScreengraphics Screen (Graphics)]]## - ##[[KeyPgScreenres Screenres]]## - ##[[KeyPgScreenset Screenset]]## {{fbdoc item="back" value="CatPgGfxScreen|Screen Functions"}}{{fbdoc item="title" value="SCREENEVENT"}}---- Queries for and retrieves system events. {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""ScreenEvent""** ( [[KeyPgByval byval]] event [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] = 0 ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **""ScreenEvent""**( [ //event// ] ) ## {{fbdoc item="param"}} ##//event//## Specifies the buffer where the function should store the event data. {{fbdoc item="ret"}} Returns -1 if there are pending events to be retrieved, 0 otherwise. {{fbdoc item="desc"}} This function returns the latest available system event from the internal GfxLib events queue. By "event" we mean any mouse or keyboard activity for example. The event data (if available) will be copied into the buffer pointed to by the ##//event//## parameter; this buffer must currently be at least 5 integers long (20 bytes). The first integer will contain the event type ID, while the remaining 4 integers will hold sensitive data to the event type. The fbgfx.bi header file contains a definition of the ##EVENT## user data type, whose memory layout is compatible with the event data returned by this function; this can be used to ease the interpretation of the event data. Here we report the ##EVENT## structure for clarity: {{fbdoc item="filename" value="examples/manual/check/KeyPgScreenevent_1.bas"}}%%(freebasic) Type EVENT Field = 1 Type As Integer Union Type scancode As Integer ascii As Integer End Type Type x As Integer y As Integer dx As Integer dy As Integer End Type button As Integer z As Integer End Union End Type %% __Event types__ The event type is identified by an ID number returned into the first integer of the ##//event//## buffer (the ##.type## field in the ##EVENT## structure). Known event type IDs are: - EVENT_KEY_PRESS (1) A key was pressed on the keyboard. The ##.scancode## field contains the platform independent scancode value for the key; if the key has an ascii representation, it is held into the ##.ascii## field, which otherwise has a value of 0. - EVENT_KEY_RELEASE (2) A key was released on the keyboard. The ##.scancode## and ##.ascii## fields have the same meaning as with the EVENT_KEY_PRESS event. - EVENT_KEY_REPEAT (3) A key is being held down repeatedly. The ##.scancode## and ##.ascii## fields have the same meaning as with the EVENT_KEY_PRESS event. - EVENT_MOUSE_MOVE (4) The mouse was moved while it was on the program window. The ##.x## and ##.y## fields contain the new mouse position relative to the upper-left corner of the screen, while the ##.dx## and ##.dy## fields contain the motion deltas. - EVENT_MOUSE_BUTTON_PRESS (5) One of the mouse buttons was pressed. The ##.button## field has one bit set identifying the button that was pressed; bit 0 identifies the left mouse button, bit 1 the right mouse button and bit 2 the middle mouse button. - EVENT_MOUSE_BUTTON_RELEASE (6) One of the mouse buttons was released. The ##.button## field has the same meaning as with the EVENT_MOUSE_BUTTON_PRESS event. - EVENT_MOUSE_DOUBLE_CLICK (7) One of the mouse buttons was double clicked. The ##.button## field has the same meaning as with the EVENT_MOUSE_BUTTON_PRESS event. - EVENT_MOUSE_WHEEL (8) The mouse wheel was used; the new wheel position is returned into the ##.z## field. - EVENT_MOUSE_ENTER (9) The mouse was moved into the program window. - EVENT_MOUSE_EXIT (10) The mouse was moved out of the program window. - EVENT_WINDOW_GOT_FOCUS (11) The program window has got focus. - EVENT_WINDOW_LOST_FOCUS (12) The program window has lost focus. - EVENT_WINDOW_CLOSE (13) The user attempted to close the program window. __Querying for events__ The function returns -1 if there are pending events to be retrieved, 0 otherwise. If the ##//event//## parameter is set to 0 (the default if omitted) ##[[KeyPgScreenevent ScreenEvent]]## will not be able to copy the event data and it will not dequeue it from the internal events queue. Calling the function this way can be useful to check if there are pending events without actually fetching them. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/screenevent.bas"}}%%(freebasic) '' include fbgfx.bi for some useful definitions #include "fbgfx.bi" using fb dim e as EVENT screenres 640, 480 do if (screenevent(@e)) then select case e.type case EVENT_KEY_PRESS if (e.scancode = SC_ESCAPE) then end end if if (e.ascii > 0) then print "'" & e.ascii & "'"; else print "unknown key"; end if print " was pressed (scancode " & e.scancode & ")" case EVENT_KEY_RELEASE if (e.ascii > 0) then print "'" & e.ascii & "'"; else print "unknown key"; end if print " was released (scancode " & e.scancode & ")" case EVENT_KEY_REPEAT if (e.ascii > 0) then print "'" & e.ascii & "'"; else print "unknown key"; end if print " is being repeated (scancode " & e.scancode & ")" case EVENT_MOUSE_MOVE print "mouse moved to " & e.x & "," & e.y & " (delta " & e.dx & "," & e.dy & ")" case EVENT_MOUSE_BUTTON_PRESS if (e.button = BUTTON_LEFT) then print "left"; elseif (e.button = BUTTON_RIGHT) then print "right"; else print "middle"; end if print " button pressed" case EVENT_MOUSE_BUTTON_RELEASE if (e.button = BUTTON_LEFT) then print "left"; elseif (e.button = BUTTON_RIGHT) then print "right"; else print "middle"; end if print " button released" Case EVENT_MOUSE_DOUBLE_CLICK If (e.button = BUTTON_LEFT) Then Print "left"; Elseif (e.button = BUTTON_RIGHT) Then Print "right"; Else Print "middle"; End If Print " button double clicked" case EVENT_MOUSE_WHEEL print "mouse wheel moved to position " & e.z case EVENT_MOUSE_ENTER print "mouse moved into program window" case EVENT_MOUSE_EXIT print "mouse moved out of program window" case EVENT_WINDOW_GOT_FOCUS print "program window got focus" case EVENT_WINDOW_LOST_FOCUS print "program window lost focus" case EVENT_WINDOW_CLOSE end end select end if loop %% {{fbdoc item="target"}} - ##**Screenevent**## does not return window related events in the DOS version, but does return input events. {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgScreengraphics Screen (Graphics)]]## - ##[[KeyPgMultikey Multikey]]## - ##[[KeyPgGetmouse Getmouse]]## {{fbdoc item="back" value="CatPgGfxScreen|Screen Functions"}}{{fbdoc item="title" value="SCREENGLPROC"}}---- Gets the address of an OpenGL procedure {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""ScreenGLProc""** ( [[KeyPgByval byval]] procname [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] ## {{fbdoc item="param"}} ##//procname//## name of the procedure to retrieve the address of {{fbdoc item="desc"}} This function can be used to get the address of any OpenGL procedure, to be used to retrieve the pointers to new functions associated with OpenGL extensions. If given procedure named ##//procname//## cannot be found, ##**screenglproc**## will return NULL (0). {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/screenglproc.bas"}}%%(freebasic) '' include fbgfx.bi for some useful definitions #include "fbgfx.bi" dim SwapInterval as function(byval interval as integer) as integer dim extensions as string '' Setup OpenGL and retrieve supported extensions ScreenRes 640, 480, 32,, FB.GFX_OPENGL ScreenControl FB.GET_GL_EXTENSIONS, extensions if (instr(extensions, "WGL_EXT_swap_control") <> 0) then '' extension supported, retrieve proc address SwapInterval = ScreenGLProc("wglSwapIntervalEXT") if (SwapInterval <> 0) then '' Ok, we got it. Set OpenGL to wait for vertical sync on buffer swaps SwapInterval(1) end if end if %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Screenglproc""**##. {{fbdoc item="target"}} - Not available for DOS target. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgScreengraphics Screen (Graphics)]]## - ##[[KeyPgScreencontrol ScreenControl]]## {{fbdoc item="back" value="CatPgGfxScreen|Screen Functions"}}{{fbdoc item="title" value="SCREEN (GRAPHICS)"}}---- Initializes a graphics mode using QB-like mode numbers {{fbdoc item="syntax"}}## **Screen** //mode// [, [ //depth// ] [, [ //num_pages// ] [, [ //flags// ] [, [ //refresh_rate// ]]]]] ## {{fbdoc item="param"}} ##//mode//## is a QB style graphics screen mode number (see below). If ##//mode//## is 0, then any currently set graphics mode is closed, and all functions resume their normal console-mode functionality. See below for available modes. ##//depth//## is the color depth in bits per pixel. This only has an effect for modes 14 and higher. Values of 8, 16 and 32 are allowed. 15 and 24 are also allowed as aliases for 16 and 32, respectively. If omitted, it defaults to 8. ##//num_pages//## is the number of video pages you want, see below. If omitted, it defaults to 1. ##//flags//## Are used to select several things as graphics driver, fullscreen mode. There are constants predefined in the ##fbgfx.bi## file ready to use. See below for available flags. ##//refresh_rate//## requests a refresh rate. If it is not available in the present card or the parameter is omitted, FreeBASIC chooses the rate automatically. {{fbdoc item="desc"}} ##**Screen**## tells the compiler to link the GfxLib and initializes a QB-only, QB-on-GUI or OpenGL graphics mode, depending on the ##//flags//## setting. In QB-only modes a dumb window or fullscreen resolution is set, one or more buffers in standard memory are created, console commands are redirected to their graphic versions, a [[GfxDefPalettes default palette]] is set and an automatic screen refresh thread is started. QB-like graphics and console statements can be used. In QB-on-GUI modes one or more buffers in standard memory are created, console commands are redirected to their graphic versions and a [[GfxDefPalettes default palette]] is set. QB-like graphics and console statements can be used. Is up to the user to create a window and to refresh it with the contents of the graphics buffers. In OpenGL modes a dumb window or fullscreen resolution is set, one or more buffers in standard memory are created, and the OS's OpenGL library is initialized. From here OpenGL only OpenGL commands can be used; QB-like and console commands are forbidden. This allows to initialize OpenGL in a portable way; you can then also use [[KeyPgScreencontrol ScreenControl]] to properly customize the GL pixel format to be used before ##**Screen**## is called or to retrieve the list of supported OpenGL extensions after a mode has been set, and [[KeyPgScreenglproc ScreenGLProc]] to obtain extension function pointers. Any buffer that is created in standard memory uses one of three supported internal pixel formats, depending on the desired color depth; see [[GfxInternalFormats Internal pixel formats]] for details. If ##**Screen**## fails to set the required mode, an "Illegal function call" error is issued and the screen pointer is set to 0. Thus ##**Screen**## failures can be detected using standard ON ERROR processing or retrieving the screen pointer with ##[[KeyPgScreenptr Screenptr]]##. Before setting a fullscreen mode the program should check if that mode is available in the graphics card using ##[[KeyPgScreenlist Screenlist]]##. __mode details__ Available modes list: QB compatibility modes: {{table columns="6" cellpadding="1" cells="Mode nr;Resolution;Emulation;Text;char size;colors on screen;1;320x200;CGA ;40X25;8x8;16 background, 1 of four sets foreground;2;640x200;CGA;80x25;8x8;16 colors to 2 attributes;7;320x200;EGA;40x25;8x8;16 colors to 16 attributes;8;640x200;EGA;40x25;8x8;16 colors to 16 attributes;9;640x350;EGA;80x25 0r 80x43;8x14 or 8x8;16 colors to 16 attributes;11;640x480;VGA;80x30 or 80x60;8x16 or 8x8;256K colors to 2 attributes;12;640x480;VGA;80x30 or 80x60;8x16 or 8x8;256K colors to 16 attributes;13;320x200;MCGA;40X25;8X8;256K colors to 256 attributes"}} New FreeBASIC modes: {{table columns="6" cellpadding="1" cells="Mode nr;Resolution;Emulation;Text;char size;colors on screen;14;320x240;###;40x30;8x8;256K colors to 256 attributes or direct color; 15;400x300;###;50x37;8x8;256K colors to 256 attributes or direct color; 16;512x384;###;64x24 or 64x48;8x16 or 8x8;256K colors to 256 attributes or direct color;17;640x400;###;80x25 or 80x50;8x16 or 8x8;256K colors to 256 attributes or direct color;18;640x480;###;80x30 or 80x60;8x16 or 8x8;256K colors to 256 attributes or direct color; 19;800x600;###;100x37 or 100x75;8x16 or 8x8;256K colors to 256 attributes or direct color;20;1024x768;###;128x48 or 128x96;8x16 or 8x8;256K colors to 256 attributes or direct color; 21;1280x1024;###;160x64 or 160x128;8x16 or 8x8;256K colors to 256 attributes or direct color"}} __##depth## details__ For modes 14 and up, the depth parameter changes the color depth to the specified new one; if depth is not specified, these modes run in 8bpp. For modes 13 and below, depth has no effect. __##num_pages## details__ You can request any number of pages for any video mode; if you omit the parameter, only the visible page (number 0) will be available. A page is either the visible screen or an offscreen buffer, you can show a page while working on another one; see the ##[[KeyPgScreenset Screenset]]## statement for details. All pages are created in standard memory, the video card memory is never used for video buffering. __##flags## details:__ ~If flags are omitted, FreeBASIC uses QB-compatible graphics in windowed (except in DOS) mode. These constants are defined in ##fbgfx.bi## . Note that most of the flags are not supported in DOS. ~Available flags: ~__graphic mode flags__ ~~-GFX_NULL (-1) Starts a QB-on-GUI graphics mode. It creates a graphics buffer but not a window. User must implement the window, the events manager and and refresh screen as needed. This mode allows to mix FreeBASIC drawing functions with API-driven windows. This flag overrides all other mode flags. See an [[SrcPgGfxNull Example of GFX_NULL]] in Windows. ~~-GFX_OPENGL(&h02) Initializes OpenGL to draw in a dumb window. FreeBASIC graphic functions can't be used. The screen is not automatically updated, FLIP must be used. This option provides a portable way to initialize the OpenGL Library. ~~-If none of the above options is specified, FreeBASIC enters the QB-only graphics mode: it creates a buffer and a dumb window and sets a thread that automatically updates the screen and manages keyboard and mouse. The FreeBASIC drawing functions can be used. ~__window mode flags__ ~~Window mode flags are meaningless if GFX_NULL mode is used ~~-GFX_WINDOWED (&h00) ~~-GFX_FULLSCREEN (&h01) The graphics card switch mode is switched to the requested mode and color depth and OS fullscreen mode is used. If the mode is not available in the present card FreeBASIC switches to windowed mode. ~~-If GFX_FULLSCREEN is not specified, FreeBASIC opens a window of the requested size in the present desktop. ~~-GFX_NO_SWITCH (&h04) prevents the user from changing to fullscreen or to windowed mode by pressing Alt-Enter. ~~-GFX_NO_FRAME (&h08) creates a window without a border. ~~-GFX_SHAPED_WINDOW (&h10) creates transparent regions wherever RGBA(255, 0, 255, 0) is drawn on the screen. ~~-GFX_ALWAYS_ON_TOP (&h20) creates a window that stays always on top. ~__option flags__ ~~Flags working in any mode, they activate special behaviors ~~-GFX_ALPHA_PRIMITIVES (&h40) Tells the graphics library to enable alpha channel support for all drawing primitives. This means the alpha specified in a color value (via either the [[KeyPgRgba RGBA]] macro or direct color in the form &hAARRGGBB) will always be used by all primitives. ~~-GFX_HIGH_PRIORITY (&h80) Tells the graphics library to enable a higher priority for graphics processing. Only has an effect on ##gdi## and ##DirectX## drivers on Win32 platform. ~__OpenGL Buffer flags__ ~~These flags work only in OpenGL graphics mode, must be combined with GFX_OPENGL ~~-GFX_STENCIL_BUFFER (&h10000) Forces OpenGL to use Stencil buffer ~~-GFX_ACCUMULATION_BUFFER (&h20000) Forces OpenGL to use Accumulation buffer ~~-GFX_MULTISAMPLE (&h40000) Requests fullscreen anti-aliasing through the ARB_multisample extension Depending on if the fullscreen parameter is 0 or 1, ##**Screen**## will try to set the specified video mode in windowed or fullscreen mode, respectively. If fullscreen is 1 and the system cannot set specified mode in fullscreen, it'll try in windowed mode. If fullscreen is 0 and the system fails to open a window for specified mode, it'll try fullscreen. If everything fails, ##**Screen**## will have no effect and execution will resume from the statement following the ##**Screen**## call. You should take care of checking if a graphics mode has been set or not, and behave accordingly; a way to check if ##**Screen**## is successful is to test the return value of the ##[[KeyPgScreenptr Screenptr]]## function, have a look at it for details. __Graphics mode console__ Console commands (##[[KeyPgLocate Locate]]##, ##[[KeyPgPrint Print]]##), input can be used both with standard QB ##**Screen**## modes and with the extended ones too, provided the standard colordepth is not modified by using the second argument of ##**Screen**##. Where the table says more than one text resolution is available for the text mode, the required text resolution can be requested by using ##[[KeyPgWidth Width]]##. Characters printed will erase the background around them (no transparent background). __Other details__ While in windowed mode, clicking on the window close button will return ##[[KeyPgChr Chr]](255)+"k"##. Clicking on the maximize window button will switch to fullscreen mode if possible. A successful ##**Screen**## call sets currently visible and working pages both to page number 0, resets the palette to the specified mode one (see Default palettes), resets the clipping region to the size of the screen, disables custom coordinates mappings, moves the graphics cursor to the center of the screen, moves the text cursor to the top-left corner of the screen and sets foreground and background colors to bright white and black respectively. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/screen.bas"}}%%(freebasic) ' Sets fullscreen 640x480 with 32bpp color depth and 4 pages SCREEN 18, 32, 4, 1 IF SCREENPTR = 0 THEN PRINT "Error setting video mode!" END END IF %% {{fbdoc item="target"}} - In DOS, linear framebuffer or banked VESA VBE modes are used whenever possible; if not available, drivers for the standard VGA modes or a 320x240x8 ""ModeX"" driver are used if possible. Windowing and OpenGL related switches are not available. {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang fb]]// and //[[CompilerOptlang -lang fblite]]// dialects, the usage is: ##**Screen** //mode// [, [ //depth// ] [, [ //num_pages// ] [, [ //flags// ] [, [ //refresh_rate// ]]]]]## - In the //[[CompilerOptlang -lang qb]]// dialect, the usage is: ##**Screen** [//mode//] [,[//active_page//][,[//visible_page//]]]## {{fbdoc item="diff"}} - None in the //[[CompilerOptlang -lang qb]]// dialect. - In QB the syntax was ##**Screen** //mode//,//colormode//,//active_page//,//visible_page//##. Of those parameters FreeBASIC supports only //mode// and redefines the rest. The use of ##**Screen** ,,apage,vpage## to swap screen pages is only available in the //[[CompilerOptlang -lang qb]]// dialect. - ##[[KeyPgScreenset Screenset]]## should be used in the //[[CompilerOptlang -lang fb]]// and //[[CompilerOptlang -lang fblite]]// dialects. {{fbdoc item="see"}} - ##[[KeyPgScreenCons Screen (Console)]]## - ##[[KeyPgScreenres Screenres]]## Better (?) alternative for Screen - ##[[KeyPgScreenlist Screenlist]]## Check available modes - ##[[KeyPgScreencontrol Screencontrol]]## - ##[[KeyPgScreenlock Screenlock]]## - ##[[KeyPgScreenunlock Screenunlock]]## - ##[[KeyPgScreenptr Screenptr]]## Semi-low level access - ##[[KeyPgScreenset Screenset]]## - ##[[KeyPgScreencopy Screencopy]]## - ##[[KeyPgScreeninfo Screeninfo]]## - ##[[KeyPgScreenglproc Screenglproc]]## - ##[[GfxInternalFormats Internal pixel formats]]## {{fbdoc item="back" value="CatPgGfxScreen|Screen Functions"}}{{fbdoc item="title" value="SCREENINFO"}}---- Retrieves information about current video mode or the desktop. {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Screeninfo** ( [[KeyPgByref byref]] //w// [[KeyPgAs as]] [[KeyPgInteger integer]] = 0, [[KeyPgByref byref]] //h// [[KeyPgAs as]] [[KeyPgInteger integer]] = 0, [[KeyPgByref byref]] //depth// [[KeyPgAs as]] [[KeyPgInteger integer]] = 0, [[KeyPgByref byref]] //bpp// [[KeyPgAs as]] [[KeyPgInteger integer]] = 0, [[KeyPgByref byref]] //pitch// [[KeyPgAs as]] [[KeyPgInteger integer]] = 0, [[KeyPgByref byref]] //rate// [[KeyPgAs as]] [[KeyPgInteger integer]] = 0, [[KeyPgByref byref]] //driver// [[KeyPgAs as]] [[KeyPgString string]] = "####" ) ## {{fbdoc item="usage"}}## **Screeninfo** [ //w// ] [, [ //h// ] [, [ //depth// ] [ , [ //bpp// ] [ , [ //pitch// ] [ , [ //rate// ] [, //driver// ]]]]] ## {{fbdoc item="param"}} ##//w//## Width. ##//h//## Height. ##//depth//## Color depth in bits. ##//bpp//## Bytes per pixel. ##//pitch//## Bytes per scan line. ##//rate//## Refresh rate. ##//driver//## Driver name. {{fbdoc item="desc"}} This function can be useful to get current mode informations like graphics driver name, color depth, screen size and more. If ##**Screeninfo**## is called when no graphics mode is set, it returns the information about the desktop. Here's a description of available fields: {{table columns="2" cellpadding="1" cells="w;Width of the screen in pixels;h;Height of the screen in pixels;depth;Current pixel format bits per pixel: this can be 1, 2, 4, 8, 16, or 32;pitch;Size of a framebuffer row in bytes;rate;Current refresh rate, or 0 if unknown;driver;Name of current graphics driver in use, like DirectX or X11"}} {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/screeninfo.bas"}}%%(freebasic) dim w as integer, h as integer dim depth as integer dim driver_name as string SCREEN 15, 32 ' Obtain info about current mode SCREENINFO w, h, depth,,,,driver_name PRINT STR(w) + "x" + STR(h) + "x" + STR(depth); PRINT " using " + driver_name + " driver" SLEEP ' Quit graphics mode and obtain info about desktop SCREEN 0 SCREENINFO w, h, depth PRINT "Desktop running at " + STR(w) + "x" + STR(h) + "x" + STR(depth); %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Screeninfo""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgScreengraphics Screen (Graphics)]]## {{fbdoc item="back" value="CatPgGfxScreen|Screen Functions"}}{{fbdoc item="title" value="SCREENLIST"}}---- Finds available fullscreen video modes {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Screenlist** ( [[KeyPgByval byval]] //depth// [[KeyPgAs as]] [[KeyPgInteger integer]] = 0 ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **Screenlist**( [ //depth// ] ) ## {{fbdoc item="param"}} ##//depth//## the color depth for which the list of modes is requested (supported depths are 8, 15, 16, 24 and 32) {{fbdoc item="ret"}} returns 0, when there are no more resolutions to read. {{fbdoc item="desc"}} It works like the ##[[KeyPgDir Dir]]## function: the first call to the function requires the ##//depth//## parameter to be specified, it returns the lowest supported resolution for the requested depth. Further calls to ##**Screenlist**## without arguments returns the next resolutions. When no more resolutions are available, ##[[KeyPgScreenres Screenres]]## returns 0. The result of ##[[KeyPgScreenres Screenres]]## is encoded in an integer with the screen width as the high word and height and the height as the low word respectively. Resolutions are returned from lowest to highest supported ones. It is safe to call this function before any graphics mode has been set. {{fbdoc item="filename" value="examples/manual/gfx/screenlist.bas"}}%%(freebasic) Dim As Integer mode, w, h '' Find which 8bit resolutions are supported mode = ScreenList(8) While (mode) w = HiWord(mode) h = LoWord(mode) Print Str(w) + "x" + Str(h) mode = ScreenList Wend %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Screenlist""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgScreengraphics Screen]]## - ##[[KeyPgScreenres Screenres]]## {{fbdoc item="back" value="CatPgGfxScreen|Screen Functions"}}{{fbdoc item="title" value="SCREENLOCK"}}---- Locks the working page's framebuffer {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Screenlock** ( ) ## {{fbdoc item="usage"}}## **Screenlock** ## {{fbdoc item="desc"}} All FreeBASIC's Graphics Library functions draw to a framebuffer and an automatic routine copies the framebuffer to the actual screen memory at each draw. If the user program does a lot of drawing, the automatic refreshes may take a significant amount of time. The ##**Screenlock**## function locks the automatic refresh so several drawing operations may be done before the screen refresh is performed, thus increasing the speed of execution. Framebuffer memory may be freely accessed by using pointers (see [[KeyPgScreenptr ScreenPtr]]) ONLY while the screen is locked. Primitive graphics statements (LINE, PSET, DRAW STRING,...) may be used at any time. The screen refresh remains locked until the use of ##[[KeyPgScreenunlock Screenunlock]]## statement, which resumes it. While calls to ##**Screenlock**## should be paired with calls to ##**ScreenUnlock**## , the program keeps track of its internal status and there is no danger in ,for example, locking the screen twice in a row as only the first lock is performed. It is strongly recommended that the lock on a page be held for as short a time as possible. Only screen drawing should occur while the screen is locked, input/output and waiting must be avoided. In Win32 and Linux the screen is locked by stopping the thread that processes also the OS' events. If the screen is kept locked for a long time the event queue could overflow and make the system unstable. The automatic refresh takes place only in the visible page of the framebuffer. ##**Screenlock**## has no efect when drawing to pages other than the visible one. {{fbdoc item="ex"}} See ##[[KeyPgScreenptr Screenptr]]## example. {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Screenlock""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgScreengraphics Screen (Graphics)]]## - ##[[KeyPgScreenunlock Screenunlock]]## - ##[[KeyPgScreenptr Screenptr]]## {{fbdoc item="back" value="CatPgGfxScreen|Screen Functions"}}{{fbdoc item="title" value="SCREENPTR"}}---- Returns a pointer to the current work page's framebuffer {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Screenptr** ( ) [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] ## {{fbdoc item="usage"}}## //result// = **Screenptr** ## {{fbdoc item="ret"}} a pointer to the current work page framebuffer memory, or NULL (0) if no graphics mode is set. {{fbdoc item="desc"}} ##**Screenptr**## provides a way to directly read/write the working page's framebuffer. ##[[KeyPgScreenlock Screenlock]]## should be used before any read or writes are attempted. The pointer returned is valid up until any subsequent call to ##[[KeyPgScreengraphics Screen]]## or ##[[KeyPgScreenres Screenres]]##, which invalidates it. ##**Screenptr**## can also be used to test if a call to ##[[KeyPgScreengraphics Screen]]## or ##[[KeyPgScreenres Screenres]]## was successful, indicated by a non-NULL (<> 0) return value. In order to access a pixel in the screen buffer, you will need to know the screen's width, height, bytes per pixel and pitch (bytes per row). This information can be found out using ##[[KeyPgScreeninfo Screeninfo]]##. Each row in the frame buffer is ##//width//## * ##//pitch//## bytes long. The frame buffer consists of ##//height//## rows, stored in order of their position on the screen, running from top to bottom, left to right. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/screenptr.bas"}}%%(freebasic) Const SCREEN_WIDTH = 640, SCREEN_HEIGHT = 480 Dim As Integer w, h, bypp, pitch '' Make 8-bit screen. Screenres SCREEN_WIDTH, SCREEN_HEIGHT, 8 '' Get screen info (w and h should match the constants above, bypp should be 1) Screeninfo w, h, , bypp, pitch '' Get the address of the frame buffer. An Any Ptr '' is used here to allow simple pointer arithmetic Dim buffer As Any Ptr = Screenptr() If (buffer = 0) Then Print "Error: graphics screen not initialized." Sleep End -1 End If '' Lock the screen to allow direct framebuffer access Screenlock() '' Find the address of the pixel in the centre of the screen '' It's an 8-bit pixel, so use a UByte Ptr. Dim As Integer x = w \ 2, y = h \ 2 Dim As Ubyte Ptr pixel = buffer + (y * pitch) + (x * bypp) '' Set the pixel color to 10 (light green). *pixel = 10 '' Unlock the screen. Screenunlock() '' Wait for the user to press a key before closing the program Sleep %% {{fbdoc item="filename" value="examples/manual/gfx/screenptr2.bas"}}%%(freebasic) Const SCREEN_WIDTH = 256, SCREEN_HEIGHT = 256 Dim As Integer w, h, bypp, pitch '' Make 8-bit screen. ScreenRes SCREEN_WIDTH, SCREEN_HEIGHT, 32 '' Get screen info (w and h should match the constants above, bypp should be 4) ScreenInfo w, h, , bypp, pitch '' Get the address of the frame buffer. An Any Ptr '' is used here to allow simple pointer arithmetic Dim buffer As Any Ptr = Screenptr() If (buffer = 0) Then Print "Error: graphics screen not initialized." Sleep End -1 End If '' Lock the screen to allow direct framebuffer access ScreenLock() '' Set row address to the start of the buffer Dim As Any Ptr row = buffer '' Iterate over all the pixels in the screen: For y As Integer = 0 To h - 1 '' Set pixel address to the start of the row '' It's a 32-bit pixel, so use a UInteger Ptr Dim As UInteger Ptr pixel = row For x As Integer = 0 To w - 1 '' Set the pixel value *pixel = Rgb(x, x Xor y, y) '' Get the next pixel address '' (UInteger Ptr will increment by 4 bytes) pixel += 1 Next x '' Go to the next row row += pitch Next y '' Unlock the screen. ScreenUnlock() '' Wait for the user to press a key before closing the program Sleep %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Screenptr""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgScreengraphics Screen (Graphics)]]## - ##[[KeyPgScreenres Screenres]]## - ##[[KeyPgScreeninfo ScreenInfo]]## - ##[[KeyPgScreenlock Screenlock]]## - ##[[KeyPgScreenunlock Screenunlock]]## {{fbdoc item="back" value="CatPgGfxScreen|Screen Functions"}}{{fbdoc item="title" value="SCREENRES"}}---- Initializes a graphics mode by specifying horizontal and vertical resolution {{fbdoc item="syntax"}}## **Screenres** //width// [[KeyPgAs as]] [[KeyPgInteger integer]], //height// [[KeyPgAs as]] [[KeyPgInteger integer]], //depth// [[KeyPgAs as]] [[KeyPgInteger integer]] = 8, //num_pages// [[KeyPgAs as]] [[KeyPgInteger integer]] = 1, //flags// [[KeyPgAs as]] [[KeyPgInteger integer]] = 0, //refresh_rate// [[KeyPgAs as]] [[KeyPgInteger integer]] = 0 ## {{fbdoc item="usage"}}## **Screenres** //width//, //height// [, [//depth//] [, [//num_pages//] [, [//flags//] [, //refresh_rate// ]]]] ## {{fbdoc item="param"}} ##//width//##, ##//height//## The display width and height, respectively. For fullscreen mode, the user should check the availability of the resolution using ##[[KeyPgScreenlist Screenlist]]##. ##//depth//## The color depth in bits per pixel. Valid color depths are: 1, 2, 4, 8, 16 and 32. Values of 15 and 24 are also allowed as aliases for 16 and 32, respectively. If omitted, the default is 8 bits per pixel. 8 bits and below will give a palette image. The default palette will be the first ##2^//depth//## colors of the 256-color palette used in ##[[KeyPgScreengraphics Screen]] 13##. ##//num_pages//## The number of video pages to create, defaults to 1. (see below) ##//flags//## Used to set various properties of the screen, including fullscreen mode and the graphics driver used. (see ##[[KeyPgScreengraphics Screen]]## or the standard header "fbgfx.bi" for available flags) ##//refresh_rate//## The refresh rate of the screen, defaults to an appropriate value. (invalid refresh rates will be ignored) {{fbdoc item="desc"}} ##**Screenres**## tells the compiler to link the GfxLib and initializes a QB-only, QB-on-GUI or OpenGL graphics mode, depending on the ##//flags//## setting In non-fullscreen modes, the resolution does not have to match any resolution of the graphics card. Resolutions like ##555x111## are possible, GfxLib will create a window of such size. See Platform differences for DOS issues. In QB-only modes a dumb window or fullscreen resolution is set, one or more buffers in standard memory are created, console commands are redirected to their graphic versions, a [[GfxDefPalettes default palette]] is set and an automatic screen refresh thread is started. QB-like graphics and console statements can be used. In QB-on-GUI modes one or more buffers in standard memory are created, console commands are redirected to their graphic versions and a [[GfxDefPalettes default palette]] is set . QB-like graphics and console statements can be used. It is up to the user to create a window and to refresh it with the contents of the graphics buffers. In OpenGL modes a dumb window or fullscreen resolution is set, one or more buffers in standard memory are created, and the system's OpenGL library is initialized. From here only OpenGL commands can be used to write to the graphics buffer. QB-like and console commands are forbidden. This mode allows to initialize OpenGL in a portable way. See the details in ##[[KeyPgScreengraphics Screen (Graphics)]]## keyword. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/screenres.bas"}}%%(freebasic) dim a as integer, b as integer ScreenRes 640, 480, 8 'This line will set the screen mode to 640x480x8. 'The following code block will draw diagonal lines over the whole screen. For a = 1 to 640 For b = 1 to 480 Pset (a,b),(a + b) AND 255 Next b Next a 'The following line will print "Hello World!" over the lines we've drawn. Print "Hello world!!" Sleep End %% {{fbdoc item="target"}} - In DOS the resolution must match one supported by the graphics card. GfxLib will try to find an appropriate mode from VGA modes, ""ModeX"" or VESA, preferring VESA LFB interface if available, or banked VESA otherwise. Windowing and OpenGL related switches are not available. Unsupported resolutions may currently crash the program, though in future GfxLib may try to find a close match instead. For optimal compatibility, you should support safe resolutions like 640x480 and 800x600, and maybe 1024x768. There are various additional modes like 768x576 around, but they are vendor specific and lacking on most cards. Also modes 1024x768 and above are not available on older cards and laptops. {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Screenres""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgScreengraphics Screen]]## The QB-like way to do - ##[[KeyPgScreenCons Screen (Console)]]## - ##[[KeyPgScreenlist Screenlist]]## Check available modes - ##[[KeyPgScreencontrol Screencontrol]]## - ##[[KeyPgScreenlock Screenlock]]## - ##[[KeyPgScreenunlock Screenunlock]]## - ##[[KeyPgScreenptr Screenptr]]## Semi-low level access - ##[[KeyPgScreenset Screenset]]## - ##[[KeyPgScreencopy Screencopy]]## - ##[[KeyPgScreeninfo Screeninfo]]## - ##[[KeyPgScreenglproc Screenglproc]]## - ##[[GfxInternalFormats Internal pixel formats]]## {{fbdoc item="back" value="CatPgGfxScreen|Screen Functions"}}{{fbdoc item="title" value="SCREENSET"}}---- Sets current work and visible pages {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Screenset** ( [[KeyPgByval byval]] //work_page// [[KeyPgAs as]] [[KeyPgInteger integer]] = -1, [[KeyPgByval byval]] //visible_page// [[KeyPgAs as]] [[KeyPgInteger integer]] = -1 ) ## {{fbdoc item="usage"}}## **Screenset** [ //work_page// ] [, //visible_page// ] ## {{fbdoc item="param"}} ##//work_page//## index to working page ##//visible_page//## index to visible page {{fbdoc item="desc"}} ##**Screenset**## allows to set the current working page and the current visible page. Page numbers range from 0 to the num_pages specified when setting the graphics mode minus 1 . You can use this function to achieve page-flipping or double-buffering. If you omit ##//work_page//## but not ##//visible_page//##, only visible page is changed. If you omit ##//visible_page//## but not ##//work_page//##, only work page is changed. If you omit both arguments, both work page and visible page are reset to page 0. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/screenset.bas"}}%%(freebasic) ' Set good old 320x200 in 8bpp mode, but with 2 pages SCREEN 13, ,2 COLOR ,15 DIM x AS INTEGER x = -40 ' Let's work on page 1 while we display page 0 SCREENSET 1, 0 DO CLS LINE (x, 80)-(x + 39, 119), 4, BF x = x + 1 IF (x > 319) THEN x = -40 ' Wait for vertical sync WAIT &h3DA, 8 ' Copy work page to visible page SCREENCOPY LOOP WHILE INKEY = "" %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Screenset""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgScreengraphics Screen (Graphics)]]## - ##[[KeyPgScreenres Screenres]]## - ##[[KeyPgScreencopy Screencopy]]## {{fbdoc item="back" value="CatPgGfxScreen|Screen Functions"}}{{fbdoc item="title" value="SCREENSYNC"}}---- Synchronizes display updates with hardware {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Screensync** ( ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **Screensync** ## {{fbdoc item="ret"}} Zero if successful, or non-zero if a graphics mode was not previously set. {{fbdoc item="desc"}} This GfxLib statement stops the execution of the program until the graphics card signals it has ended tracing a frame and is going to start the new one. If the program uses the small interval of time between frames to redraw the image, the flickering is greatly reduced. The use of the QB-compatible form WAIT &H3DA,8 is deprecated. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/screensync.bas"}}%%(freebasic) 'main loop DO ' do user input ' calculate_a_frame SCREENSYNC ' draw_ a_ frame LOOP UNTIL INKEY <> "" %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Screensync""**##. {{fbdoc item="diff"}} - New to FreeBASIC. - QBasic used WAIT &H3DA,8 for this purpose. {{fbdoc item="see"}} - ##[[KeyPgWait Wait]]## {{fbdoc item="back" value="CatPgGfxScreen|Screen Functions"}}{{fbdoc item="title" value="SCREENUNLOCK"}}---- Unlocks work page's framebuffer {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Screenunlock** ( [[KeyPgByval byval]] //startline// [[KeyPgAs as]] [[KeyPgInteger integer]] = -1, [[KeyPgByval byval]] //endline// [[KeyPgAs as]] [[KeyPgInteger integer]] = -1 ) ## {{fbdoc item="usage"}}## **Screenunlock** [ //start_line// ] [, //end_line// ] ## {{fbdoc item="param"}} ##//startline//## optional argument specifying first screen line to be updated. If omitted, top screen line is assumed. ##//endline//## optional argument specifying last screen line to be updated. If omitted, bottom screen line is assumed. {{fbdoc item="desc"}} ##**Screenunlock**## unlocks the current work page assuming it was previously locked by calling ##[[KeyPgScreenlock Screenlock]]## and lets the system restart updating the screen regularly. When called with ##start_line## and ##end_line## , only the screen area between those lines is assumed to have changed, and will be updated. An internal flag exists remembering the screen lock state, thus ##**Screenunlock**## has an effect only on a screen that is locked - or in other words, a screen that is not locked with ##**Screenlock**## cannot get unlocked, however ##**Screenunlock**## still will force an update of given area or full screen. After ##**Screenunlock**## is called, all graphics statements still may be safely used, OTOH accessing the work page framebuffer directly via ##[[KeyPgScreenptr Screenptr]]## may only be used after locking the screen again with ##[[KeyPgScreenlock Screenlock]]##. Warning (Win32, Linux) : The screen is locked by stopping the thread that processes also the OS' events. This means the screen should be locked only for the short time required to redraw it, and no user input will be received while the screen is locked. {{fbdoc item="ex"}} See ##[[KeyPgScreenptr Screenptr]]## example. {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Screenunlock""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgScreengraphics Screen (Graphics)]]## - ##[[KeyPgScreenlock Screenlock]]## - ##[[KeyPgScreenptr Screenptr]]## {{fbdoc item="back" value="CatPgGfxScreen|Screen Functions"}}{{fbdoc item="title" value="SECOND"}}---- Gets the seconds from a [[ProPgDates Date Serial]] {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Second** ( [[KeyPgByval byval]] //date_serial// [[KeyPgAs as]] [[KeyPgDouble double]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## #include "vbcompat.bi" //result// = **Second**( //date_serial// ) ## {{fbdoc item="param"}} ##//date_serial//## the date serial {{fbdoc item="ret"}} Returns the seconds from a variable containing a date in [[ProPgDates Date Serial]] format. {{fbdoc item="desc"}} The compiler will not recognize this function unless ##vbcompat.bi## is included. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/dates/second.bas"}}%%(freebasic) #include "vbcompat.bi" Dim ds As Double = DateSerial(2005, 11, 28) + TimeSerial(7, 30, 50) Print Format(ds, "yyyy/mm/dd hh:mm:ss "); Second(ds) %% {{fbdoc item="diff"}} - Did not exist in QB. This function appeared in PDS and VBDOS {{fbdoc item="see"}} - [[ProPgDates Date Serials]] {{fbdoc item="back" value="CatPgDate|Date and Time Functions"}}{{fbdoc item="title" value="SEEK (Function)"}}---- Gets the position of the next read/write operation for a file or device {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Seek** ( [[KeyPgByval byval]] //filenum// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgLongint longint]] ## {{fbdoc item="param"}} ##//filenum//## file number of an open file {{fbdoc item="ret"}} The file position where the next read or write operation will take place. {{fbdoc item="desc"}} The position is given in records if the file was opened in ##[[KeyPgRandom Random]]## access mode, in bytes in any other case. The file position returned is 1-based, so the first record of a file is 1. The ##[[KeyPgSeekset Seek]]## statement is used to set the position of the next read or write operation. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/fileio/seek-func.bas"}}%%(freebasic) dim f as integer, position as integer f = freefile open "file.ext" for binary as #f position = seek(f) close #f %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgSeekset Seek (Statement)]]## - ##[[KeyPgLoc Loc]]## - ##[[KeyPgOpen Open]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}}{{fbdoc item="title" value="SEEK (Statement)"}}---- Sets the position of the next read/write operation on a file {{fbdoc item="syntax"}}## **Seek** [#]//filenum//, //position// ## {{fbdoc item="param"}} ##//filenum//## file number of an opened a file ##//position//## the new position for i/o operations {{fbdoc item="desc"}} Sets the position at which the next read or write operation on a file will occur. The position is given in records if the file was opened in ##[[KeyPgRandom Random]]## access mode, in bytes in any other case. The position is 1 based, the first record of a file is at position 1. The ##[[KeyPgSeekreturn Seek]]## function is used to get the position of the next read or write operation. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/fileio/seek-statment.bas"}}%%(freebasic) ' e.g. if you want to skip to the 100th byte in the file for reading/writing: dim f as integer f = freefile open "file.ext" for binary as #f seek f, 100 close #f %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgSeekreturn Seek (Function)]]## - ##[[KeyPgOpen Open]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:58:33 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 632353f3c78cd2e3ad9f53f2fe94b998 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 2555 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="SELECT CASE"}}---- Conditional statement block {{fbdoc item="syntax"}}## **Select Case** //expression// [ **Case** //expressionlist//] [//statements//] [ **Case Else** ] [//statements//] **End Select** //or// Select Case As Const //integerexpression// [ **Case** //constant// | //enumeration// ] [ //statements// ] [ **Case Else** ] [ //statements// ] **End Select** ## {{fbdoc item="desc"}} Select Case executes specific code depending on the value of an expression. The expression is compared against each Case, in order, until a matching expression is found. The code inside the matching Case branch is executed, and the program skips down to the end of the Select Case block. Case Else matches any Case not already matched, so if there is a Case Else, at least one Case is guaranteed to be executed. If no Cases match, the whole Select Case block will be skipped. For C users: In FreeBASIC, ##**Select Case**## works as a switch where all cases have a "break;" at the end. As there is no fall-through, multiple options must be put in an expression list in a single ##**Case**##. ##**End Select**## can be used to exit the ##**Select Case...End Select**## block Besides integer types, floating point and strings //expressions// are also supported with the first syntax. Syntax of an expression list: ##{ //expression// | //expression// TO //expression// | IS //relational operator// //expression// }[, ...]## example of expression lists: {{table columns="2" cellpadding="1" cells="Case 1 ;constant;Case 5.4 To 10.1;range;Case Is > 3;bigger than-smaller than;Case 1, 3, 5, 7, 9;enumeration;Case x ;value of a variable"}} If AS CONST is used, only integer constants in the range 0..4097 can be evaluated and the expression list supports single constants and enumerations only. Being limited to integer values allows ##**Select Case As Const**## to be faster than ##**Select Case**##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/control/select.bas"}}%%(freebasic) dim choice as integer input "Choose a number between 1 and 10: "; choice select case as const choice case 1 print "number is 1" case 2 print "number is 2" case 3, 4 print "number is 3 or 4" case 5 to 10 print "number is in the range of 5 to 10" case else print "number is outside the 1-10 range" end select %% {{fbdoc item="diff"}} - SELECT CASE AS CONST did not exist in QB {{fbdoc item="see"}} - ##[[KeyPgIfthen If...Then]]## {{fbdoc item="back" value="CatPgControlFlow|Control Flow"}} {{fbdoc item="title" value="SETDATE"}}---- Sets the current system date {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Setdate** ( [[KeyPgByref byref]] //newdate// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **Setdate**( //newdate// ) ## {{fbdoc item="param"}} ##//newdate//## the new date to set {{fbdoc item="ret"}} Returns zero on success or non-zero on failure on all ports except DOS. {{fbdoc item="desc"}} To set the date you just format ##//newdate//## and send to ##**Setdate**## in a valid format following one of the following: ##"mm-dd-yy"##, ##"mm-dd-yyyy"##, ##"mm/dd/yy"##, or ##"mm/dd/yyyy"## (##mm## is the month, ##dd## is the day, ##yy## or ##yyyy## is the year. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/system/setdate.bas"}}%%(freebasic) Dim m As String, d As String, y As String m = "03" 'march d = "13" 'the 13th y = "1994" 'good ol' days SetDate m + "/" + d + "/" + y %% {{fbdoc item="diff"}} - The DATE statement was used in QB and the syntax was "//DATE = string//" {{fbdoc item="see"}} - ##[[KeyPgDate Date]]## - ##[[KeyPgSettime Settime]]## {{fbdoc item="back" value="CatPgDate|Date and Time Functions"}}{{fbdoc item="title" value="SETENVIRON"}}---- Sets a system environment variable {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Setenviron** ( [[KeyPgByref byref]] //varname// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **Setenviron**( //varname// ) ## {{fbdoc item="param"}} ##//varname//## The name of the environment variable to set. {{fbdoc item="ret"}} Return zero (0) if successful, non-zero otherwise. {{fbdoc item="desc"}} Modifies system environment variables. There are several variables available for editing other than the default ones on your system. An example of this would be fbgfx, where you can choose the form of graphics driver the FreeBASIC graphics library will use. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/system/setenviron.bas"}}%%(freebasic) 'e.g. to set the system variable "path" to "c:": shell "set path" 'shows the value of path setenviron "path=c:" shell "set path" 'shows the new value of path %% {{fbdoc item="filename" value="examples/manual/system/setenviron2.bas"}}%%(freebasic) '' WINDOWS ONLY EXAMPLE! - We just set the graphics method to use '' GDI rather than OpenGL, DirectX, or X Driver. '' Try changing this to OpenGL or DirectX On Windows '' Or xlib on Linux '' You may note a difference in FPS. SetEnviron("fbgfx=GDI") '' Desktop width/height Dim As Integer ScrW, ScrH, BPP ScreenInfo ScrW, ScrH, BPP '' Create a screen at the width/height of your monitor. '' Normally this would be slow, but GDI is fairly fast for this kind '' of thing. ScreenRes ScrW, ScrH, BPP '' Start our timer/ Dim As Double T = Timer '' Lock our page ScreenLock Do '' Print time since last frame Locate 1, 1 Print "FPS: " & 1 / ( Timer - T ) T = Timer '' Flip our screen ScreenUnlock ScreenLock '' Commit a graphical change to our screen. Cls Loop Until Len(Inkey) '' unlock our page. ScreenUnlock %% {{fbdoc item="diff"}} - In QB, ##**Setenviron**## was called ##**Environ**##. {{fbdoc item="see"}} - ##[[KeyPgEnviron Environ]]## - ##[[KeyPgShell Shell]]## {{fbdoc item="back" value="CatPgOpsys|Operating System Functions"}}{{fbdoc item="title" value="SETMOUSE"}}---- Sets the position and visibility of the mouse cursor {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Setmouse** ( [[KeyPgByval byval]] //x// [[KeyPgAs as]] [[KeyPgInteger integer]] = -1, [[KeyPgByval byval]] //y// [[KeyPgAs as]] [[KeyPgInteger integer]] = -1, [[KeyPgByval byval]] //visibility// [[KeyPgAs as]] [[KeyPgInteger integer]] = -1, [[KeyPgByval byval]] //clip// [[KeyPgAs as]] [[KeyPgInteger integer]] = -1 ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **Setmouse**([ //x// ] [, [ //y// ] [, [ //visibility// ] [, [ //clip// ]]]]) ## {{fbdoc item="param"}} ##//x//## optional - set x coordinate ##//y//## optional - set y coordinate ##//visibility//## optional - set visibility: 1 indicates visible, 0 indicates hidden ##//clip//## optional - set clipping: 1 indicates mouse is clipped to graphics window, 0 indicates no clipping {{fbdoc item="ret"}} 0 on success, non-zero to indicate failure. {{fbdoc item="desc"}} ##**Setmouse**## will set the ##//X//,//Y//## coordinates of the mouse pointer, as well as setting it's visibility. Mouse position is set using the X and Y parameters. The mouse will be visible if visibility is set to 1, and invisible if visibility is set to 0. ##**Setmouse**## is intended for graphics modes initiated using the ##[[KeyPgScreengraphics Screen (Graphics)]]## statement only. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/input/setmouse.bas"}}%%(freebasic) #include "fbgfx.bi" Dim x As Integer, y As Integer, buttons As Integer ' create a screen 800x600, 32-bit color, 1 video page Screen 19, 32, 1 Do ' get mouse x, y and button state GetMouse x, y , , buttons If buttons = 1 Then ' on left mouse click, center mouse SetMouse 400, 300 End If ' do loop until esc is pressed Loop Until MultiKey(fb.SC_ESCAPE) %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Setmouse""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgGetmouse Getmouse]]## - ##[[KeyPgScreengraphics Screen]]## - ##[[KeyPgMultikey Multikey]]## - ##[[KeyPgGetkey Getkey]]## {{fbdoc item="back" value="CatPgGfxInput|User Input Functions"}}{{fbdoc item="title" value="SETTIME"}}---- Sets the current system time {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Settime** ( [[KeyPgByref byref]] //newtime// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **Settime**( //newtime// ) ## {{fbdoc item="param"}} ##//newtime//## the new time to set {{fbdoc item="ret"}} Returns zero on success or non-zero on failure on all ports except DOS. {{fbdoc item="desc"}} To set the time, format the date and send to ##Settime## in one of the following formats: ##"hh:mm:ss"##, ##"hh:mm"##, or ##"hh"## (##hh## is the hour, ##mm## is the minute, and ##ss## is the second). {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/system/settime.bas"}}%%(freebasic) SETTIME "1:20:30" %% {{fbdoc item="diff"}} - The ##[[KeyPgTime Time]]## statement was used QB and the syntax was ##TIME = //newtime//##. {{fbdoc item="see"}} - ##[[KeyPgTime Time]]## - ##[[KeyPgSetdate Setdate]]## {{fbdoc item="back" value="CatPgDate|Date and Time Functions"}}{{fbdoc item="title" value="SGN"}}---- Returns the sign part of a number {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Sgn** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgDouble double]] ) [[KeyPgAs as]] [[KeyPgDouble double]] ## {{fbdoc item="usage"}}## //result// = **Sgn** ( //number// ) ## {{fbdoc item="param"}} ##//number//## the number {{fbdoc item="ret"}} Returns the sign part of ##//number//##. - If //number// is greater than zero, then SGN returns 1. - If //number// is equal to zero, then SGN returns 0. - If //number// is less than zero, then SGN returns -1. {{fbdoc item="desc"}} The required ##//number//## argument can be any valid numeric expression. If ##//number//## is an uninitialized variable, zero is returned. The ##**Sgn**## unary ##[[KeyPgOperator operator]]## can be overloaded with user defined types. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/math/sgn.bas"}}%%(freebasic) DIM N AS INTEGER PRINT SGN ( -1.87 ) PRINT SGN ( 0 ) PRINT SGN ( 42.658 ) PRINT SGN ( N ) %% The output would look like: %% -1 0 1 0 %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, this operator cannot be overloaded. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgAbs Abs]]## - ##[[KeyPgOperator Operator]]## {{fbdoc item="back" value="CatPgMath|Math"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:58:43 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 70dfd31b380e66b72035c12df1ff03bc Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 1743 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="SHARED"}}---- Variable declaration modifier specifying visibility throughout a module {{fbdoc item="syntax"}}## [[KeyPgDim Dim]] **Shared** ... [[KeyPgRedim Redim]] **Shared** ... [[KeyPgCommon Common]] **Shared** ... ## {{fbdoc item="desc"}} ##Shared## makes module-level variables visible inside ##[[KeyPgSub Sub]]##s and ##[[KeyPgFunction Function]]##s. If ##Shared## is not used on a module-level variable's declaration, it is stored on the stack of the implicit main function and therefore only visible to the module-level code in that file. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/variable/shared.bas"}}%%(freebasic) '' Compile with -lang qb or fblite declare sub MySub dim shared x as integer dim y as integer x = 10 y = 5 MySub sub MySub print "x is "; x 'this will report 10 as it is shared print "y is "; y 'this will not report 5 because it is not shared end sub %% {{fbdoc item="diff"}} - The ##Shared## statement inside scope blocks -- functions, subs, if/thens, and loops -- is not supported. Use ##Dim##|##Redim##|##Common Shared## in the main program instead. Or if you're inside a scope block and ##Redim##ming a variable or array previously set up with ##Shared##, just do a ##Redim## without ##Shared##; it will work fine and won't ruin anything. {{fbdoc item="see"}} - ##[[KeyPgCommon Common]]## - ##[[KeyPgDim Dim]]## - ##[[KeyPgErase Erase]]## - ##[[KeyPgExtern Extern]]## - ##[[KeyPgLbound Lbound]]## - ##[[KeyPgRedim Redim]]## - ##[[KeyPgPreserve Preserve]]## - ##[[KeyPgShared Shared]]## - ##[[KeyPgStatic Static]]## - ##[[KeyPgUbound Ubound]]## - ##[[KeyPgVar Var]]## {{fbdoc item="back" value="CatPgVariables|Variable Declarations"}} {{fbdoc item="title" value="SHELL"}}---- Sends a command to the system command interpreter {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Shell**( //command// [[KeyPgAs as]] [[KeyPgString string]] ) ## {{fbdoc item="usage"}}## Shell( //command// ) ## {{fbdoc item="param"}} ##//command//## A string specifying the command to send to the command interpreter. {{fbdoc item="desc"}} Program execution will be suspended until the command interpreter exits. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/system/shell.bas"}}%%(freebasic) 'e.g. for windows: shell "dir c:*.*" 'e.g. for linux: shell "ls" %% {{fbdoc item="target"}} - Linux requires the //command// case matches the real name of the command. Windows and DOS are case insensitive. The program being shelled may be case sensitive for its command line parameters. - Path separators in Linux are forward slashes / . Windows uses backward slashes \ but it allows for forward slashes . DOS uses backward \ slashes. {{fbdoc item="diff"}} - QB allowed SHELL on its own without a "command" argument which caused a default command shell to be started. Execution in the main program would suspend until exit from the command shell. {{fbdoc item="see"}} - ##[[KeyPgExec Exec]]## - ##[[KeyPgRun Run]]## {{fbdoc item="back" value="CatPgOpsys|Operating System Functions"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:58:51 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 2e8f95a562d8ef533ca075892f5a0301 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 923 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="SHORT"}}---- Standard data type: 16 bit signed {{fbdoc item="syntax"}}## [[KeyPgDim dim]] //variable// [[KeyPgAs as]] **Short** ## {{fbdoc item="desc"}} 16-bit signed whole-number data type. Can hold values from -32768 to 32767. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/datatype/short.bas"}}%%(freebasic) Dim x As Short = CShort(&H8000) Dim y As Short = CShort(&H7FFF) Print "Short Range = "; x; " to "; y %% **Output:** %%Short Range = -32768 to 32767%% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Short""**##. {{fbdoc item="diff"}} - The name "short" is new to FreeBASIC, however they are the same as integers in QB {{fbdoc item="see"}} - ##[[KeyPgUshort Ushort]]## - ##[[KeyPgCshort Cshort]]## {{fbdoc item="back" value="CatPgStdDataTypes|Standard Data Types"}} {{fbdoc item="title" value="SIN"}}---- Returns the sine of a number {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Sin** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgDouble double]] ) [[KeyPgAs as]] [[KeyPgDouble double]] ## {{fbdoc item="usage"}}## //result// = **Sin** ( //number// ) ## {{fbdoc item="param"}} ##//number//## the angle (in radians) {{fbdoc item="ret"}} Returns the sine of the argument ##//number//## as a ##[[KeyPgDouble Double]]## within the range of -1 to 1. {{fbdoc item="desc"}} The argument ##//number//## is measured in [[TutMathAngles radians]] (not [[TutMathAngles degrees]]). The required ##//number//## argument can be any valid numeric expression. If ##//number//## is an uninitialized variable, zero is returned. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/math/sin.bas"}}%%(freebasic) CONST PI AS DOUBLE = 3.1415926535897932 DIM a AS DOUBLE DIM r AS DOUBLE INPUT "Please enter an angle in degrees: ", a r = a * PI / 180 'Convert the degrees to Radians PRINT "" PRINT "The sine of a" ; a; " degree angle is"; SIN ( r ) SLEEP %% The output would look like: %% Please enter an angle in degrees: 30 The sine of a 30 degree angle Is 0.5 %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgAsin Asin]]## - [[TutMathIntroTrig A Brief Introduction To Trigonometry]] {{fbdoc item="back" value="CatPgMath|Math"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:58:59 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 6b9c5355b40de6655d0743c699273f76 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 816 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="SINGLE"}}---- Standard data type: 32 bit floating point {{fbdoc item="syntax"}}## [[KeyPgDim dim]] //variable// [[KeyPgAs as]] **Single** ## {{fbdoc item="desc"}} Single is a 32-bit, floating point data type used to store decimal numbers. They can hold values in a range of 1.1 E-38 to 3.43 E+38. Its precision is of 6 decimal digits. They are similar to ##[[KeyPgDouble Double]]## data types, but less precise. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/datatype/single.bas"}}%%(freebasic) 'Example of using a single variable. dim a as single a = 1.9857665 print a sleep %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgDouble Double]]## - ##[[KeyPgCsng Csng]]## {{fbdoc item="back" value="CatPgStdDataTypes|Standard Data Types"}} {{fbdoc item="title" value="SIZEOF"}}---- Returns the size of a variable or type in bytes. {{fbdoc item="syntax"}}## **Sizeof** ( //variable// | [[DataType DataType]] ) ## {{fbdoc item="desc"}} The ##Sizeof## operator returns the length of a //variable// or [[DataType DataType]]. Different from ##[[KeyPgLen Len]]##, when used with fixed-length strings (including ##[[KeyPgZstring Zstring]]##s and ##[[KeyPgWstring Wstring]]##s) it will return the number of bytes allocated, and when used with variable-length strings, it will return the size of the string descriptor. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/misc/sizeof.bas"}}%%(freebasic) Print SizeOf(Byte) ' returns 1 %% {{fbdoc item="filename" value="examples/manual/misc/sizeof-udt.bas"}}%%(freebasic) Type bar a As Integer b As Double End Type Dim foo As bar Print SizeOf(foo) %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Sizeof""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgLen Len]]## {{fbdoc item="back" value="CatPgMisc|Miscellaneous"}}{{fbdoc item="title" value="SLEEP"}}---- Waits until a specified time has elapsed, or a key is pressed. {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Sleep** [[KeyPgOverload overload]] ( [[KeyPgByval byval]] //amount// [[KeyPgAs as]] [[KeyPgInteger integer]] = -1 ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Sleep** ( [[KeyPgByval byval]] //amount// [[KeyPgAs as]] [[KeyPgInteger integer]] , [[KeyPgByval byval]] //keyflag// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## **Sleep** [ //amount// [, //keyflag// ]] ## {{fbdoc item="param"}} ##//amount//## Optional number of milliseconds to wait (default is to wait for a key press). ##//keyflag//## Optional flag; give it a value of 1 to specify that the wait cannot be interrupted by a key press. {{fbdoc item="desc"}} ##**Sleep**## will wait until ##//amount//## milliseconds (can be seconds in //[[CompilerOptlang -lang qb]]//, see below) given elapsed (if any value was passed) or until the user presses a key. If ##//amount//## is below 100 ms then ##**Sleep**## will always wait the full requested amount (key presses are ignored). Include the second parameter, ##1##, for a "deep" sleep, which cannot be interrupted by pressing a key. The accuracy of ##**Sleep**## is variable depending on the OS cycle time (Windows NT/2K/XP: 15 ms, 9x/Me: 50 ms, Linux 10ms, DOS 55 ms). Call ##**Sleep**## with 25ms or less to release time-slice when waiting for user input or looping inside a thread. This will prevent the program from unnecessarily hogging the CPU. ##**Sleep**## does not clear the keyboard buffer and any keys pressed during a call to ##**Sleep**## are retained and can be read using ##[[KeyPgInkey Inkey]]##. In order to wait for a key press, and remove the key from the buffer, ##[[KeyPgGetkey Getkey]]## can be used instead. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/system/sleep.bas"}}%%(freebasic) print "press a key" sleep getkey 'clear the keyboard buffer print "waiting half second" sleep 500 %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang fb]]// and //[[CompilerOptlang -lang fblite]]// dialects, the ##//amount//## value is in **milliseconds**. - In the //[[CompilerOptlang -lang qb]]// dialect, the ##//amount//## value is in **seconds** as in QB. If the second parameter ##//keyflag//## is given, or the keyword is written as ##**""__Sleep""**## the value is expected to be in **milliseconds**. {{fbdoc item="diff"}} - None in the //[[CompilerOptlang -lang qb]]// dialect. - In QB, the delay was given in whole seconds only and did not support the ##//keyflag//## parameter. {{fbdoc item="see"}} - ##[[KeyPgTimer Timer]]## - ##[[KeyPgInkey Inkey]]## {{fbdoc item="back" value="CatPgMisc|Miscellaneous"}}{{fbdoc item="title" value="SPACE"}}---- Creates a string of a certain length filled with spaces spaces (" ") {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Space**( //count// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgString string]] ## {{fbdoc item="usage"}}## //result// = **Space**[$]( //count// ) ## {{fbdoc item="param"}} ##//count//## An integer type specifying the length of the string to be created. {{fbdoc item="ret"}} The created string. An empty string will be returned if ##//count//## <= 0. {{fbdoc item="desc"}} ##**Space**## creates a string with the specified number of spaces. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/space.bas"}}%%(freebasic) DIM A AS WSTRING *14 A="x"+space(10)+"x" 'prints x x %% {{fbdoc item="lang"}} - The string type suffix "$" is obligatory in the //[[CompilerOptlang -lang qb]]// dialect. - The string type suffix "$" is optional in the //[[CompilerOptlang -lang fblite]]// and //[[CompilerOptlang -lang fb]]// dialects. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgWspace Wspace]]## - ##[[KeyPgStringFunction String (Function)]]## {{fbdoc item="back" value="CatPgString|String Functions"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:59:08 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: f420bb925fe33d6b64873997377842a1 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 1109 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="SPC"}}---- Output function to skip spaces when writing to screen or file {{fbdoc item="syntax"}}## **Spc**( //columns// ) ## {{fbdoc item="usage"}}## [[KeyPgPrint Print]] **Spc**( //columns// ) [(, | ;)] ... ## {{fbdoc item="param"}} ##//columns//## number of columns to skip {{fbdoc item="desc"}} ##**Spc**## skips n-//columns// when ##[[KeyPgPrint Print]]##ing to screen or to a file. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/console/spc.bas"}}%%(freebasic) DIM AS STRING A, B, N, M A = "Jane" B = "DOE" N = "Bob" M = "Smith" PRINT "FIRST NAME"; SPC(25); "LAST NAME" PRINT "----------"; SPC(25); "----------" PRINT A; SPC(35-LEN(A)); B PRINT N; SPC(35-LEN(N)); M %% The output would look like: ##%% FIRST NAME LAST NAME ---------- ---------- Jane DOE Bob Smith %%## {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgPrint Print]]## - ##[[KeyPgTab Tab]]## {{fbdoc item="back" value="CatPgConsole|Console Functions"}} {{fbdoc item="title" value="SQR"}}---- Returns a square root of a number {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Sqr** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgDouble double]] ) [[KeyPgAs as]] [[KeyPgDouble double]] ## {{fbdoc item="usage"}}## result = **Sqr** ( //number// ) ## {{fbdoc item="param"}} ##//number//## the number (greater than or equal to zero) {{fbdoc item="ret"}} Returns the square root of the argument ##//number//##. If ##//number//## equals zero, **Sqr** returns zero. If ##//number//## is less than zero, **Sqr** returns a domain error (-1.#IND). {{fbdoc item="desc"}} This is the same as raising the argument //number// to the one-half power ( ^ 1/2). The required ##//number//## argument can be any valid numeric expression greater than zero. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/math/sqr.bas"}}%%(freebasic) DIM a AS SINGLE DIM b AS SINGLE INPUT "Please enter one side of a right triangle: ",a INPUT "Please enter another side of a right triangle: ",b PRINT "" PRINT "The hypotenuse of the triangle has a length of"; SQR ( a * a + b * b ) SLEEP %% The output would look like: %% Please enter one side of a Right triangle: 3 Please enter another side of a Right triangle: 4 The hypotenuse of the triangle has a length of 5 %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - [[CatPgMath Arithmetic Operators]] {{fbdoc item="back" value="CatPgMath|Math"}}{{fbdoc item="title" value="STATIC"}}---- Defines variables, objects and arrays having static storage {{fbdoc item="syntax"}}## **Static** //symbol// [ ( [ //subscripts// ] ) ] [ [[KeyPgAs as]] [[DataType DataType]] ] [ , ... ] //or// { [[KeyPgSub sub]]|[[KeyPgFunction function]] } //proc_header// **Static** [ ... ] [[KeyPgEndblock end]] { [[KeyPgSub sub]]|[[KeyPgFunction function]] } ## {{fbdoc item="param"}} ##//symbol//## variable or array symbol name. ##//subscripts//## a comma-separated list of subscript ranges. ##//proc_header//## procedure header for a procedure definition. {{fbdoc item="desc"}} Specifies [[ProPgStorageClasses static storage]] for variables, objects and arrays; they are allocated at program startup and deallocated upon exit. Objects are constructed once when they are defined, and destructed upon program exit. When declaring static arrays, only [[ProPgLiterals numeric literals]], [[KeyPgConst constants]] or [[KeyPgEnum enumerations]] may be used as subscript range values. Static variable-length arrays must be declared empty (no subscript range list) and resized using ##[[KeyPgRedim Redim]]## before used. In both iterative and recursive blocks, like looping [[CatPgControlFlow control flow statements]] or procedures, static variables, objects and arrays local to the block are guaranteed to occupy the same storage across all instantiations of the block. For example, procedures that call themselves - either directly or indirectly - share the same instances of their local static variables. When used with module-level and member procedure declarations, ##**Static**## specifies [[ProPgStorageClasses static storage]] for all local variables, objects and arrays. ##[[KeyPgStaticMember Static (Member)]]## is also used in member procedure declarations to specify static member procedures. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/variable/static.bas"}}%%(freebasic) sub f '' static variables are initialized to 0 by default static i as integer i += 1 Print "Number of times called: " & i end sub '' the static variable in f() retains its value between '' multiple procedure calls. f() f() %% Will output: %% Number of times called: 1 Number of times called: 2 %% {{fbdoc item="diff"}} - ""QuickBASIC"" allows variables and arrays to be declared using the ##**Static**## keyword within procedures and ##DEF FN## routines only. - ##**Static**## forces local visibility of variables and arrays in ""QuickBASIC"" ##DEF FN## routines. ""FreeBASIC"" supports neither ##DEF FN## routines nor this usage of ##**Static**##. - Using ##[[KeyPgStaticMember Static]]## to specify static member procedures is new to ""FreeBASIC"". {{fbdoc item="see"}} - ##[[KeyPgStaticMember Static (Member)]]## - ##[[KeyPgDim Dim]]##, ##[[KeyPgRedim Redim]]## - ##[[KeyPgSub Sub (Module)]]##, ##[[KeyPgFunction Function (Module)]]## - ##[[KeyPgMemberSub Sub (Member)]]##, ##[[KeyPgMemberFunction Function (Member)]]## - ##[[KeyPgOptionstatic Option Static]]## - [[ProPgStorageClasses Storage Classes]] {{fbdoc item="back" value="CatPgProcedures|Procedures"}}{{fbdoc item="back" value="CatPgVariables|Variable Declarations"}}{{fbdoc item="title" value="STATIC (Member)"}}---- Declaration specifier for a static member procedure. {{fbdoc item="syntax"}}## [[KeyPgType Type]] //typename// [[KeyPgDeclare declare]] **Static** //membertype// //membername// ... End Type ## {{fbdoc item="param"}} ##//typename//## name of a user defined data type ##//membertype//## ##[[KeyPgMemberSub Sub]]## or ##[[KeyPgMemberFunction Function]]##. ##//membername// ...## Name of the member to declare or define with parameter list or return value following. {{fbdoc item="desc"}} When declaring a member procedure, ##**Static**## specifies that the member procedure not have an implicit instance argument passed to it, and thus can only access values passed to it. Static member procedures may access Private or Protected members in their type, but to call procedures you must pass the Object as an additional first parameter. You may call a static member procedure anywhere in your code just like any other procedure in a type, i.e. //variable of the type//.//static procedure name//(//arguments//). The address of a static member function can also be assigned to a function pointer using the standard [[KeyPgOpProcptr ProcPtr()]] or the [[KeyPgOpAt @ Operator]] usage. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/udt/static.bas"}}%%(freebasic) '' Example showing how the actual procedure invoked by a member can be set at runtime. '' using static member procedures. type Object enum handlertype ht_default ht_A ht_B end enum declare constructor( byval ht as handlertype = ht_default) declare sub handler() private: declare static sub handler_default( byref obj as Object ) declare static sub handler_A( byref obj as Object ) declare static sub handler_B( byref obj as Object ) handler_func as sub( byref obj as Object ) end type constructor Object( byval ht as handlertype ) select case ht case ht_A handler_func = @Object.handler_A case ht_B handler_func = @Object.handler_B case else handler_func = @Object.handler_default end select end constructor sub Object.handler() handler_func(this) end sub sub Object.handler_default( byref obj as Object ) print "Handling using default method" end sub sub Object.handler_A( byref obj as Object ) print "Handling using method A" end sub sub Object.handler_B( byref obj as Object ) print "Handling using method B" end sub dim objects(1 to 4) as Object => _ { _ Object.handlertype.ht_B, _ Object.handlertype.ht_default, _ Object.handlertype.ht_A _ } '' 4th array item will be Object.handlertype.ht_default for i as integer = 1 to 4 print i, objects(i).handler() next i %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgClass Class]]## - ##[[KeyPgDeclare Declare]]## - ##[[KeyPgType Type]]## - ##[[KeyPgStatic Static]]## {{fbdoc item="back" value="CatPgProcedures|Procedures"}}{{fbdoc item="back" value="CatPgUserDefTypes|User Defined Types"}}{{fbdoc item="title" value="STDCALL"}}---- Specifies a //stdcall//-style calling convention in a procedure declaration {{fbdoc item="syntax"}}## [[KeyPgDeclare Declare]] [[[KeyPgStatic Static]]] [[KeyPgSub Sub]] //procedure_name// [[[KeyPgOverload Overload]]] **Stdcall** [[[KeyPgAlias Alias]] //"""external_name"""//] [([//parameter_list//])] [[[KeyPgModuleConstructor Constructor]] [//priority//]] [[[KeyPgStatic Static]]] [[[KeyPgExport Export]]] [[KeyPgDeclare Declare]] [[[KeyPgStatic Static]]] [[KeyPgFunction Function]] //procedure_name// [[[KeyPgOverload Overload]]] **Stdcall** [[[KeyPgAlias Alias]] //"""external_name"""//] [([//parameter_list//])] [[KeyPgAs as]] //return_type// [[[KeyPgStatic Static]]] [[[KeyPgExport Export]]] [[[KeyPgPublic Public]]|[[KeyPgPrivate Private]]] [[KeyPgSub Sub]] //procedure_name// [[[KeyPgOverload Overload]]] **Stdcall** [[[KeyPgAlias Alias]] //"""external_name"""//] [([//parameter_list//])] [[[KeyPgModuleConstructor Constructor]] [//priority//]] [[[KeyPgStatic Static]]] [[[KeyPgExport Export]]] //..procedure body..// [[KeyPgEnd End]] [[KeyPgSub Sub]] [[[KeyPgPublic Public]]|[[KeyPgPrivate Private]]] [[KeyPgFunction Function]] //procedure_name// [[[KeyPgOverload Overload]]] **Stdcall** [[[KeyPgAlias Alias]] //"""external_name"""//] [([//parameter_list//])] [[KeyPgAs as]] //return_type// [[[KeyPgStatic Static]]] [[[KeyPgExport Export]]] //..procedure body..// [[KeyPgEnd End]] [[KeyPgFunction Function]] ## {{fbdoc item="desc"}} In procedure declarations, ##**Stdcall**## specifies that a procedure will use the //stdcall// calling convention. In the //stdcall// calling convention, any parameters are to be passed (pushed onto the stack) in the reverse order in which they are listed, that is, from right to left. The procedures need not preserve the ##EAX##, ##ECX## or ##EDX## registers, and must clean up the stack (pop any parameters) before it returns. ##**Stdcall**## is not allowed to be used with variadic procedure declarations (those with the last parameter listed as "##[[KeyPgDots ...]]##"). //stdcall// is the default calling convention for procedures not declared with a calling convention specifier, or that are declared within ##[[KeyPgExternBlock Extern "Windows"]]## blocks. //stdcall// is also the standard calling convention used in BASIC languages, and the Windows API. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/procs/stdcall.bas"}}%%(freebasic) Declare Function Example stdcall (param1 As Integer, param2 As Integer) As Integer Declare Function Example2 cdecl (param1 As Integer, param2 As Integer) As Integer Function Example (param1 As Integer, param2 As Integer) As Integer ' This is an STDCALL function, the first parameter on the stack is param2, since it was pushed last. Print param1, param2 Return param1 Mod param2 End Function Function Example2 cdecl (param1 As Integer, param2 As Integer) As Integer ' This is a CDECL function, the first parameter on the stack is param1, since it was pushed last. Print param1, param2 Return param1 Mod param2 End Function %% {{fbdoc item="target"}} - On Dos and Windows systems, //stdcall// procedures append an "@//N//" decoration to the internal/external procedure name, where //N// is the size of the parameter list, in bytes. - On Linux systems, //stdcall// procedures are the same as //cdecl// procedures (//see [[KeyPgCdecl Cdecl]], [[KeyPgExternBlock Extern "C"]]//), except that variadic procedures are still not allowed. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - [[KeyPgPascal Pascal]], [[KeyPgCdecl Cdecl]] - [[KeyPgDeclare Declare]] - [[KeyPgSub Sub]], [[KeyPgFunction Function]] {{fbdoc item="back" value="CatPgProcedures|Procedures"}}{{fbdoc item="title" value="STEP"}}---- Statement modifier. {{fbdoc item="syntax"}}## [[KeyPgFornext For]] //iterator// = //initial_value// To //end_value// **Step** //increment// [[KeyPgLinegraphics Line]] [ //buffer//, ] **Step** ( //x1//, //y1// ) - **Step** ( //x2//, //y2// ) [, [ //color// ][, [ B|BF ][, //style// ] ] ] [[KeyPgCircle Circle]] [ //target,// ] **Step** ( //x//, //y// ), //radius// [, [ //color// ][, [ //start// ][, [ //end// ][, [ //aspect// ][, F] ] ] ] ] [[KeyPgPaint Paint]] [ //target//, ] STEP ( //x//, //y// ) [, [ //paint// ][, [ //border_color// ] ] ] ## {{fbdoc item="desc"}} In a ##[[KeyPgFornext For]]## statement, ##**Step**## specifies the increment of the loop iterator with each loop. In a ##[[KeyPgLinegraphics Line]]##, ##[[KeyPgCircle Circle]]## or ##[[KeyPgPaint Paint]]## statement, ##**Step**## indicates that the following coordinate has values relative to the graphics cursor. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/control/step.bas"}}%%(freebasic) dim i as integer FOR I=10 TO 1 STEP -1 NEXT %% {{fbdoc item="filename" value="examples/manual/gfx/step.bas"}}%%(freebasic) LINE -STEP(10,10),13 %% {{fbdoc item="see"}} - ##[[KeyPgFornext For...Next]]## - ##[[KeyPgLinegraphics Line]]## - ##[[KeyPgCircle Circle]]## - ##[[KeyPgPaint Paint]]## {{fbdoc item="back" value="CatPgMisc|Miscellaneous"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:59:18 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 368b10aada993b7ad15d5efc0029013e Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 2266 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="STICK"}}---- Reads axis position from attached gaming devices {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Stick** ( [[KeyPgByval byval]] //axis// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **Stick**( //axis// ) ## {{fbdoc item="param"}} ##//axis//## the axis number to query for position {{fbdoc item="ret"}} Returns a number between 1 and 200 for specified ##//axis//##, otherwise zero (0), if the device is not attached. {{fbdoc item="desc"}} ##**Stick**## will retrieve the axis position for the first and second axes on the first and second gaming devices. ##//axis//## must be a number between 0 and 3 having the following meaning: {{table columns="2" cells="Axis;Returns;0;X position of gaming device A;1;Y position of gaming device A when STICK(0) was called;2;X position of gaming device B when STICK(0) was called;3;Y position of gaming device B when STICK(0) was called"}} ##**Stick(0)**## must first be called to obtain the positions for the other axes. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/input/stick.bas"}}%%(freebasic) '' Compile with -lang qb Screen 12 Do Locate 1, 1 Print "Joystick A-X position : "; Stick(0); " " Print "Joystick A-Y position : "; Stick(1); " " Print "Joystick B-X position : "; Stick(2); " " Print "Joystick B-Y position : "; Stick(3); " " Print Print "Button A1 was pressed : "; Strig(0); " " Print "Button A1 is pressed : "; Strig(1); " " Print "Button B1 was pressed : "; Strig(2); " " Print "Button B1 is pressed : "; Strig(3); " " Print "Button A2 was pressed : "; Strig(4); " " Print "Button A2 is pressed : "; Strig(5); " " Print "Button B2 was pressed : "; Strig(6); " " Print "Button B2 is pressed : "; Strig(7); " " Print Print "Press ESC to Quit" If Inkey$ = Chr$(27) Then Exit Do End If Sleep 1 Loop %% {{fbdoc item="lang"}} - Only available in the //[[CompilerOptlang -lang qb]]// dialect. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgGetjoystick Getjoystick]]## - ##[[KeyPgStrig Strig]]## {{fbdoc item="back" value="CatPgGfxInput|User Input Functions"}} {{fbdoc item="title" value="STOP"}}---- Halts program execution, and waits for a key press before ending the program. {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Stop** ( [[KeyPgByval byval]] //retval// [[KeyPgAs as]] [[KeyPgInteger integer]] = 0 ) ## {{fbdoc item="usage"}}## **Stop** ## {{fbdoc item="param"}} ##//retval//## Error code returned to system. {{fbdoc item="desc"}} Halts the execution of the program and stands by. It's provided as a help to debugging, as it preserves the memory and doesn't close files. For normal program termination the ##[[KeyPgEnd End]]## keyword should be used. An optional return value, an integer, can be specified to return an error code to the system. If no return value is given, a value of 0 is automatically returned. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/debug/stop.bas"}}%%(freebasic) print "this text is shown" sleep stop print "this text will never be shown" %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgEnd End]]## {{fbdoc item="back" value="CatPgMisc|Miscellaneous"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:59:26 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: e406b67431068c59c3888a239dbdadab Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 3959 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="STR"}}---- Returns a string representation of a number or Unicode character string {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Str** [[KeyPgOverload overload]] ( [[KeyPgByval byval]] //n// [[KeyPgAs as]] [[KeyPgByte byte]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Str** ( [[KeyPgByval byval]] //n// [[KeyPgAs as]] [[KeyPgUbyte ubyte]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Str** ( [[KeyPgByval byval]] //n// [[KeyPgAs as]] [[KeyPgShort short]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Str** ( [[KeyPgByval byval]] //n// [[KeyPgAs as]] [[KeyPgUshort ushort]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Str** ( [[KeyPgByval byval]] //n// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Str** ( [[KeyPgByval byval]] //n// [[KeyPgAs as]] [[KeyPgUinteger uinteger]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Str** ( [[KeyPgByval byval]] //n// [[KeyPgAs as]] [[KeyPgLongint longint]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Str** ( [[KeyPgByval byval]] //n// [[KeyPgAs as]] [[KeyPgUlongint ulongint]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Str** ( [[KeyPgByval byval]] //n// [[KeyPgAs as]] [[KeyPgSingle single]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Str** ( [[KeyPgByval byval]] //n// [[KeyPgAs as]] [[KeyPgDouble double]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Str** ( [[KeyPgByref byref]] //str// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Str** ( [[KeyPgByval byval]] //str// [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgPtr ptr]] ) [[KeyPgAs as]] [[KeyPgString string]] ## {{fbdoc item="usage"}}## //result// = **Str**[$]( //number// ) //or// //result// = **Str**( //string// ) ## {{fbdoc item="param"}} ##//number//## Numeric expression to convert to a string. ##//string//## String expression to convert to a string. {{fbdoc item="desc"}} ##**Str**## converts numeric variables to their string representation. Used this way it is the ##[[KeyPgString String]]## equivalent to ##[[KeyPgWstr Wstr]]## applied to numeric variables, and the opposite of the ##[[KeyPgVal Val]]## function, which converts a string into a number. ##**Str**## also converts Unicode character strings to ASCII character strings. Used this way it does the opposite of ##[[KeyPgWstr Wstr]]##. If an ASCII character string is given, that string is returned unmodified. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/str.bas"}}%%(freebasic) dim a as integer dim b as string a = 8421 b = str(a) print a, b %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// dialect, ##**Str**## will left pad a positive number with a space. - The string type suffix "$" is obligatory in the //[[CompilerOptlang -lang qb]]// dialect. - The string type suffix "$" is optional in the //[[CompilerOptlang -lang fblite]]// and //[[CompilerOptlang -lang fb]]// dialects. {{fbdoc item="target"}} - DOS version/target of FreeBASIC does not support the wide-character string version of ##**Str**##. {{fbdoc item="diff"}} - QB does not support the wide-character string version of ##**Str**##. {{fbdoc item="see"}} - ##[[KeyPgVal Val]]## - ##[[KeyPgChr Chr]]## - ##[[KeyPgAsc Asc]]## {{fbdoc item="back" value="CatPgCasting|Converting Data Types"}}{{fbdoc item="back" value="CatPgString|String Functions"}} {{fbdoc item="title" value="STRIG"}}---- Reads button state from attached gaming devices {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Strig** ( [[KeyPgByval byval]] //button// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **Strig**( //button// ) ## {{fbdoc item="param"}} ##//button//## the button to query for state {{fbdoc item="ret"}} Returns -1 (pressed) or 0 (not-pressed) to indicate the state of the ##//button//## requested. {{fbdoc item="desc"}} ##**Strig**## will retrieve the button state for the first and second buttons on the first and second gaming devices. ##//button//## must be a number between 0 and 7 and has the following meaning: {{table columns="2" cells="Button;State to return;0;First button on gaming device A pressed since STICK(0) was called;1;First button on gaming device A is pressed;2;First button on gaming device B pressed since STICK(0) was called;3;First button on gaming device A is pressed;4;Second button on gaming device A pressed since STICK(0) was called;5;First button on gaming device A is pressed;6;Second button on gaming device B pressed since STICK(0) was called;7;First button on gaming device A is pressed"}} Calling ##**Stick(0)**## will reset the state returned where ##//button//## is equal to 0, 2, 4, or 6. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/input/strig.bas"}}%%(freebasic) '' Compile with -lang qb Screen 12 Do Locate 1, 1 Print "Joystick A-X position : "; Stick(0); " " Print "Joystick A-Y position : "; Stick(1); " " Print "Joystick B-X position : "; Stick(2); " " Print "Joystick B-Y position : "; Stick(3); " " Print Print "Button A1 was pressed : "; Strig(0); " " Print "Button A1 is pressed : "; Strig(1); " " Print "Button B1 was pressed : "; Strig(2); " " Print "Button B1 is pressed : "; Strig(3); " " Print "Button A2 was pressed : "; Strig(4); " " Print "Button A2 is pressed : "; Strig(5); " " Print "Button B2 was pressed : "; Strig(6); " " Print "Button B2 is pressed : "; Strig(7); " " Print Print "Press ESC to Quit" If Inkey$ = Chr$(27) Then Exit Do End If Sleep 1 Loop %% {{fbdoc item="lang"}} - Only available in the //[[CompilerOptlang -lang qb]]// dialect. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgGetjoystick Getjoystick]]## - ##[[KeyPgStick Stick]]## {{fbdoc item="back" value="CatPgGfxInput|User Input Functions"}}{{fbdoc item="title" value="STRING"}}---- Standard data type: 8 bit character string {{fbdoc item="syntax"}}## [[KeyPgDim dim]] //variable// [[KeyPgAs as]] **String** [ * //size//] ## {{fbdoc item="desc"}} A ##**String**## is an array of characters. A ##**String**## declared without the ##//size//## parameter is dynamically resized depending on the length of the string. The length can range from 0 bytes to 2 gigabytes. A descriptor contains a pointer to the actual string and the length of the string. ##[[KeyPgOpVarptr Varptr]]## will return a pointer to the descriptor, while ##[[KeyPgOpStrptr Strptr]]## will point to the actual string. Despite the use of the descriptor, an implicit NULL character (##[[KeyPgChr chr$]](0)##) is added to the end of the string, to allow passing them to functions in external libraries without making slow copies. ""FreeBASIC""'s internal functions will ignore this character, and not treat it as part of the string. A ##**String**## declared with ##//size//## is a QB-style fixed length string. It has no descriptor and it is not resized to fit its contents. As in QB, if data overflows the size of the string, it is truncated on the right side. Fixed length strings are also terminated with a NULL character, and so they use ##//size// + 1## bytes of space. This NULL terminator may be removed in future, to prevent the redundant character complicating data layout in user-defined ##[[KeyPgType Type]]##s. String variable names need not end in a dollar sign as in other dialects of BASIC. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/datatype/string.bas"}}%%(freebasic) '' Compile with -lang fblite or qb '' Variable-length dim a as string a = "Hello" '' Or dim b$ b$ = "World" '' Fixed-length dim c as string * 32 c = "Hello World" %% {{fbdoc item="diff"}} - In QB the strings were limited to 32767 characters. - In QB static or fixed-size strings were often used in records to represent a number of bytes of data; for example, a string of 1 length to represent 1 byte in a UDT read from a file. This is not possible in FreeBASIC since strings always have an NULL character following. When converting QBasic code that reads UDTs from files, make sure all instances of "##As String * //n//##" are replaced with "##As uByte (0 to //n// - 1)##" or your files will be incompatible. {{fbdoc item="see"}} - ##[[KeyPgStringFunction String (Function)]]## - ##[[KeyPgZstring Zstring]]## - ##[[KeyPgStr Str]]## - ##[[KeyPgOpStrptr Strptr]]## - ##[[KeyPgOpVarptr Varptr]]## {{fbdoc item="back" value="CatPgStdDataTypes|Standard Data Types"}}{{fbdoc item="back" value="CatPgString|String Functions"}}{{fbdoc item="title" value="STRING (Function)"}}---- Creates and fills a string of a certain length with a certain character {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **String**( //count// [[KeyPgAs as]] [[KeyPgInteger integer]], //ch_code// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **String**( //count// [[KeyPgAs as]] [[KeyPgInteger integer]], //ch// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgString string]] ## {{fbdoc item="usage"}}## //result// = **String**[$]( //count//, //ch_code// ) ##//or//## //result// = **String**[$]( //count//, //ch// ) ## {{fbdoc item="param"}} ##//count//## An integer specifying the length of the string to be created. ##//ch_code//## An integer specifying the ASCII character code to be used to fill the string. ##//ch//## A string whose first character is to be used to fill the string. {{fbdoc item="ret"}} The created string. An empty string will be returned if either ##//ch//## is an empty string, or ##//count//## <= 0. {{fbdoc item="desc"}} A list of [[CptAscii ASCII character codes]]. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/string.bas"}}%%(freebasic) PRINT STRING( 4, 69 ) '' prints "EEEE" PRINT STRING( 5, "Indeed" ) '' prints "IIIII" end 0 %% {{fbdoc item="lang"}} - The string type suffix "$" is obligatory in the //[[CompilerOptlang -lang qb]]// dialect. - The string type suffix "$" is optional in the //[[CompilerOptlang -lang fblite]]// and //[[CompilerOptlang -lang fb]]// dialects. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgString String]] (data type)## - ##[[KeyPgSpace Space]]## {{fbdoc item="back" value="CatPgString|String Functions"}}{{fbdoc item="title" value="SUB"}}---- Defines a procedure {{fbdoc item="syntax"}}## [[[KeyPgPublic Public]]|[[KeyPgPrivate Private]]] **Sub** //identifier// [[[KeyPgCdecl CDecl]]|[[KeyPgPascal Pascal]]|[[KeyPgStdcall StdCall]]] [[[KeyPgOverload Overload]]] [[[KeyPgAlias Alias]] //external_identifier//] [( [//parameter_list//] )] [[[KeyPgStatic Static]]] //statements// ... [[[KeyPgReturn Return]]] ... [[KeyPgEndblock End]] Sub [[[KeyPgPublic Public]]] **Sub** //identifier// [[[KeyPgCdecl CDecl]]|[[KeyPgPascal Pascal]]|[[KeyPgStdcall StdCall]]] [[[KeyPgOverload Overload]]] [[[KeyPgAlias Alias]] //external_identifier//] [()] [[[KeyPgModuleConstructor Constructor]]|[[KeyPgModuleDestructor Destructor]]] [[[KeyPgStatic Static]]] //statements// ... [[[KeyPgReturn Return]]] ... [[KeyPgEndblock End]] Sub ## {{fbdoc item="param"}} ##//identifier//##: the name of the subroutine ##//external_identifier//##: externally visible (to the linker) name enclosed in quotes ##//parameter_list//##: parameter[, parameter[, ...]] ##//parameter//##: ##[[[KeyPgByref ByRef]]|[[KeyPgByval ByVal]]] //identifier// [[[KeyPgAs As]] //type//] [= //default_value//]## ##//identifier//##: the name of the variable referenced in the subroutine ##//type//##: the type of variable ##//default_value//##: the value of the argument if none is specified in the call ##//statements//##: one or more statements that make up the subroutine body {{fbdoc item="desc"}} A subroutine is a block of code which may be called at any time from a program. This code may need to be executed multiple times, and subroutines provide an invaluable means to simplify code by replacing these blocks of code with a single subroutine call. A subroutine also serves to allow a user to extend the FreeBASIC language to provide custom commands. Many of the functions built into FreeBASIC are merely subroutines part of a "runtime library" linked to by default. The ##**Sub**## keyword marks the beginning of a subroutine, and its end is marked by ##**End Sub**##. The "name" parameter is the name by which this subroutine is called. For instance, if the declaration is "##**Sub**...**End Sub**##", the user can execute the code in between "##**Sub** foo##" and "##**End Sub**##" by using "##foo##" as a statement. This code is executed separate from the code which calls the subroutine, so any variable names, unless they are shared, are not available to the subroutine. Values can, however, be passed using parameters. Parameters are the arguments passed to any statement. For instance, if a user executes a statement as "##[[KeyPgPrint Print]] 4##", the value "4" is passed to the function "##[[KeyPgPrint Print]]##". Parameters that need to be passed to a subroutine are supplied by one or more parameter arguments in the "##**Sub**##" keyword. Creating a subroutine with "##**Sub** mysub(foo, bar)...**End Sub**##", allows the code in between "##**Sub**##" and "##**End Sub**##" to refer to the first passed argument as "foo" and the second passed argument as "bar". If a parameter is given a default value, that parameter is optional. Parameters must also have a supplied type, in the form "##//parameter// as //type//##". If this is omitted, ##//type//## is assumed to be ##[[KeyPgInteger Integer]]##. A passed value MUST be of the type specified. A subroutine can also specify how parameters are passed, either as "##[[KeyPgByref Byref]]##" or "##[[KeyPgByval Byval]]##", as shown in the syntax definition. If a parameter is "##[[KeyPgByref Byref]]##", the parameter name literally becomes a reference to the original variable passed to the subroutine. Any changes made to that variable will be reflected outside of the subroutine. If a parameter is passed "##[[KeyPgByval Byval]]##", however, the value of any passed variable is copied into a new variable, and any changes made to it will not affect the original. The ##[[KeyPgStatic Static]]## specifier indicates that the values of all local variables defined in the sub should be preserved between calls. To specify individual local variables as static see the ##[[KeyPgStatic Static]]## keyword. Sub is the same as ##[[KeyPgFunction Function]]##, except it does not allow a value to be returned. The second syntax defines either a constructor or destructor using the ##[[KeyPgModuleConstructor Constructor]]## and ##[[KeyPgModuleDestructor Destructor]]## keywords, respectively. Constructor subroutines are executed before the first line of code in the module, while destructors execute on module exit. Note the public access specifier and empty parameter list for both constructors and destructors. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/procs/sub-1.bas"}}%%(freebasic) '' Example of writing colored text using a sub: sub PrintColoredText( byval colour as integer, byref text as string ) color colour print text end sub PrintColoredText( 1, "blue" ) '' a few colors PrintColoredText( 2, "green" ) PrintColoredText( 4, "red" ) print dim i as integer for i = 0 to 15 '' all 16 colors PrintColoredText( i, ("color " & i) ) next i %% {{fbdoc item="filename" value="examples/manual/procs/sub-2.bas"}}%%(freebasic) ' The following demonstrates optional parameters. Sub TestSub(P As String = "Default") Print P End Sub TestSub "Testing:" TestSub %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang fb]]// dialect the parameters are passed ##[[KeyPgByval Byval]]## by default. - The //[[CompilerOptlang -lang qb]]// and //[[CompilerOptlang -lang fblite]]// dialects keep the QB convention: parameters are ##[[KeyPgByref Byref]]## by default. {{fbdoc item="diff"}} - Public and Private access specifiers are new to FreeBASIC - Constructor subroutines are new to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDeclare Declare]]## - ##[[KeyPgFunction Function]]## - ##[[KeyPgExit Exit]]## - ##[[KeyPgPublic Public]]## - ##[[KeyPgPrivate Private]]## - ##[[KeyPgStatic Static]]## {{fbdoc item="back" value="CatPgProcedures|Procedures"}}{{fbdoc item="title" value="SWAP"}}---- Exchanges the values of two variables {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Swap** ( [[KeyPgByref byref]] //a// [[KeyPgAs as]] [[KeyPgAny any]], [[KeyPgByref byref]] //b// [[KeyPgAs as]] [[KeyPgAny any]] ) ## {{fbdoc item="param"}} ##//a//## A value to swap. ##//b//## A value to swap. {{fbdoc item="desc"}} Swaps the value of two variables. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/memory/swap.bas"}}%%(freebasic) ' using swap to order 2 numbers: dim a as integer, b as integer input "input a number: "; a input "input another number: "; b if a > b then swap a, b print "the numbers, in ascending order are:" print a, b %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - {{fbdoc item="back" value="CatPgMemory|Memory Functions"}}{{fbdoc item="title" value="SYSTEM"}}---- Closes all open files and ends the program {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **System** ( [[KeyPgByval byval]] //retval// [[KeyPgAs as]] [[KeyPgInteger integer]] = 0 ) ## {{fbdoc item="usage"}}## **System**( [ //retval// ] ) ## {{fbdoc item="param"}} ##//retval//## Error code returned to system. {{fbdoc item="desc"}} Closes all open files and returns to the system. An optional return value, an integer, can be specified to return an error code to the system. If no return value is given, a value of 0 is automatically returned. This is the same as ##[[KeyPgEnd End]]## and is here for compatibility between older BASIC dialects. It is recommended to use ##[[KeyPgEnd End]]## instead. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/system/system.bas"}}%%(freebasic) print "this text is shown" system print "this text will never be shown" %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgEnd End]]## {{fbdoc item="back" value="CatPgOpsys|Operating System Functions"}}{{fbdoc item="title" value="TAB"}}---- Sets the column when writing to screen or file {{fbdoc item="syntax"}}## **Tab**( //column// ) ## {{fbdoc item="usage"}}## [[KeyPgPrint Print]] **Tab**( //column// ) [(, | ;)] ... ## {{fbdoc item="param"}} ##//column//## column to move to {{fbdoc item="desc"}} **Tab** will move the cursor to ##//column//## when ##[[KeyPgPrint Print]]##ing to screen or to a file. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/console/tab.bas"}}%%(freebasic) print "foo"; tab(5); "bar" print "hello"; tab(5); "world" %% {{fbdoc item="diff"}} - None. {{fbdoc item="see"}} - ##[[KeyPgPrint Print]]## - ##[[KeyPgSpc Spc]]## {{fbdoc item="back" value="CatPgConsole|Console Functions"}} {{fbdoc item="title" value="TAN"}}---- Gets the tangent of a number {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Tan** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgDouble double]] ) [[KeyPgAs as]] [[KeyPgDouble double]] ## {{fbdoc item="usage"}}## //result// = **Tan** ( //number// ) ## {{fbdoc item="param"}} ##//number//## the angle (in radians) {{fbdoc item="ret"}} Returns the tangent of the argument ##//number//## as a ##[[KeyPgDouble Double]]## within the range of -infinity to infinity. {{fbdoc item="desc"}} The argument ##//number//## is measured in [[TutMathAngles radians]] (not [[TutMathAngles degrees]]). The required //number// argument can be any valid numeric expression. If ##//number//## is an uninitialized variable, zero is returned. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/math/tan.bas"}}%%(freebasic) CONST PI AS DOUBLE = 3.1415926535897932 DIM a AS DOUBLE DIM r AS DOUBLE INPUT "Please enter an angle in degrees: ", a r = a * PI / 180 'Convert the degrees to Radians PRINT "" PRINT "The tangent of a" ; a; " degree angle is"; TAN ( r ) SLEEP %% The output would look like: %% Please enter an angle in degrees: 75 The tangent of a 75 degree angle Is 3.732050807568878 %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgAtn Atn]]## - ##[[KeyPgAtan2 Atan2]]## - [[TutMathIntroTrig A Brief Introduction To Trigonometry]] {{fbdoc item="back" value="CatPgMath|Math"}}{{fbdoc item="title" value="THEN"}}---- Control flow statement for conditional branching. {{fbdoc item="syntax"}}## **If** //expression// **Then** //statement(s)// [**Else** //statement(s)//] //or// **If** //expression// **Then** : //statement(s)// [**Else** //statement(s)//] : **End If** //or// **If** //expression// **Then** //statement(s)// [ **Elseif** //expression// **Then** ] //statement(s)// [ **Else** ] //statement(s)// **End If** ## {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgIfthen If...Then]]## {{fbdoc item="back" value="CatPgMisc|Miscellaneous"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:59:38 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 8f27270ae61b31cc8ec42a7bfd26295e Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 1514 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="This"}}---- Hidden instance parameter passed to non-static member functions in a ##[[KeyPgType Type]]## or ##[[KeyPgClass Class]]## {{fbdoc item="syntax"}}## **this**.//fieldname// //or// [[KeyPgWith With]] **this** .//fieldname// End With ## {{fbdoc item="desc"}} ##**This**## is a hidden parameter passed to all non-static member functions of a ##[[KeyPgType Type]]## or ##[[KeyPgClass Class]]##. Non-static member functions are procedures declared inside the body of a ##[[KeyPgType Type]]## or ##[[KeyPgClass Class]]## and include ##[[KeyPgMemberSub Sub]]##, ##[[KeyPgMemberFunction Function]]##, ##[[KeyPgConstructor Constructor]]##, ##[[KeyPgDestructor Destructor]]##, assignment or cast ##[[KeyPgOperator Operator]]##, and ##[[KeyPgProperty Property]]## procedures. The ##**This**## parameter has the same data type as the ##[[KeyPgType Type]]## or ##[[KeyPgClass Class]]## in which the procedure is declared. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/udt/this.bas"}}%%(freebasic) TYPE sometype DECLARE SUB MyCall() value AS INTEGER END TYPE DIM example AS sometype '' Set element test to 0 example.value = 0 print example.value example.MyCall() '' Output should now be 10 print example.value END 0 SUB sometype.MyCall() This.value = 10 END SUB %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgClass Class]]## - ##[[KeyPgType Type]]## {{fbdoc item="back" value="CatPgUserDefTypes|User Defined Types"}} {{fbdoc item="title" value="THREADCREATE"}}---- Starts a user-defined procedure in a separate execution thread {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Threadcreate** ( [[KeyPgByval byval]] //proc// [[KeyPgAs as]] [[KeyPgSub sub]] ( [[KeyPgByval byval]] [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] ), [[KeyPgByval byval]] //param// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] = 0, [[KeyPgByval byval]] //stack_size// [[KeyPgAs as]] [[KeyPgInteger integer]] = 0 ) [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] ## {{fbdoc item="usage"}}## //result// = **Threadcreate** ( //proc// [, [ //param// ] [, //stack_size// ] ] ) ## {{fbdoc item="param"}} ##//proc//## A pointer to the ##[[KeyPgSub Sub]]## intended to work as a thread. ##//param//## Optional [[KeyPgAny any]] [[KeyPgPtr ptr]] argument for the ##[[KeyPgSub Sub]]## pointed to by ##//proc//## (it can be a pointer to a structure or an array if more arguments are needed). ##//stack_size//## Optional number of bytes to reserve for this thread's stack. {{fbdoc item="ret"}} **Threadcreate** returns an ##[[KeyPgAny any]] [[KeyPgPtr ptr]]## handle to the thread created, or the null pointer (0) on failure. {{fbdoc item="desc"}} The user function is started as a thread executes in parallel with the main part of the program. The OS achieves this by assigning it to a different processor if it exists, or using the waiting times in the main program. Before closing, a program must wait for the termination of all the threads it has launched; see ##[[KeyPgThreadWait Threadwait]]##. To avoid simultaneous access to shared resources from different threads, FreeBASIC implements mutexes, mutual exclusion locks that can be "owned" by a single thread when doing critical work. See ##[[KeyPgMutexCreate Mutexcreate]]##, ##[[KeyPgMutexLock Mutexlock]]##, ##[[KeyPgMutexUnlock Mutexunlock]]##, ##[[KeyPgMutexDestroy Mutexdestroy]]##. On some systems, the stack automatically grows beyond ##//stack_size//## if more space is needed; on others, this is the fixed maximum allowed. Behavior is undefined when more stack is used than the reserved size on systems where stacks are not able to grow. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/threads/threadcreate.bas"}}%%(freebasic) dim shared terminate as integer =0 sub mythread (param as any ptr) dim a as integer, b as integer while 1 b=0 while b<80 print "*"; a=0 while a<&h7ffffff a+=1 wend b+=1 wend if terminate=1 then exit sub wend end sub dim thread as any ptr dim a as integer, b as integer print "Main program prints dots" print "Thread prints asterisks" thread=threadcreate(@mythread,0) print "Thread launched"; b=0 while b<80 a=0 while a<&h3 print "."; a+=1 wend b+=1 wend terminate=1 print "Terminate launched"; threadwait (thread) print "Thread terminated" sleep %% {{fbdoc item="lang"}} - Threading is not allowed in ##-lang qb## {{fbdoc item="target"}} - **Threadcreate** is not available with the DOS version / target of FreeBASIC, because multithreading is not supported by DOS kernel nor the used extender. - In Linux the threads are always started in the order they are created, this can't be assumed in Win32. It's an OS, not a FreeBASIC issue. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgThreadWait Threadwait]]## - ##[[KeyPgMutexCreate Mutexcreate]]## - ##[[KeyPgMutexLock Mutexlock]]## - ##[[KeyPgMutexUnlock Mutexunlock]]## - ##[[KeyPgMutexDestroy Mutexdestroy]]## {{fbdoc item="back" value="CatPgThreading|Threading Support Functions"}}{{fbdoc item="title" value="THREADWAIT"}}---- Waits until the designated thread has been completed before returning {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Threadwait** ( [[KeyPgByval byval]] //id// [[KeyPgAs as]] [[KeyPgAny any]] [[KeyPgPtr ptr]] ) ## {{fbdoc item="usage"}}## **Threadwait**( //id// ) ## {{fbdoc item="param"}} ##//id//## ##[[KeyPgAny any]] [[KeyPgPtr ptr]]## handle of a thread created by ##[[KeyPgThreadCreate Threadcreate]]## {{fbdoc item="desc"}} ##Threadwait## doesn't return until the thread designated by ##//id//## ends. ##Threadwait## does not force the thread to end; if a thread requires a signal to force its end, a mechanism such as shared variables must be used. Threads are launched by the ##[[KeyPgThreadCreate Threadcreate]]## function. To avoid simultaneous access to shared resources from different threads, FreeBASIC implements mutexes, mutual exclusion locks that can be "owned" by a single thread when doing critical work. See ##[[KeyPgMutexCreate Mutexcreate]]##, ##[[KeyPgMutexLock Mutexlock]]##, ##[[KeyPgMutexUnlock Mutexunlock]]##, ##[[KeyPgMutexDestroy Mutexdestroy]]## {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/threads/threadwait.bas"}}%%(freebasic) dim shared printsync as any ptr sub mythread(byval idp as any ptr) var id = cint(idp) dim as double t, w dim as integer i, n if( id = 1 ) then w = 1 n = 10 else w = 0.3 n = 5 end if for i = 1 to n mutexlock printsync print "Thread #"; id; ": on step #"; i mutexunlock printsync '' simulate some work t = timer while( timer - t ) < w wend next i mutexlock printsync print "Thread #"; id; " is done " mutexunlock printsync end sub dim as any ptr t1, t2 print "Starting threads ... " '' create a mutex to sync printing printsync = MutexCreate() '' create 2 threads, each taking a different '' amount of time to complete t1 = threadcreate( @mythread, cast(any ptr, 1) ) t2 = threadcreate( @mythread, cast(any ptr, 2) ) '' wait for threads to complete threadwait( t1 ) threadwait( t2 ) mutexdestroy printsync print "All done." %% {{fbdoc item="lang"}} - Threading is not allowed in ##-lang qb## {{fbdoc item="target"}} - **Threadwait** is not available with the DOS version / target of FreeBASIC, because multithreading is not supported by DOS kernel nor the used extender. - In Linux the threads are always started in the order they are created, this can't be assumed in Win32. It's an OS, not a FreeBASIC issue. {{fbdoc item="diff"}} - New to Freebasic {{fbdoc item="see"}} - ##[[KeyPgThreadCreate Threadcreate]]## - ##[[KeyPgMutexCreate Mutexcreate]]## - ##[[KeyPgMutexLock Mutexlock]]## - ##[[KeyPgMutexUnlock Mutexunlock]]## - ##[[KeyPgMutexDestroy Mutexdestroy]]## {{fbdoc item="back" value="CatPgThreading|Threading Support Functions"}}{{fbdoc item="title" value="TIME"}}---- Returns the current system time as a string {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Time** ( ) [[KeyPgAs as]] [[KeyPgString string]] ## {{fbdoc item="usage"}}## //result// = **Time** ## {{fbdoc item="ret"}} Returns the current system. {{fbdoc item="desc"}} Returns the current system time in the format ##hh:mm:ss##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/dates/time.bas"}}%%(freebasic) print "the current time is: "; time %% {{fbdoc item="diff"}} - The QB TIME statement (to set the system time) is now called ##[[KeyPgSettime Settime]]##. {{fbdoc item="see"}} - ##[[KeyPgDate Date]]## - ##[[KeyPgTimer Timer]]## {{fbdoc item="back" value="CatPgDate|Date and Time Functions"}}{{fbdoc item="title" value="TIMER"}}---- Returns the amount of time that has passed since a static reference point. {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Timer** ( ) [[KeyPgAs as]] [[KeyPgDouble double]] ## {{fbdoc item="usage"}}## //result// = **Timer** ## {{fbdoc item="ret"}} Returns a ##[[KeyPgDouble double]]## precision result with the time, in seconds, since a static reference point. {{fbdoc item="desc"}} The ##**Timer**## function is useful for finding out how long a section of code takes to run, or for control the timing of your code. To find out how much time has passed between two points in your program, you can record the value of ##**Timer**## at the start and end points, and then subtract the start value from the end value. On some platforms, the value of ##**Timer**## resets to zero at midnight (see below), so if the start and end time are on either side of the reset point, the difference will be negative. This could cause unexpected behavior in some programs. In those cases, adding ##86400## (the number of seconds in 24 hours) to the difference should return the correct result. If the time taken is longer than a day, then it will be also be necessary to check the number of days that have elapsed. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/dates/timer.bas"}}%%(freebasic) '' Example of using TIMER function '' Note: see text about correct waiting strategies Dim Start As Double Print "Wait 2.5 seconds." Start = Timer Do Sleep 1, 1 Loop Until (Timer - Start) > 2.5 Print "Done." %% {{fbdoc item="target"}} - On Win32 and Linux, if the program must wait for periods of 0.1 seconds or more, ##[[KeyPgSleep Sleep]]## should be used, this allows other programs to run during the waiting period. For shorter delays, a loop using TIMER can be more precise. - The reference point chosen varies, depending on the platform. On Windows, the time is measured relative to the point the computer was turned on. On DOS, the time is measured relative to midnight, and resets to 0 every time midnight is reached. - The precision of TIMER varies, depending on the computer used. If the processor has a precision timer (as the Performance Counter Pentium processors from Intel have) the precision is linked to the processor clock and microseconds can be expected. With older processors (386, 486) the resolution is 1/18 second. {{fbdoc item="diff"}} - In QB TIMER returned the number of seconds from last midnight, and its accuracy was 1/18 secs {{fbdoc item="see"}} - ##[[KeyPgTime Time]]## - ##[[KeyPgSleep Sleep]]## {{fbdoc item="back" value="CatPgDate|Date and Time Functions"}}{{fbdoc item="title" value="TIMESERIAL"}}---- Gets a [[ProPgDates Date Serial]] for the specified hours, minutes, and seconds {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""TimeSerial""** ( [[KeyPgByval byval]] //hour// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByval byval]] //minute// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByval byval]] //second// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgDouble double]] ## {{fbdoc item="usage"}}## #include "vbcompat.bi" //result// = **""TimeSerial""**( //hours//, //minutes//, //seconds// ) ## {{fbdoc item="param"}} ##//hour//## number of hours, in the range 0-23 ##//minute//## number of minutes ##//second//## number of seconds {{fbdoc item="ret"}} Returns a [[ProPgDates date serial]] containing the time formed by the values in the ##//hours//##, ##//minutes//## and ##//seconds//## parameters.The date serial returned has no integer part. {{fbdoc item="desc"}} ##//hours//## must be specified in the range 0-23 The compiler will not recognize this function unless ##vbcompat.bi## or ##datetime.bi## is included. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/dates/timeserial.bas"}}%%(freebasic) #include "vbcompat.bi" Dim ds As Double = DateSerial(2005, 11, 28) + TimeSerial(7, 30, 50) Print Format(ds, "yyyy/mm/dd hh:mm:ss") %% {{fbdoc item="diff"}} - Did not exist in QB. This function appeared in PDS and VBDOS {{fbdoc item="see"}} - [[ProPgDates Date Serials]] - ##[[KeyPgDateSerial DateSerial]]## - ##[[KeyPgTimeValue TimeValue]]## - ##[[KeyPgDateValue DateValue]]## {{fbdoc item="back" value="CatPgDate|Date and Time Functions"}}{{fbdoc item="title" value="TIMEVALUE"}}---- Gets a [[ProPgDates Date Serial]] from a time string {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""TimeValue""** ( [[KeyPgByref byref]] //timestring// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgDouble double]] ## {{fbdoc item="usage"}}## #include "vbcompat.bi" //result// = **""TimeValue""**( //timestring// ) ## {{fbdoc item="param"}} ##//timestring//## the string to convert {{fbdoc item="ret"}} Returns a [[ProPgDates Date Serial]] from a time string. {{fbdoc item="desc"}} The time string must be in the format ##"23:59:59"## or ##"11:59:59PM"## The compiler will not recognize this function unless ##vbcompat.bi## or ##datetime.bi## is included. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/dates/timevalue.bas"}}%%(freebasic) #include "vbcompat.bi" Dim ds As Double = TimeValue("07:12:28AM") Print Format(ds, "hh:mm:ss") %% {{fbdoc item="diff"}} - Did not exist in QB. This function appeared in PDS and VBDOS {{fbdoc item="see"}} - [[ProPgDates Date Serials]] - ##[[KeyPgDateSerial DateSerial]]## - ##[[KeyPgTimeValue TimeValue]]## - ##[[KeyPgDateValue DateValue]]## {{fbdoc item="back" value="CatPgDate|Date and Time Functions"}}{{fbdoc item="title" value="TO"}}---- Statement modifier to specify a range. {{fbdoc item="syntax"}}## FOR //iterator// //intial_value// TO //ending_value// //statement(s)//. NEXT [ //iterator// ] //or// SELECT CASE //case_comparison_value// CASE //lower_bound// TO //upper_bound// //statement(s)//. END SELECT //or// DIM //variable_identifier//( //lower_bound// TO //upper_bound// ) AS //type_specifier// ## {{fbdoc item="desc"}} The TO keyword is used to define a certain numerical range. This keyword is valid only if used with [[KeyPgFornext FOR ... NEXT]], [[KeyPgSelectcase SELECT / CASE]] and [[KeyPgDim DIM]] statements. In the first syntax, the TO keyword defines the initial and ending values of the iterator in a FOR statement. In the second syntax, the TO keyword defines lower and upper bounds for CASE comparisons. In the third syntax, the TO keyword defines the array bounds in a DIM statement For more information, see [[KeyPgFornext FOR...NEXT]], [[KeyPgDim DIM]] and [[KeyPgSelectcase SELECT CASE]]. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/misc/to.bas"}}%%(freebasic) '' this program uses bound variables along with the TO keyword to create an array, store random '' temperatures inside the array, and to determine output based upon the value of the temperatures Randomize Timer '' define minimum and maximum number of temperatures we will create Const minimum_temp_count As Integer = 1 Const maximum_temp_count As Integer = 10 '' define the range of temperatures zones in which bacteria breed rapidly (in degrees) Const min_low_danger As Integer = 40 Const max_low_danger As Integer = 69 Const min_medium_danger As Integer = 70 Const max_medium_danger As Integer = 99 Const min_high_danger As Integer = 100 Const max_high_danger As Integer = 130 '' define array to hold temperatures using our min/max temp count bounds Dim As Integer array( minimum_temp_count To maximum_temp_count ) '' declare a for loop that iterates from minimum to maximum temp count Dim As Integer it For it = minimum_temp_count To maximum_temp_count array( it ) = Int( Rnd( 1 ) * 200 ) + 1 '' display a message based on temperature using our min/max danger zone bounds Select Case array( it ) Case min_low_danger To max_low_danger Color 11 Print "Temperature" ; it ; " is in the low danger zone at" ; array( it ) ; " degrees!" Case min_medium_danger To max_medium_danger Color 14 Print "Temperature" ; it ; " is in the medium danger zone at" ; array( it ) ; " degrees!" Case min_high_danger To max_high_danger Color 12 Print "Temperature" ; it ; " is in the high danger zone at" ; array( it ) ; " degrees!" Case Else Color 3 Print "Temperature" ; it ; " is safe at" ; array( it ) ; " degrees." End Select Next it Sleep %% {{fbdoc item="diff"}} - none {{fbdoc item="see"}} - ##[[KeyPgFornext For...Next]]## - ##[[KeyPgDim Dim]]## - ##[[KeyPgSelectcase Select Case]]## {{fbdoc item="back" value="CatPgMisc|Miscellaneous"}}{{fbdoc item="title" value="TRANS"}}---- Parameter to the ##[[KeyPgPutgraphics Put]]## graphics statement which selects transparent background as the blitting method {{fbdoc item="syntax"}}## **Put** [ //target//, ] [ STEP ] ( //x//,//y// ), //source// [ ,( //x1//,//y1// )-( //x2//,//y2// ) ], **Trans** ## {{fbdoc item="param"}} ##**Trans**## Required. {{fbdoc item="desc"}} ##**Trans**## selects transparent background as the method for blitting an image buffer. This is similar to the ##PSET## method, but pixels containing the mask color are skipped. For 8-bit color images, the mask color is palette index 0. For 16/32-bit color images, the mask color is Magenta, which is ##[[KeyPgRgb RGB]](255, 0, 255)##. The alpha value is ignored when checking for the mask color in 32-bit images. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/put-trans.bas"}}%%(freebasic) '' set up a screen: 320 * 200, 16 bits per pixel screenres 320, 200, 16 '' set up an image with the mask color as the background. dim img as any ptr = imagecreate( 32, 32, rgb(255, 0, 255) ) circle img, (16, 16), 15, rgb(255, 255, 0), , , 1, f circle img, (10, 10), 3, rgb( 0, 0, 0), , , 2, f circle img, (23, 10), 3, rgb( 0, 0, 0), , , 2, f circle img, (16, 18), 10, rgb( 0, 0, 0), 3.14, 6.28 '' Put the image with PSET (gives the exact contents of the image buffer) draw string (110, 50 - 4), "Image put with PSET" put (60 - 16, 50 - 16), img, pset '' Put the image with TRANS draw string (110, 150 - 4), "Image put with TRANS" put (60 - 16, 150 - 16), img, trans '' free the image memory imagedestroy img '' wait for a keypress sleep %% {{image class="center" title="Put Trans example output" url="/images/trans.png"}} {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgPutgraphics Put (Graphics)]]## {{fbdoc item="back" value="CatPgGfx2D|2D Drawing Functions"}}{{fbdoc item="title" value="TRIM"}}---- Removes surrounding substrings or characters on the left and right side of a string {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Trim** [[KeyPgOverload overload]] ( [[KeyPgByref byref]] //str// [[KeyPgAs as]] [[KeyPgString string]], [ **Any** ] [[KeyPgByref byref]] //trimset// [[KeyPgAs as]] [[KeyPgString string]] = " " ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Trim** ( [[KeyPgByref byref]] //str// [[KeyPgAs as]] [[KeyPgWstring wstring]], [ **Any** ] [[KeyPgByref byref]] //trimset// [[KeyPgAs as]] [[KeyPgWstring wstring]] = [[KeyPgWstr Wstr]](" ") ) [[KeyPgAs as]] [[KeyPgWstring wstring]] ## {{fbdoc item="usage"}}## //result// = **Trim**[$]( //str// [, [ **Any** ] //trimset// ] ) ## {{fbdoc item="param"}} ##//str//## The source string. ##//trimset//## The substring to trim. {{fbdoc item="ret"}} Returns the trimmed string. {{fbdoc item="desc"}} This procedure trims surrounding characters from the left (beginning) and right (end) of a source string. Substrings matching ##//trimset//## will be trimmed if specified, otherwise spaces ([[CptAscii ASCII]] code 32) are trimmed. If the ##**Any**## keyword is used, any character matching a character in ##//trimset//## will be trimmed. All comparisons are case-sensitive. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/trim.bas"}}%%(freebasic) dim s1 as string = " ... Stuck in the middle ... " print "'" + trim(s1) + "'" print "'" + trim(s1, any " .") + "'" dim s2 as string = "BaaBaaaaB With You aaBBaaBaa" Print "'" + trim(s2, "Baa") + "'" Print "'" + trim(s2, any "Ba") + "'" %% will produce the output: %% '... Stuck in the middle ...' 'Stuck in the middle' 'aaB With You aaB' ' With You ' %% {{fbdoc item="target"}} - DOS version/target of FreeBASIC does not support the wide-character version of ##**Trim**##. {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Trim""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - [[KeyPgLtrim Ltrim]] - [[KeyPgRtrim Rtrim]] {{fbdoc item="back" value="CatPgString|String Functions"}}{{fbdoc item="title" value="TYPE"}}---- Declares a user-defined type. {{fbdoc item="syntax"}}## **Type** //typename// [ [[KeyPgField Field]] = //alignment// ] [ [[KeyPgVisPrivate Private]]: ] [ [[KeyPgVisPublic Public]]: ] [ [[KeyPgVisProtected Protected]]: ] [[KeyPgDeclare declare]] [[KeyPgConstructor constructor]] [ ( [ //parameters// ] ) ] [[KeyPgDeclare declare]] [[KeyPgDestructor destructor]] [ () ] [[KeyPgDeclare declare]] [ [[KeyPgStaticMember Static]] | [[KeyPgConstMember Const]] ] [[KeyPgMemberSub sub]] //fieldname// [//calling convention specifier//] [ [[KeyPgAlias alias]] //external_name// ] [ ( [ //parameters// ] ) ] [ [[KeyPgStatic Static]] ] [[KeyPgDeclare declare]] [ [[KeyPgStaticMember Static]] | [[KeyPgConstMember Const]] ] [[KeyPgMemberFunction function]] //fieldname// [//calling convention specifier//] [ [[KeyPgAlias alias]] //external_name// ] [ ( [ //parameters// ] ) ] [ [[KeyPgAs as]] [[DataType datatype]] ] [ [[KeyPgStatic Static]] ] //fieldname// [ ( //array subscripts// ) | : //bits// ] [[KeyPgAs as]] //[[DataType DataType]]// [ = //initializer// ] [[KeyPgAs as]] [[DataType DataType]] //fieldname// [ ( //array subscripts// ) | : //bits// ] [ = //initializer// ], ... [[KeyPgDeclare declare]] [[KeyPgOperator operator]] //operatorname//[ ( [ //parameters// ] ) ] [[KeyPgDeclare declare]] [[KeyPgProperty property]] //fieldname//[ ( [ //parameters// ] ) ] [ [[KeyPgAs as]] [[DataType datatype]] ] ... **End Type** ## {{fbdoc item="param"}} ##//alignment//## Specifies the byte alignment for data fields. ##//fieldname//## Name of the data field or member procedure. ##//external_name//## Name of field as seen when externally linked. ##//parameters//## The parameters to be passed to a member procedure. ##//array subscripts//## Subscripts to declare a fixed-length array. ##//bits//## Number of bits a data field occupies. ##//initializer//## Default initializer for the data field. ##//operatorname//## The name of the operator to be overloaded. ##//calling convention specifier//## Can be ##[[KeyPgCdecl Cdecl]]##, ##[[KeyPgStdcall Stdcall]]## or ##[[KeyPgPascal Pascal]]##. {{fbdoc item="desc"}} ##**Type**## is used to declare custom data types containing one or more bit, scalar, array or other ##**Type**## fields. Types support member functions including ##[[KeyPgConstructor Constructor]]##, ##[[KeyPgDestructor Destructor]]##, ##[[KeyPgMemberFunction Function]]##, ##[[KeyPgOperator Operator]]##, ##[[KeyPgProperty Property]]## and ##[[KeyPgMemberSub Sub]]##. Fields default to ##[[KeyPgVisPublic Public:]]## member access unless, ##[[KeyPgVisPrivate Private:]]## or ##[[KeyPgVisProtected Protected:]]## is specified. An anonymous ##[[KeyPgUnion Union]]## can be nested in a ##**Type**## declaration. The optional ##[[KeyPgField Field]]=//number//## when given will change the default field alignment. ##[[KeyPgField Field]]=1## will disable any alignment, making the ##**Type**## contiguous in memory. ##**Type**## can be used to return a temporary type variable. See ##[[KeyPgTypeTemp Type()]]##. ##**Type**## can be used to declare a type definition ( i.e. an alias or alternative name ) for an already declared or yet to be declared type. See ##[[KeyPgTypeAlias Type (Alias)]]## Data fields may have an optional default ##//initializer//## value. This default value initializes the data field immediately before any constructor is called. ##[[KeyPgStaticMember Static]]## immediately preceding ##[[KeyPgMemberSub Sub]]## or ##[[KeyPgMemberFunction Function]]## indicates that no hidden ##[[KeyPgThis This]]## parameter is to be passed to the member procedure. ##[[KeyPgConstMember Const]]## immediately preceding ##[[KeyPgMemberSub Sub]]## or ##[[KeyPgMemberFunction Function]]## indicates that the hidden ##[[KeyPgThis This]]## parameter is to be considered read-only. **Warning** Special care must be taken when using a user defined type for file I/O. It is recommended to use ##Field = 1## for such cases, and it may be required to read files created by other applications. UDTs that contain pointers to data should not be written to file as-is: when the data is read later, the pointers will almost certainly be invalid, and the data they pointed to will no longer be available. Instead, custom input/output routines should be used, to save the allocated data in a different format in the file. This includes UDTs containing variable-length strings. Additionally, reading fixed length strings in UDT's from files is problematic: at present, fixed-length strings contain an extra NULL character on the end. To preserve alignment the field would need to be declared with one char less than the actual size and accessing the field by its name makes the last character unavailable. It also means there may be potential problems passing the string to functions that expect the NULL character to be there. A better solution is to use ubyte arrays, this requires a couple of auxiliary functions converting to/from string. See the example. {{fbdoc item="ex"}} This is an example of a QB-style type, not including procedure definitions {{fbdoc item="filename" value="examples/manual/udt/type1.bas"}}%%(freebasic) TYPE clr red AS UBYTE green AS UBYTE blue AS UBYTE END TYPE DIM c AS clr c.red = 255 c.green = 128 c.blue = 64 %% And this is an example of a type working as an object: {{fbdoc item="filename" value="examples/manual/udt/type2.bas"}}%%(freebasic) '' Example showing the problems with fixed length string fields in UDTs '' Suppose we have read a GIF header from a file '' signature width height dim as zstring*(10+1) z => "GIF89a" + mkshort(10) + mkshort(11) print "Using fixed-length string" type hdr1 field = 1 as string*(6-1) sig /' We have to dimension the string with 1 char ' less to avoid misalignments '/ as ushort wid, hei end type dim as hdr1 ptr h1 = cptr(hdr1 ptr, @z) print h1->sig, h1->wid, h1->hei '' Prints GIF89 (misses a char!) 10 11 '' We can do comparisons only with the 5 visible chars and creating a temporary string with LEFT if left(h1->sig, 5) = "GIF89" then print "ok" else print "error" '' Using a ubyte array, we need an auxiliary function to convert it to a string function ub2str( ub() as ubyte ) as string dim as integer length = ubound(ub) + 1 dim as string res = space(length) for i as integer = 0 to length-1 res[i] = ub(i): next function = res end function print print "Using an array of ubytes" type hdr2 field = 1 sig(0 to 6-1) as ubyte '' Dimension 6 as ushort wid, hei end type dim as hdr2 ptr h2 = cptr(hdr2 ptr, @z) '' Viewing and comparing is correct but a conversion to string is required print ub2str(h2->sig()), h2->wid, h2->hei '' Prints GIF89a 10 11 (ok) if ub2str(h2->sig()) = "GIF89a" then print "ok" else print "error" '' Prints ok %% {{fbdoc item="target"}} - The default field alignment is 4 bytes for DOS and Linux targets. - The default field alignment is 8 bytes for Windows targets. {{fbdoc item="lang"}} - Object-related features such as functions declared inside ##**Type**## blocks are supported only with the //[[CompilerOptlang -lang fb]]// dialect since version 0.17b - In the //[[CompilerOptlang -lang fb]]// and //[[CompilerOptlang -lang fblite]]// dialects, the default field alignment depends on the target platform. - With the //[[CompilerOptlang -lang qb]]// dialect the fields are aligned to byte boundaries by default, unless otherwise specified. - To force byte alignment use ##FIELD=1##. {{fbdoc item="diff"}} - At present, fixed-length strings have an extra, redundant character on the end, which means they take up one more byte than they do in QB. For this reason, UDTs that use them are not compatible with QB when used for file I/O. {{fbdoc item="see"}} - ##[[KeyPgUnion Union]]## - ##[[KeyPgEnum Enum]]## - ##[[KeyPgOffsetof OffsetOf]]## - ##[[KeyPgTypeTemp Type (Temporary)]]## - ##[[KeyPgTypeAlias Type (Alias)]]## - ##[[KeyPgTypeof Typeof]]## - ##[[KeyPgField Field]]## {{fbdoc item="back" value="CatPgUserDefTypes|User Defined Types"}}{{fbdoc item="title" value="Type (Alias)"}}---- Declares an alternative name for a type {{fbdoc item="syntax"}}## **Type** //typename// [[KeyPgAs as]] //symbol// ## {{fbdoc item="param"}} ##//typename//## new alternative name. ##//symbol//## symbol or data type declaration to associate with ##//typename//##. {{fbdoc item="desc"}} ##//symbol//## may refer to any declared data type including a built-in data type, ##[[KeyPgSub Sub]]## or ##[[KeyPgFunction Function]]## pointer, ##[[KeyPgType Type]]## declaration, ##[[KeyPgUnion Union]]## declaration, or ##[[KeyPgEnum Enum]]## declaration. A type alias can be used to allow forward declarations of [[CatPgUserDefTypes User Defined Types]]. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/udt/type-fwd.bas"}}%%(freebasic) TYPE ParentFwd as Parent TYPE Child Name as zstring * 32 ParentRef AS ParentFwd ptr ''... END TYPE TYPE Parent Name as zstring * 32 ChildList(0 to 9) AS Child ''... END TYPE DIM p AS Parent p.Name = "Foo" with p.ChildList(0) .Name = "Jr." .ParentRef = @p '' ... end with with p.ChildList(0) print .Name; " is child of "; .parentRef->Name end with %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgType Type...End Type]]## - ##[[KeyPgTypeTemp Type (Temporary)]]## {{fbdoc item="back" value="CatPgUserDefTypes|User Defined Types"}}{{fbdoc item="title" value="TYPEOF"}}---- Returns the type of a variable. {{fbdoc item="syntax"}}## **Typeof** ( //variable// | //datatype// ) ## {{fbdoc item="param"}} ##//variable//## A variable of any type. ##//datatype//## A [[DataType DataType]]. {{fbdoc item="desc"}} Typeof is a compiler intrinsic that replaces itself with the type of the variable passed to it. It can either be used in a variable declaration (Example 1) or it can be used in the preprocessor for comparison, printing. (Example 2) Typeof also supports passing any intrinsic data type, or user-defined type, not only variables defined as those types. Also supported are expressions, the type is inferred from the expression (much like [[KeyPgVar Var]]) {{fbdoc item="ex"}} Example 1: {{fbdoc item="filename" value="examples/manual/misc/typeof1.bas"}}%%(freebasic) Dim As Integer foo Dim As TypeOf(67.2) bar '' '67.2' is a literal double Dim As TypeOf( foo + bar ) teh_double '' double + integer results in double Print Len(teh_double) %% Example 2: {{fbdoc item="filename" value="examples/manual/misc/typeof2.bas"}}%%(freebasic) Dim As String foo #print TypeOf(foo) #if TypeOf(foo) = Integer #print "Never happened!" #endIf %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgType Type...End Type]]## {{fbdoc item="back" value="CatPgMisc|Miscellaneous"}}{{fbdoc item="title" value="Temporary Types"}}---- Creates a temporary copy of a user defined type {{fbdoc item="syntax"}}## //result// = **Type**( //initializers//, ... ) //or// //result// = **Type**( //initializers//, ... ) ## {{fbdoc item="param"}} ##//initializers//## Initial values for the type ##//typename//## The name of the ##[[KeyPgType Type]]## or ##[[KeyPgUnion Union]]## {{fbdoc item="ret"}} A temporary copy of the type. {{fbdoc item="desc"}} Used to create an anonymous and temporary type. If ##//typename//## is not explicitly given, it will be inferred from its usage. Usage of the temporary copy may include assigning it to a variable, passing it as a parameter to a procedure, or returning it as a value from a procedure. The ##[[KeyPgConstructor Constructor]]## for the type, if there is one, will be called when the temporary copy is created. And the ##[[KeyPgDestructor Destructor]]## for the type, if there is one, will be called immediately after its use. It can also be used as an even shorter shortcut than ##[[KeyPgWith With]]## (see below) if you are changing all the records. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/udt/temp-type.bas"}}%%(freebasic) Type Example As Integer field1 As Integer field2 End Type Dim ex As Example '' Filling the type by setting each field ex.field1 = 1 ex.field2 = 2 '' Filling the type by setting each field using WITH With ex .field1 = 1 .field2 = 2 End With '' Fill the variable's fields with a temporary type ex = Type( 1, 2 ) %% {{fbdoc item="filename" value="examples/manual/udt/temp-type2.bas"}}%%(freebasic) '' Passing a user-defined types to a procedure using a temporary type '' where the type can be inferred. Type S As Single x, y End Type Sub test ( v As S ) Print "S", v.x, v.y End Sub test( type( 1, 2 ) ) %% {{fbdoc item="filename" value="examples/manual/udt/temp-type3.bas"}}%%(freebasic) '' Passing a user-defined type to a procedure using temporary types '' where the type is ambiguous and the name of the type must be specified. Type S As Single x, y End Type Type T As Integer x, y End Type Union U As Integer x, y End Union '' Overloaded procedure test() Sub test overload ( v As S ) Print "S", v.x, v.y End Sub Sub test ( v As T ) Print "T", v.x, v.y End Sub Sub test ( v As U ) Print "U", v.x, v.y End Sub '' Won't work: ambiguous '' test( type( 1, 2 ) ) '' Specify name of type instead test( type( 1, 2 ) ) test( type( 1, 2 ) ) test( type( 1 ) ) %% {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgType Type...End Type]]## - ##[[KeyPgTypeAlias Type (Alias)]]## {{fbdoc item="back" value="CatPgUserDefTypes|User Defined Types"}}{{fbdoc item="back" value="CatPgProgrammer|Programmer's Guide"}}{{fbdoc item="title" value="UBOUND"}}---- Returns the upper bound of an array's dimension {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Ubound** ( array() [[KeyPgAs as]] [[KeyPgAny any]], [[KeyPgByval byval]] //dimension// [[KeyPgAs as]] [[KeyPgInteger integer]] = 1 ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **Ubound**( //array// [, //dimension// ] ) ## {{fbdoc item="param"}} ##//array//## an array of any type ##//dimension//## the dimension to get upper bound of {{fbdoc item="ret"}} Returns the upper bound of an array's dimension. {{fbdoc item="desc"}} ##**Ubound**## returns the largest value that can be used as an index into a particular dimension of an array. Array dimensions are numbered from one (1) to //n//, where //n// is the total number of dimensions. If ##//dimension//## is not specified, ##**Ubound**## will return the upper bound of the first dimension. If ##//dimension//## is less than one (1) or greater than the total number of dimensions (//n//) in the array, the result is undefined. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/array/ubound.bas"}}%%(freebasic) dim array(-10 to 10, 5 to 15, 1 to 2) as integer print ubound(array) 'returns 10 print ubound(array, 2) 'returns 15 print ubound(array, 3) 'returns 2 %% {{fbdoc item="see"}} - ##[[KeyPgLbound Lbound]]## - ##[[KeyPgStatic Static]]## - ##[[KeyPgDim Dim]]## - ##[[KeyPgRedim Redim]]## {{fbdoc item="back" value="CatPgArray|Array Functions"}}{{fbdoc item="title" value="UBYTE"}}---- Standard data type: 8 bit unsigned {{fbdoc item="syntax"}}## [[KeyPgDim dim]] //variable// [[KeyPgAs as]] **Ubyte** ## {{fbdoc item="desc"}} 8-bit unsigned whole-number data type. Can hold a value in the range of 0 to 255. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/datatype/ubyte2.bas"}}%%(freebasic) DIM ubytevar AS UBYTE ubytevar = 200 PRINT "ubytevar= ", ubytevar %% {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/datatype/ubyte.bas"}}%%(freebasic) Dim x As UByte = 0 Dim y As UByte = &HFF Print "UByte Range = "; x; " to "; y %% **Output:** %%UByte Range = 0 to 255%% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Ubyte""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgByte Byte]]## - ##[[KeyPgCubyte Cubyte]]## {{fbdoc item="back" value="CatPgStdDataTypes|Standard Data Types"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 04:59:53 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 2b0e8cf9c02e02556af9ffd890f8f4ba Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 1526 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="UCASE"}}---- Returns an upper case copy of a string {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Ucase** [[KeyPgOverload overload]] ( [[KeyPgByref byref]] //str// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgString string]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Ucase** ( [[KeyPgByref byref]] //str// [[KeyPgAs as]] [[KeyPgWstring wstring]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] ## {{fbdoc item="usage"}}## //result// = **Ucase**[$]( //str// ) ## {{fbdoc item="param"}} ##//str//## String to convert to uppercase. {{fbdoc item="ret"}} Uppercase copy of ##//str//##. {{fbdoc item="desc"}} Returns a copy of ##//str//## with all of the letters converted to upper case. If ##//str//## is empty, the null string (##"####"##) is returned. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/ucase.bas"}}%%(freebasic) print ucase("AbCdEfG") %% will produce the output: %%ABCDEFG %% {{fbdoc item="see"}} - DOS does not support the wide-character string version of ##**Ucase**##. {{fbdoc item="lang"}} - The string type suffix "$" is obligatory in the //[[CompilerOptlang -lang qb]]// dialect. - The string type suffix "$" is optional in the //[[CompilerOptlang -lang fblite]]// and //[[CompilerOptlang -lang fb]]// dialects. {{fbdoc item="diff"}} - QB does not support Unicode. {{fbdoc item="see"}} - ##[[KeyPgLcase Lcase]]## {{fbdoc item="back" value="CatPgString|String Functions"}} {{fbdoc item="title" value="UINTEGER"}}---- Standard data type: 32 bit unsigned {{fbdoc item="syntax"}}## [[KeyPgDim dim]] //variable// [[KeyPgAs as]] **Uinteger** ## {{fbdoc item="desc"}} 32-bit unsigned whole-number data type. Can hold values from 0 to 4294967295. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/datatype/uinteger.bas"}}%%(freebasic) Dim x As UInteger = 0 Dim y As UInteger = &HFFFFFFFF Print "UInteger Range = "; x; " to "; y %% **Output:** %%UInteger Range = 0 to 4294967295%% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Uinteger""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgInteger Integer]]## - ##[[KeyPgCuint Cuint]]## {{fbdoc item="back" value="CatPgStdDataTypes|Standard Data Types"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 05:00:01 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 160ca29f58007ca8ff60fda901888f01 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 1135 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="ULONG"}}---- Standard data type: unsigned integer having same size as ##[[KeyPgSizeof Sizeof]]([[KeyPgAny Any]] [[KeyPgPtr Ptr]])## {{fbdoc item="syntax"}}## [[KeyPgDim dim]] //variable// [[KeyPgAs as]] **Ulong** ## {{fbdoc item="desc"}} Depending on the platform, same as ##[[KeyPgUinteger Uinteger]]## or ##[[KeyPgUlongint Ulongint]]##. A 32-bit or 64-bit unsigned whole-number data type. ##**Ulong**## has the same size as ##[[KeyPgSizeof Sizeof]]([[KeyPgAny Any]] [[KeyPgPtr Ptr]])##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/datatype/ulong.bas"}}%%(freebasic) Dim x As ULong = 0 Dim y As ULong = &HFFFFFFFF Print "ULong Range = "; x; " to "; y %% **Output:** %%ULong Range = 0 to 4294967295%% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Ulong""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgLong Long]]## - ##[[KeyPgUinteger Uinteger]]## - ##[[KeyPgUlongint Ulongint]]## {{fbdoc item="back" value="CatPgStdDataTypes|Standard Data Types"}} {{fbdoc item="title" value="ULONGINT"}}---- Standard data type: 64 bit unsigned {{fbdoc item="syntax"}}## [[KeyPgDim dim]] //variable// [[KeyPgAs as]] **Ulongint** ## {{fbdoc item="desc"}} A 64-bit unsigned whole-number data type. Can hold values from 0 to 18 446 744 073 709 551 615 {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/datatype/ulongint.bas"}}%%(freebasic) Dim x As ULongInt = 0 Dim y As ULongInt = &HFFFFFFFFFFFFFFFFull Print "ULongInt Range = "; x; " to "; y %% **Output:** %%ULongInt Range = 0 to 18446744073709551615%% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Ulongint""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgLongint Longint]]## - ##[[KeyPgCulngint Culngint]]## {{fbdoc item="back" value="CatPgStdDataTypes|Standard Data Types"}}{{fbdoc item="title" value="UNION"}}---- Declares a union user defined type. {{fbdoc item="syntax"}}## **Union** //typename// //fieldname// as [[DataType datatype]] [[KeyPgDeclare declare]] //member function declaration// ... ... End Union ## {{fbdoc item="param"}} ##//typename//## Name of the ##**Union**## ##//fieldname//## Name of a data field member ##//member function declaration//## Any of the supported member functions {{fbdoc item="desc"}} Unions are similar to a ##[[KeyPgType Type]]## structure, except that the elements of a union occupy the same space in memory. The size of the Union is the size of the largest data item. Since they occupy the same space, only a single element can be used. Unions can be nested inside a type structure. See Example. Unions support member functions including ##[[KeyPgConstructor Constructor]]##, ##[[KeyPgDestructor Destructor]]##, ##[[KeyPgMemberFunction Function]]##, ##[[KeyPgOperator Operator]]##, ##[[KeyPgProperty Property]]## and ##[[KeyPgMemberSub Sub]]##. All members of a union are public and access control is not supported. A ##**Union**## can be passed as a user defined type to overloaded operator functions. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/udt/union.bas"}}%%(freebasic) 'define our union union AUnion a as ubyte b as integer end union 'define a composite type type CompType s as string * 20 ui as byte 'Flag to tell us what to use in union. union au as ubyte bu as integer end union end type 'Flags to let us know what to use in union. 'You can only use a single element of a union. const IsInteger = 1 const IsUByte = 2 dim MyUnion as AUnion dim MyComposite as CompType 'Can only set one value in union MyUnion.a = 128 MyComposite.s = "Type + Union" MyComposite.ui = IsInteger 'Tells us this is an integer union MyComposite.bu = 1500 print "Union: ";MyUnion.a print "Composite: "; if MyComposite.ui = IsInteger then print MyComposite.bu elseif MyComposite.ui = IsUByte then print MyComposite.au else print "Unknown type." end if sleep %% {{fbdoc item="lang"}} - Object-related features as functions defined inside the ##**Union**## block are supported only in the //[[CompilerOptlang -lang fb]]// dialect. - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Union""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgType Type]]## {{fbdoc item="back" value="CatPgUserDefTypes|User Defined Types"}}{{fbdoc item="title" value="UNLOCK"}}---- Removes a previous access restriction (lock) on a file {{fbdoc item="syntax"}}## **Unlock** #//filenum// [, //record// ] **Unlock** #//filenum//, [ //start// ] TO //end// ## {{fbdoc item="param"}} ##//filenum//## The file number used to ##[[KeyPgOpen Open]]## the file. ##//record//## The record (##[[KeyPgRandom Random]]## files) or byte position (##[[KeyPgBinary Binary]]## files) to unlock. If omitted, the entire file is unlocked. ##//start//## The first record (##[[KeyPgRandom Random]]## files) or byte position (##[[KeyPgBinary Binary]]## files) in a range to unlock. If omitted, the current record/byte position (##[[KeyPgSeekreturn Seek]]##(##//filenum//##) is used. ##//end//## The last record (##[[KeyPgRandom Random]]## files) or byte position (##[[KeyPgBinary Binary]]## files) in a range to unlock. {{fbdoc item="desc"}} ##**Unlock**## removes the temporary access restriction set by ##[[KeyPgLock Lock]]##. It is strongly recommended to use the same arguments used in the previous ##[[KeyPgLock Lock]]##. {{fbdoc item="ex"}} For an example see ##[[KeyPgLock Lock]]##. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgLock Lock]]## - ##[[KeyPgOpen Open]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 05:00:10 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: c2a590983eb8a116b36ae6f79b4c94cd Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 853 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="UNSIGNED"}}---- Integer data type modifier {{fbdoc item="syntax"}}## [[KeyPgDim dim]] //variable// [[KeyPgAs as]] **Unsigned** //{integer-based data type}// ## {{fbdoc item="desc"}} Forces an integer-based data type to be unsigned (cannot contain negative numbers, but has it's maximum value doubled). {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/datatype/unsigned.bas"}}%%(freebasic) 'e.g. notice what is displayed: dim x as unsigned integer x = -1 print x 'output is 4294967295 %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Unsigned""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgUinteger Uinteger]]## {{fbdoc item="back" value="CatPgStdDataTypes|Standard Data Types"}} {{fbdoc item="title" value="UNTIL"}}---- Conditional clause used in ##[[KeyPgDoloop Do..Loop]]## statements. {{fbdoc item="syntax"}}## Do **Until** //condition// or Loop **Until** //condition// ## {{fbdoc item="desc"}} ##**Until**## is used with the ##[[KeyPgDoloop Do...Loop]]## structure. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/control/until.bas"}}%%(freebasic) DIM a AS INTEGER a = 1 DO PRINT "hello" a = a + 1 LOOP UNTIL a > 10 'This will continue to print "hello" on the screen until the condition (a > 10) is met. %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgDoloop Do...Loop]]## {{fbdoc item="back" value="CatPgMisc|Miscellaneous"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 05:00:19 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 6c2a5afd928ccf17badb5310dba053d8 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 838 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="USHORT"}}---- Standard data type: 16 bit unsigned {{fbdoc item="syntax"}}## [[KeyPgDim dim]] //variable// [[KeyPgAs as]] **Ushort** ## {{fbdoc item="desc"}} 16-bit unsigned whole-number data type. Can hold values from 0 to 65535. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/datatype/ushort.bas"}}%%(freebasic) Dim x As UShort = 0 Dim y As UShort = &HFFFF Print "UShort Range = "; x; " to "; y %% **Output:** %%UShort Range = 0 to 65535%% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Ushort""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgShort Short]]## - ##[[KeyPgCushort Cushort]]## {{fbdoc item="back" value="CatPgStdDataTypes|Standard Data Types"}} {{fbdoc item="title" value="USING (Namespaces)"}}---- Brings namespace symbols into the current scope {{fbdoc item="syntax"}}## **Using** //identifier// [, //identifier// [, ...] ] ## {{fbdoc item="param"}} ##//identifier//##: The name of the ##[[KeyPgNamespace Namespace]]## that you want to use. {{fbdoc item="desc"}} The ##**Using**## command allows all symbols from a given namespace to be accessed without the namespace's name prefix. Unlike ""C++"" but like C#, the ##[[KeyPgNamespace Namespace]]## keyword is not needed after ##**Using**##, because individual symbols cannot be inherited from a namespace. Inheriting a whole namespace can save typing, but sometimes some meaning of the code can be lost, and conflicts with other symbols could be created. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/module/using.bas"}}%%(freebasic) Namespace Sample Type T x As Integer End Type End Namespace '' Just using the name T would not find the symbol, '' because it is inside a namespace. Dim SomeVariable As Sample.T '' Now the whole namespace has been inherited into '' the global namespace. Using Sample '' This statement is valid now, since T exists '' without the "Sample." prefix. Dim OtherVariable As T %% {{fbdoc item="diff"}} - QB had the ##**Using**## keyword, but for other purposes. Namespaces did not exist in QB. {{fbdoc item="see"}} - ##[[KeyPgPrintusing Print Using]]## - ##[[KeyPgPalette Palette Using]]## - ##[[KeyPgNamespace Namespace]]## {{fbdoc item="back" value="CatPgModularizing|Modularizing"}}{{fbdoc item="title" value="VA_ARG"}}---- Returns the current argument from a variable argument list {{fbdoc item="syntax"}}## //variable// = **va_arg** ( //argument_list//, [[DataType datatype]] ) ## {{fbdoc item="desc"}} The ##**va_arg**## macro allows the use of a variable number of arguments within a function. ##**va_arg**## returns the current argument in the list, ##//argument_list//##, with an expected data type of ##//datatype//##. Before ##**va_arg**## can be used, it must be Initialized with the command ##[[KeyPgVaFirst va_first]]##. Unlike the C macro with the same name, ##**va_arg**## does not automatically increment ##//argument_list//## to the next argument within the list. The command ##[[KeyPgVaNext va_next]]## must be used for this purpose. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/procs/va_arg.bas"}}%%(freebasic) FUNCTION Avg cdecl (Count as INTEGER, ... ) AS DOUBLE DIM ARG AS ANY PTR DIM SUM AS DOUBLE = 0 DIM i AS INTEGER ARG = VA_FIRST() FOR i = 1 TO COUNT SUM += VA_ARG(ARG, DOUBLE) ARG = VA_NEXT(ARG,DOUBLE) NEXT i RETURN SUM/COUNT end function PRINT AVG (4, 3.4,5.0,3.2,4.1) PRINT AVG (2, 65.2,454.65481) SLEEP %% The output would look like: %% 3.925 259.927405 %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__va_arg""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgDots ... (Ellipsis)]]## - ##[[KeyPgVaFirst va_first]]## - ##[[KeyPgVaNext va_next]]## {{fbdoc item="back" value="CatPgProcedures|Procedures"}}{{fbdoc item="back" value="CatPgVarArg|Variable Argument list"}}{{fbdoc item="title" value="VA_FIRST"}}---- Returns the first argument in a variable argument list {{fbdoc item="syntax"}}## //pointer_variable// = **va_first**() ## {{fbdoc item="desc"}} The ##**va_first**## function initializes a [[ProPgPointers pointer]], //pointer_variable//, to point to the first variable argument passed to a function. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/procs/va_first.bas"}}%%(freebasic) FUNCTION Avg cdecl (Count as INTEGER, ... ) AS DOUBLE DIM ARG AS ANY PTR DIM SUM AS DOUBLE = 0 DIM i AS INTEGER ARG = VA_FIRST() FOR i = 1 TO COUNT SUM += VA_ARG(ARG, DOUBLE) ARG = VA_NEXT(ARG,DOUBLE) NEXT i RETURN SUM/COUNT end function PRINT AVG (4, 3.4,5.0,3.2,4.1) PRINT AVG (2, 65.2,454.65481) SLEEP %% The output would look like: %% 3.925 259.927405 %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Va_first""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - [[KeyPgDots ... (Ellipsis)]] - ##[[KeyPgVaArg va_arg]]## - ##[[KeyPgVaNext va_next]]## {{fbdoc item="back" value="CatPgProcedures|Procedures"}}{{fbdoc item="back" value="CatPgVarArg|Variable Argument list"}}{{fbdoc item="title" value="VAL"}}---- Converts a string to a floating point number {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Val** [[KeyPgOverload overload]] ( [[KeyPgByref byref]] //str// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgDouble double]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Val** ( [[KeyPgByref byref]] //str// [[KeyPgAs as]] [[KeyPgWstring wstring]] ) [[KeyPgAs as]] [[KeyPgDouble double]] ## {{fbdoc item="usage"}}## //result// = **Val**( //strnum// ) ## {{fbdoc item="param"}} ##//strnum//## the string containing a number to convert {{fbdoc item="ret"}} Returns a converted ##[[KeyPgDouble Double]]## precision number. If the first character of the string is invalid, ##**Val**## will return a 0. {{fbdoc item="desc"}} ##**Val**##("10") will return 10.0, and ##**Val**##("10.10") will return 10.1. The function parses the string from the left, skipping any white space, and returns the longest number it can read, stopping at the first non-suitable character it finds. Scientific notation is recognized, with ##"D"## or ##"E"## used to specify the exponent. ##**Val**## can be used to convert integer numbers in binary / octal / hexadecimal format, if they have the relevant identifier (##"&B"## / ##"&O"## / ##"&H"##) prefixed, for example: ##**Val**("&HFF")## returns 255. **Note**: If you want to return an integer, consider using ##[[KeyPgValint ValInt]]## or ##[[KeyPgVallng ValLng]]## instead. They are faster, since they don't use floating-point numbers, and only ##[[KeyPgVallng ValLng]]## provides full 64-bit precision for ##[[KeyPgLongint LongInt]]## types. If you want to convert a number into string format, use the ##[[KeyPgStr Str]]## function. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/val.bas"}}%%(freebasic) dim a as string, b as integer a = "20xa211" b = val(a) print a, b %% %% 20xa211 20 %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgStr Str]]## - ##[[KeyPgValint Valint]]## - ##[[KeyPgVallng Vallng]]## - ##[[KeyPgChr Chr]]## - ##[[KeyPgAsc Asc]]## {{fbdoc item="back" value="CatPgCasting|Converting Data Types"}}{{fbdoc item="back" value="CatPgString|String Functions"}}{{fbdoc item="title" value="VALINT"}}---- Converts a string to an integer number {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Valint** [[KeyPgOverload overload]] ( [[KeyPgByref byref]] //strnum// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Valint** ( [[KeyPgByval byval]] //strnum// [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgPtr ptr]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## //result// = **Valint** ( //strnum// ) ## {{fbdoc item="param"}} ##//strnum//## the string to convert {{fbdoc item="ret"}} Returns an ##[[KeyPgInteger Integer]]## of the converted string If the first character of the string is invalid, ##**Valint**## will return a 0. {{fbdoc item="desc"}} For example, ##**Valint**("10")## will return 10, and ##**Valint**("10.60")## will return 10 as well. The function parses the string from the left, skipping any white space, and returns the longest number it can read, stopping at the first non-suitable character it finds. Any non-numeric characters, including decimal points and exponent specifiers, are considered non-suitable. ##**Valint**## can be used to convert integer numbers in [[KeyPgBin binary]] / [[KeyPgOct octal]] / [[KeyPgHex hexadecimal]] format, if they have the relevant identifier (##"&B"## / ##"&O"## / ##"&H"##) prefixed, for example: ##**Valint**("&HFF")## returns 255. If you want to convert a number into string format, use the ##[[KeyPgStr Str]]## function. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/valint.bas"}}%%(freebasic) dim a as string, b as integer a = "20xa211" b = valint(a) print a, b %% %% 20xa211 20 %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Valint""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgStr Str]]## - ##[[KeyPgVal Val]]## - ##[[KeyPgValuint Valuint]]## - ##[[KeyPgVallng Vallng]]## - ##[[KeyPgChr Chr]]## - ##[[KeyPgAsc Asc]]## {{fbdoc item="back" value="CatPgCasting|Converting Data Types"}}{{fbdoc item="back" value="CatPgString|String Functions"}}{{fbdoc item="title" value="VALLNG"}}---- Converts a string to a long integer. {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Vallng** [[KeyPgOverload overload]] ( [[KeyPgByref byref]] //strnum// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgLongint longint]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Vallng** ( [[KeyPgByref byref]] //strnum// [[KeyPgAs as]] [[KeyPgWstring wstring]] ) [[KeyPgAs as]] [[KeyPgLongint longint]] ## {{fbdoc item="usage"}}## //result// = **Vallng**( //strnum// ) ## {{fbdoc item="param"}} ##//strnum//## The string containing a number to convert. {{fbdoc item="ret"}} Returns a converted ##[[KeyPgLongint longint]]## number. If the first character of the string is invalid, ##**Vallng**## will return a 0. {{fbdoc item="desc"}} For example, ##**Vallng**("10")## will return 10, and ##**Vallng**("10.60")## will return 10 as well. The function parses the string from the left, skipping any white space, and returns the longest number it can read, stopping at the first non-suitable character it finds. Any non-numeric characters, including decimal points and exponent specifiers, are considered non-suitable. ##**Vallng**## can be used to convert integer numbers in [[KeyPgBin binary]] / [[KeyPgOct octal]] / [[KeyPgHex hexadecimal]] format, if they have the relevant identifier (##"&B"## / ##"&O"## / ##"&H"##) prefixed, for example: ##**Vallng**("&HFF")## returns 255. If you want to convert a number into string format, use the ##[[KeyPgStr Str]]## function. (**Note**: In early versions of FreeBASIC, this function was called ##**""Val64""**##) {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/vallng.bas"}}%%(freebasic) dim a as string, b as integer a = "20xa211" b = vallng(a) print a, b %% Output: %% 20xa211 20 %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Vallng""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgStr Str]]## - ##[[KeyPgVal Val]]## - ##[[KeyPgValint Valint]]## - ##[[KeyPgValulng Valulng]]## - ##[[KeyPgChr Chr]]## - ##[[KeyPgAsc Asc]]## {{fbdoc item="back" value="CatPgCasting|Converting Data Types"}}{{fbdoc item="back" value="CatPgString|String Functions"}}{{fbdoc item="title" value="VALUINT"}}---- Converts a string to an unsigned integer number {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Valuint** [[KeyPgOverload overload]] ( [[KeyPgByref byref]] //strnum// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgUinteger uinteger]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Valuint** ( [[KeyPgByref byref]] //strnum// [[KeyPgAs as]] [[KeyPgWstring wstring]] ) [[KeyPgAs as]] [[KeyPgUinteger uinteger]] ## {{fbdoc item="usage"}}## //result// = **Valuint**( //strnum// ) ## {{fbdoc item="param"}} ##//strnum//## the string containing the number to convert {{fbdoc item="ret"}} Returns a converted ##[[KeyPgUinteger Uinteger]]## number. If the first character of the string is invalid, ##**Valuint**## will return a 0. {{fbdoc item="desc"}} For example, ##**Valuint**("10")## will return 10, and ##**Valuint**("10.60")## will return 10 as well. The function parses the string from the left, skipping any white space, and returns the longest number it can read, stopping at the first non-suitable character it finds. Any non-numeric characters, including decimal points and exponent specifiers, are considered non-suitable. ##**Valuint**## can be used to convert integer numbers in [[KeyPgBin binary]] / [[KeyPgOct octal]] / [[KeyPgHex hexadecimal]] format, if they have the relevant identifier (##"&B"## / ##"&O"## / ##"&H"##) prefixed, for example: ##**Valuint**("&HFF")## returns 255. If you want to convert a number into string format, use the ##[[KeyPgStr Str]]## function. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/valuint.bas"}}%%(freebasic) dim a as string, b as uinteger a = "20xa211" b = valuint(a) print a, b %% %% 20xa211 20 %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Valuint""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgStr Str]]## - ##[[KeyPgVal Val]]## - ##[[KeyPgValint Valint]]## - ##[[KeyPgVallng Vallng]]## - ##[[KeyPgChr Chr]]## - ##[[KeyPgAsc Asc]]## {{fbdoc item="back" value="CatPgCasting|Converting Data Types"}}{{fbdoc item="back" value="CatPgString|String Functions"}}{{fbdoc item="title" value="VALULNG"}}---- Converts a string to a unsigned long integer number {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Valulng** [[KeyPgOverload overload]] ( [[KeyPgByref byref]] //strnum// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgUlongint ulongint]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Valulng** ( [[KeyPgByref byref]] //strnum// [[KeyPgAs as]] [[KeyPgWstring wstring]] ) [[KeyPgAs as]] [[KeyPgUlongint ulongint]] ## {{fbdoc item="usage"}}## //result// = **Valulng**( //strnum// ) ## {{fbdoc item="param"}} ##//strnum//## the string containing a number to convert {{fbdoc item="ret"}} Returns a converted ##[[KeyPgUlongint Ulongint]]## number. If the first character of the string is invalid, ##**Valulng**## will return a 0. {{fbdoc item="desc"}} For example, ##**Valulng**("10")## will return 10, and ##**Valulng**("10.60")## will return 10 as well. The function parses the string from the left, skipping any white space, and returns the longest number it can read, stopping at the first non-suitable character it finds. Any non-numeric characters, including decimal points and exponent specifiers, are considered non-suitable. ##**Valulng**## can be used to convert integer numbers in [[KeyPgBin binary]] / [[KeyPgOct octal]] / [[KeyPgHex hexadecimal]] format, if they have the relevant identifier (##"&B"## / ##"&O"## / ##"&H"##) prefixed, for example: ##**Valulng**("&HFF")## returns 255. If you want to convert a number into string format, use the ##[[KeyPgStr Str]]## function. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/valulng.bas"}}%%(freebasic) dim a as string, b as ulongint a = "20xa211" b = valulng(a) print a, b %% %% 20xa211 20 %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Valulng""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgStr Str]]## - ##[[KeyPgVal Val]]## - ##[[KeyPgValint Valint]]## - ##[[KeyPgVallng Vallng]]## - ##[[KeyPgChr Chr]]## - ##[[KeyPgAsc Asc]]## {{fbdoc item="back" value="CatPgCasting|Converting Data Types"}}{{fbdoc item="back" value="CatPgString|String Functions"}}{{fbdoc item="title" value="VA_NEXT"}}---- Returns a pointer to the next argument in a variable argument list {{fbdoc item="syntax"}}## //Argument_Pointer// = **va_next** (//Argument_List//, [[DataType datatype]] ) ## {{fbdoc item="desc"}} The ##**va_next**## macro points to the next argument within the list ##//Argument_List//## of the type ##//datatype//##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/procs/va_next.bas"}}%%(freebasic) FUNCTION Avg cdecl (Count as INTEGER, ... ) AS DOUBLE DIM ARG AS ANY PTR DIM SUM AS DOUBLE = 0 DIM i AS INTEGER ARG = VA_FIRST() FOR i = 1 TO COUNT SUM += VA_ARG(ARG, DOUBLE) ARG = VA_NEXT(ARG,DOUBLE) NEXT i RETURN SUM/COUNT end function PRINT AVG (4, 3.4,5.0,3.2,4.1) PRINT AVG (2, 65.2,454.65481) SLEEP %% The output would look like: %% 3.925 259.927405 %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Va_next""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - [[KeyPgDots ... (Ellipsis)]] - ##[[KeyPgVaArg va_arg]]## - ##[[KeyPgVaFirst va_first]]## {{fbdoc item="back" value="CatPgProcedures|Procedures"}}{{fbdoc item="back" value="CatPgVarArg|Variable Argument list"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 05:00:32 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: f850236c5e2fa23dc95eba517de04709 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 3150 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="VAR"}}---- Declares a variable whose type is implied from the initializer expression {{fbdoc item="syntax"}}## **Var** [[[KeyPgShared shared]]] //symbolname// = //expression//[, //symbolname// = //expression//] ## {{fbdoc item="desc"}} ##**Var**## declares a variable whose type is implied from the initializer expression. It is illegal to specify an explicit type in a ##**Var**## declaration. The initializer expression does not have to be a constant, it can be, or, it can be any variable of any type. Note: ##[[KeyPgWstring Wstring]]## is not supported with ##**Var**##, due to the fact that there is no var-len ##[[KeyPgWstring Wstring]]## type. This isn't likely to change, due to the complexities involved with handling Unicode. Since the type of the variable is inferred from what you assign into it, it's helpful to know how literals work. Any literal number without a decimal point defaults to ##[[KeyPgInteger Integer]]##. A literal number //with// a decimal point defaults to ##[[KeyPgDouble Double]]##. All literal strings default to the type 'zstring', however, if you initialize a variable using ##[[KeyPgWstring Wstring]]##, and a literal string, the variable will be "promoted" to a variable length string. Explicit suffixes may be used on literal variables, to change/clarify their type. See [[ProPgLiterals Literals]] and [[TblVarTypes Variable Types]] for some more information about suffixes that can be used on literals. Note: Suffixes must appear on the initializer, not on the variable. Trying to use ##**Var**## with a variable that has a suffix will throw a compile error. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/variable/var.bas"}}%%(freebasic) var a = cast(byte, 0) var b = cast(short, 0) var c = cast(integer, 0) var d = cast(longint, 0) var au = cast(ubyte, 0) var bu = cast(ushort, 0) var cu = cast(uinteger, 0) var du = cast(ulongint, 0) var e = cast(single, 0.0) var f = cast(double, 0.0) var g = @c '' integer ptr var h = @a '' byte ptr var s2 = "hello" '' var-len string var ii = 6728 '' implicit integer var id = 6728.0 '' implicit double print "Byte: ";len(a) print "Short: ";len(b) print "Integer: ";len(c) print "Longint: ";len(d) print "UByte: ";len(au) print "UShort: ";len(bu) print "UInteger: ";len(cu) print "ULongint: ";len(du) print "Single: ";len(e) print "Double: ";len(f) print "Integer Pointer: ";len(g) print "Byte Pointer: ";len(h) print "Variable String: ";len(s2) print print "Integer: ";len(ii) print "Double: ";len(id) sleep %% {{fbdoc item="diff"}} - New to FreeBASIC 0.17 {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Var""**##. {{fbdoc item="see"}} - ##[[KeyPgCommon Common]]## - ##[[KeyPgDim Dim]]## - ##[[KeyPgErase Erase]]## - ##[[KeyPgExtern Extern]]## - ##[[KeyPgLbound LBound]]## - ##[[KeyPgRedim Redim]]## - ##[[KeyPgPreserve Preserve]]## - ##[[KeyPgShared Shared]]## - ##[[KeyPgStatic Static]]## - ##[[KeyPgUbound UBound]]## {{fbdoc item="back" value="CatPgVariables|Variable Declarations"}} {{fbdoc item="title" value="VIEW (GRAPHICS)"}}---- Sets new physical coordinate mapping and clipping region {{fbdoc item="syntax"}}## **View** [SCREEN] ( //x1//, //y1// )-( //x2//, //y2// )[, [ //color// ] [, //border// ]]] ## {{fbdoc item="param"}} ##SCREEN## When specified, any x,y coordinate will be relative to the top-left corner of the screen, and not to the left-top corner of the viewport. ##( //x1//, //y1// )-( //x2//, //y2// )## Coordinates of the top-left and bottom-right corners of the new viewport in screen pixels. ##//color//## Color with which to clear the new viewport; if omitted, the viewport will not be cleared. ##//border//## Color of the border box surrounding the new viewport. If omitted, no border box will be drawn. {{fbdoc item="desc"}} Use this statement to set a new clipping region, also known as viewport. The new viewport will override the previous one, if any; if the ##SCREEN## argument is omitted, all future coordinates specifications will be relative to the top-left corner of the new viewport, instead of relative to the top-left corner of the screen. Any graphical primitive will be affected by the new viewport, and drawing outside specified region will produce no effect. If ##//color//## is specified, in the same format as the one supported by ##[[KeyPgColor Color]]##, the new viewport is cleared with it; if ##//border//## is specified, also in ##[[KeyPgColor Color]]## format, a box using ##//border//## as color will be drawn surrounding given region. If all arguments are omitted, the viewport is reset to the screen mode size. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/view.bas"}}%%(freebasic) screen 12 dim ip as integer ptr dim as integer i, j, k 'simple sprite for i=0 to 63: for j=0 to 63:pset (i,j), (i\4) xor (j\4):next j,i ip=imagecreate(64,64) get (0,0)-(63,63),ip cls 'viewport line (215,135)-(425,345),1,bf view (220,140)-(420,340) k=0 'move sprite do i=100*sin(k*.02)+50: j=100* sin(k*.027)+50 screensync screenlock cls 1: put (i,j),ip ,pset screenunlock k=k+1 loop until len(inkey) imagedestroy(ip) %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgScreengraphics Screen (Graphics)]]## - ##[[KeyPgWindow Window]]## - ##[[KeyPgPmap Pmap]]## - ##[[KeyPgViewtext View Print]]## {{fbdoc item="back" value="CatPgGfxScreen|Screen Functions"}}{{fbdoc item="title" value="VIEW PRINT"}}---- Sets the printable area of the screen {{fbdoc item="syntax"}}## **View Print** //firstrow// **To** //lastrow// ## {{fbdoc item="param"}} ##//firstrow//## first row of print area ##//lastrow//## last row of print area {{fbdoc item="desc"}} Sets the boundaries of the console screen text area to the lines starting at first up to and including last. Lines are counted starting with 1. The text cursor is moved to the beginning of the first line specified. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/console/view.bas"}}%%(freebasic) Cls View Print 5 To 6 Color , 1 '' clear only View Print area Cls %% **View Print** can be used in graphics mode to avoid the text output overwriting graphics. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/console/view-gfx.bas"}}%%(freebasic) screen 12 dim as integer R,Y,x,y1 dim as single y2 view print 20 to 27 line (0,0)-(639,300),1,BF line (100,50)-(540,200),0,BF do r = (r + 1) AND 15 FOR y = 1 TO 99 y1 = ((1190 \ y + r) AND 15) y2 = 6 / y FOR x = 100 TO 540 PSET (x, y + 100), CINT((319 - x) * y2) AND 15 XOR y1 NEXT x,y if r=0 then color int(rnd*16): print "blah" loop until len(inkey) %% {{fbdoc item="diff"}} - None. {{fbdoc item="see"}} - ##[[KeyPgCls Cls]]## - ##[[KeyPgColor Color]]## {{fbdoc item="back" value="CatPgConsole|Console Functions"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 05:00:41 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 928d6daf88eb8b8479158c976a99fe4f Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 2004 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="PRIVATE: (Access Control)"}}---- Specifies private member access control in a ##[[KeyPgType Type]]## or ##[[KeyPgClass Class]]## {{fbdoc item="syntax"}}## [[KeyPgType Type]] //typename// **Private:** //member declarations// End Type ## {{fbdoc item="param"}} ##//typename//## name of the ##[[KeyPgType Type]]## or ##[[KeyPgClass Class]]## ##//member declarations//## declarations for fields, functions, or enumerations {{fbdoc item="desc"}} ##**Private:**## indicates that ##//member declarations//## following it have private access. Private members are accessible only from inside a member function for the ##[[KeyPgType Type]]## or ##[[KeyPgClass Class]]##. ##//member declarations//## following ##**Private:**## are private until a different access control specifier is given, like ##[[KeyPgVisPublic Public:]]## or ##[[KeyPgVisProtected Protected:]]##. Members in a ##[[KeyPgType Type]]## declaration are ##**Public:**## by default if no member access control specifier is given. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/udt/private.bas"}}%%(freebasic) Type testing number As Integer Private: nome As String Declare Sub setNome( ByRef newnome As String ) End Type Sub testing.setnome( ByRef newnome As String ) '' This is OK. We're inside a member function for the type this.nome = newnome End Sub Dim As testing myVariable '' This is OK, number is public myVariable.number = 69 '' this would generate a compile error '' - nome is private and we're trying to access it outside any of this TYPE's member functions '' myVariable.nome = "FreeBASIC" %% {{fbdoc item="lang"}} - Available only in the //[[CompilerOptlang -lang fb]]// dialect. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgVisPublic Public:]]## (Access Control) - ##[[KeyPgVisProtected Protected:]]## (Access Control) - ##[[KeyPgType Type]]## {{fbdoc item="back" value="CatPgUserDefTypes|User Defined Types"}} {{fbdoc item="title" value="PROTECTED: (Access Control)"}}---- Specifies protected member access control in a ##[[KeyPgType Type]]## or ##[[KeyPgClass Class]]## {{fbdoc item="syntax"}}## [[KeyPgType Type]] //typename// **Protected:** //member declarations// End Type ## {{fbdoc item="param"}} ##//typename//## name of the ##[[KeyPgType Type]]## or ##[[KeyPgClass Class]]## ##//member declarations//## declarations for fields, functions, or enumerations {{fbdoc item="desc"}} ##**Protected:**## indicates that ##//member declarations//## following it have protected access. Protected members are accessible only from inside a member function for the ##[[KeyPgType Type]]## or ##[[KeyPgClass Class]]##, and classes which are derived from the ##[[KeyPgType Type]]## or ##[[KeyPgClass Class]]##. ##//member declarations//## following ##**Protected:**## are protected until a different access control specifier is given, like ##[[KeyPgVisPrivate Private:]]## or ##[[KeyPgVisPublic Public:]]##. Members in a ##[[KeyPgType Type]]## declaration are ##**Public:**## by default if no member access control specifier is given. NOTE: This keyword is supported in the latest fbc compiler, however, its usefulness is limited since classes and inheritance are **Not** yet supported. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/udt/protected.bas"}}%%(freebasic) '' Example pending classes feature ... %% {{fbdoc item="lang"}} - Available only in the //[[CompilerOptlang -lang fb]]// dialect. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgClass Class]]## - ##[[KeyPgVisPrivate Private:]]## (Access Control) - ##[[KeyPgVisPublic Public:]]## (Access Control) - ##[[KeyPgType Type]]## {{fbdoc item="back" value="CatPgUserDefTypes|User Defined Types"}}{{fbdoc item="title" value="PUBLIC: (Access Control)"}}---- Specifies public member access control in a ##[[KeyPgType Type]]## or ##[[KeyPgClass Class]]## {{fbdoc item="syntax"}}## [[KeyPgType Type]] //typename// **Public:** //member declarations// End Type ## {{fbdoc item="param"}} ##//typename//## name of the ##[[KeyPgType Type]]## or ##[[KeyPgClass Class]]## ##//member declarations//## declarations for fields, functions, or enumerations {{fbdoc item="desc"}} ##**Public:**## indicates that ##//member declarations//## following it have public access. Public members are accessible with any usage of the ##[[KeyPgType Type]]## or ##[[KeyPgClass Class]]##. ##//member declarations//## following ##**Public:**## are public until a different access control specifier is given, like ##[[KeyPgVisPrivate Private:]]## or ##[[KeyPgVisProtected Protected:]]## Members in a ##[[KeyPgType Type]]## declaration are ##**Public:**## by default if no member access control specifier is given. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/udt/public.bas"}}%%(freebasic) TYPE testing PRIVATE: nome as string PUBLIC: number as integer declare sub setNome( byref newnome as string ) END TYPE sub testing.setnome( byref newnome as string ) this.nome = newnome end sub dim as testing myVariable '' We can access these members anywhere since '' they're public myVariable.number = 69 '' myVariable.setNome( "FreeBASIC" ) %% {{fbdoc item="lang"}} - Available only in the //[[CompilerOptlang -lang fb]]// dialect. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgClass Class]]## - ##[[KeyPgVisPrivate Private:]]## (Access Control) - ##[[KeyPgVisProtected Protected:]]## (Access Control) - ##[[KeyPgPublic Public]]## - ##[[KeyPgType Type]]## {{fbdoc item="back" value="CatPgUserDefTypes|User Defined Types"}}{{fbdoc item="title" value="WAIT"}}---- Reads from a hardware port with a mask. {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Wait** ( [[KeyPgByval byval]] //port// [[KeyPgAs as]] [[KeyPgUshort ushort]] , [[KeyPgByval byval]] //and_mask// [[KeyPgAs as]] [[KeyPgInteger integer]] , [[KeyPgByval byval]] //xor_mask// [[KeyPgAs as]] [[KeyPgInteger integer]] = 0 ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## **Wait** //port,// //and_value// [, //xor_value//] ## {{fbdoc item="param"}} ##//port//## Port to read. ##//and_mask//## Mask value to [[KeyPgOpAnd And]] the port value with. ##//xor_mask//## Mask value to [[KeyPgOpXor Xor]] the port value with. {{fbdoc item="ret"}} 0 if successful, -1 on failure. {{fbdoc item="desc"}} ##**Wait**## keeps reading ##//port//## until the reading ANDed with ##//and_mask//## and optionally XORed with ##//xor_mask//## gives a non-zero result. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/hardware/wait.bas"}}%%(freebasic) wait &h3da, &h8 'Old Qbasic way of waiting for the monitor's vsync screensync 'FreeBASIC way of accomplishing the same thing %% {{fbdoc item="target"}} - In the Windows and Linux versions three port numbers (&H3C7, &H3C8, &H3C9) are hooked by the graphics library when a graphics mode is in use to emulate VGA palette handling as in QB. This use is deprecated; use ##[[KeyPgPalette Palette]]## to retrieve and set palette colors. - Using true port access in the Windows version requires the program to install a device driver for the present session. For that reason, Windows executables using hardware port access should be run with administrator permits each time the computer is restarted. Further runs don't require admin rights as they just use the already installed driver. The driver is only 3K in size and is embedded in the executable. {{fbdoc item="see"}} - ##[[KeyPgInp Inp]]## - ##[[KeyPgOut Out]]## {{fbdoc item="back" value="CatPgMisc|Miscellaneous"}} {{fbdoc item="title" value="WBIN"}}---- Returns the binary wstring (Unicode) representation of a number {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Wbin** [[KeyPgOverload overload]] ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgByte byte]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Wbin** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgByte byte]], [[KeyPgByval byval]] //digits// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Wbin** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgShort short]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Wbin** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgShort short]], [[KeyPgByval byval]] //digits// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Wbin** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Wbin** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByval byval]] //digits// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Wbin** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgLongint longint]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Wbin** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgLongint longint]], [[KeyPgByval byval]] //digits// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] ## {{fbdoc item="usage"}}## //result// = **Wbin**( //number// [, //digits//] ) ## {{fbdoc item="param"}} ##//number//## A whole number or expression evaluating to a whole number. ##//digits//## Optional number of digits to return. {{fbdoc item="ret"}} Returns a binary [[KeyPgString string]] representation of //number//. {{fbdoc item="desc"}} Returns a ##[[KeyPgWstring wstring]}## (Unicode) representing the binary value of the integer ##//expression//##. Binary digits range from 0 to 1. If you specify ##//digits//## > 0, the result wstring will be exactly that length. It will be truncated or padded with zeros on the left, if necessary. The length of the ##[[KeyPgWstring wstring]}## will not go longer than the maximum number of digits required for the type of ##//expression//## (32 for an integer, 64 for floating point or longint) {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/wbin.bas"}}%%(freebasic) PRINT WBIN(54321) PRINT WBIN(54321, 5) PRINT WBIN(54321, 20) %% will produce the output: %%1101010000110001 10001 00001101010000110001 %% {{fbdoc item="target"}} - Unicode (w)strings are not supported in the DOS port of FreeBASIC. {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Wbin""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgBin Bin]]## - ##[[KeyPgWhex Whex]]## - ##[[KeyPgWoct Woct]]## {{fbdoc item="back" value="CatPgString|String Functions"}}{{fbdoc item="title" value="WCHR"}}---- Returns a wide-character string containing one or more Unicode characters {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] Wchr ( [[KeyPgByval byval]] //ch// [[KeyPgAs as]] [[KeyPgInteger integer]] [, ... ] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] ## {{fbdoc item="usage"}}## //result// = **Wchr**( //ch0// [, //ch1// ... //chN// ] ) ## {{fbdoc item="param"}} ##//ch//## The Unicode integer value of a character. {{fbdoc item="ret"}} Returns a wide-character string. {{fbdoc item="desc"}} ##**Wchr**## returns a wide-character string containing the character(s) represented by the Unicode values passed to it. When ##**Wchr**## is used with numerical constants or literals, the result is evaluated at compile-time, so it can be used in variable initializers. Not all Unicode characters can be displayed on any machine, the characters available depend on the font presently in use in the console. Graphics modes can't display Unicode characters, as the GfxLib built-in font is not Unicode. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/wchr.bas"}}%%(freebasic) print "the character represented by the UNICODE code of 934 is:"; WCHR(934) print "multiple UNICODE characters:"; WCHR(933, 934, 935) %% will produce the output: <<Φ ΥΦΧ<<::c:: {{fbdoc item="target"}} - DOS does not support ##**Wchr**##. {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Wchr""**##. {{fbdoc item="diff"}} - New to Freebasic {{fbdoc item="see"}} - ##[[KeyPgChr Chr]]## - ##[[KeyPgWstr Wstr]]## {{fbdoc item="back" value="CatPgString|String Functions"}}{{fbdoc item="title" value="WEEKDAY"}}---- Gets the number of day of the week from a [[ProPgDates Date Serial]] {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Weekday** ( [[KeyPgByval byval]] //serial// [[KeyPgAs as]] [[KeyPgDouble double]] , [[KeyPgByval byval]] //firstdayofweek// [[KeyPgAs as]] [[KeyPgInteger integer]] = fbusesystem ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## #include "vbcompat.bi" //result// = **Weekday**( //date_serial// [, //firstdayofweek// ] ) ## {{fbdoc item="param"}} ##//date_serial//## the date ##//firstdayofweek//## the first day of the week {{fbdoc item="ret"}} Returns the week day number from a variable containing a date in [[ProPgDates Date Serial]] format. {{fbdoc item="desc"}} The week day values must be in the range 1-7, its meaning depends on the ##//firstdayofweek//## parameter ##//firstdayofweek//## is optional. {{table columns="3" cellpadding="1" cells="value;first day of week;constant;omitted;sunday;###;0;local settings;fbUseSystem;1;sunday;fbSunday;2;monday;fbMonday;3;tuesday;fbTuesday;4;wednesday;fbWednesday;5;thursday;fbThursday;6;friday;fbFriday;7;saturday;fbSaturday"}} The compiler will not recognize this function unless ##vbcompat.bi## is included. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/dates/weekday.bas"}}%%(freebasic) #include "vbcompat.bi" dim a as double = dateserial (2005, 11, 28) + timeserial(7, 30, 50) print format(a, "yyyy/mm/dd hh:mm:ss "); weekday(a) %% {{fbdoc item="diff"}} - Did not exist in QB. This function appeared in PDS and VBDOS {{fbdoc item="see"}} - [[ProPgDates Date Serials]] {{fbdoc item="back" value="CatPgDate|Date and Time Functions"}}{{fbdoc item="title" value="WEEKDAYNAME"}}---- Gets the name of a week day from its integral representation {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""WeekdayName""** ( [[KeyPgByval byval]] //weekday// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByval byval]] //abbreviate// [[KeyPgAs as]] [[KeyPgInteger integer]] = 0, [[KeyPgByval byval]] //firstdayofweek// [[KeyPgAs as]] [[KeyPgInteger integer]] = fbUseSystem ) [[KeyPgAs as]] [[KeyPgString string]] ## {{fbdoc item="usage"}}## #include "vbcompat.bi" //result// = **""WeekdayName""**( //weekday// [, //abbreviate// [, //firstdayofweek// ] ] ) ## {{fbdoc item="param"}} ##//weekday//## the number of the day of the week ##//abbreviate//## flag to indicate that name should be abbreviated ##//firstdayofweek//## first day of the week {{fbdoc item="ret"}} Returns the local operating system language day of week name from the ##//weekday//## value 1 to 7. {{fbdoc item="desc"}} How ##//weekday//## is interpreted depends on the ##//firstdayofweek//## parameter. If ##//abbreviate//## is true, a 3 letter abbreviation is returned, if false or omitted, the whole name is returned. ##//firstdayofweek//## is an optional parameter specified as follows: {{table columns="3" cellpadding="1" cells="value;first day of week;constant;omitted;sunday;###;0;local settings;fbUseSystem;1;sunday;fbSunday;2;monday;fbMonday;3;tuesday;fbTuesday;4;wednesday;fbWednesday;5;thursday;fbThursday;6;friday;fbFriday;7;saturday;fbSaturday"}} The compiler will not recognize this function unless ##vbcompat.bi## or ##datetime.bi## is included. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/dates/weekdayname.bas"}}%%(freebasic) #include "vbcompat.bi" Dim a As Double = DateSerial(2005, 11, 28) + TimeSerial(7, 30, 50) Print Format(a, "yyyy/mm/dd hh:mm:ss "); WeekDayName(WeekDay(a)) %% {{fbdoc item="diff"}} - Did not exist in QB. This function appeared in Visual Basic. {{fbdoc item="see"}} - [[ProPgDates Date Serials]] {{fbdoc item="back" value="CatPgDate|Date and Time Functions"}}{{fbdoc item="title" value="WEND"}}---- Control flow statement. {{fbdoc item="syntax"}}## **While** [//condition//] [//statement block//] **Wend** ## {{fbdoc item="desc"}} Wend specifies the end of a ##[[KeyPgWhilewend While...Wend]]## loop block. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgWhilewend While...Wend]]## {{fbdoc item="back" value="CatPgMisc|Miscellaneous"}} {{fbdoc item="title" value="WHEX"}}---- Returns the hexadecimal wstring (Unicode) representation of a number {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Whex** [[KeyPgOverload overload]] ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgByte byte]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Whex** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgByte byte]], [[KeyPgByval byval]] //digits// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Whex** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgShort short]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Whex** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgShort short]], [[KeyPgByval byval]] //digits// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Whex** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Whex** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByval byval]] //digits// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Whex** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgLongint longint]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Whex** ( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgLongint longint]], [[KeyPgByval byval]] //digits// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] ## {{fbdoc item="usage"}}## //result// = **Whex**( //number// [, //digits// ] ) ## {{fbdoc item="param"}} ##//number//## A whole number or expression evaluating to a whole number. ##//digits//## Optional number of digits to return. {{fbdoc item="ret"}} Returns a hexadecimal [[KeyPgString string]] representation of //number//. {{fbdoc item="desc"}} Hexadecimal digits range from 0-9, or A-F. If you specify ##//digits//## > 0, the resulting ##[[KeyPgWstring wstring]]## will be exactly that length. It will be truncated or padded with zeros on the left, if necessary. The length of the wstring will not go longer than the maximum number of digits required for the type of ##//expression//## (8 for an integer, 16 for floating point or longint) {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/whex.bas"}}%%(freebasic) print Hex(54321) print Hex(54321, 2) print Hex(54321, 5) %% will produce the output: %%D431 31 0D431 %% {{fbdoc item="target"}} - Unicode (w)strings are not supported in the DOS port of FreeBASIC. {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Whex""**##. {{fbdoc item="diff"}} - New to FreeBASIC. {{fbdoc item="see"}} - ##[[KeyPgHex Hex]]## - ##[[KeyPgWbin Wbin]]## - ##[[KeyPgWoct Woct]]## {{fbdoc item="back" value="CatPgString|String Functions"}}{{fbdoc item="title" value="WHILE"}}---- Control flow statement. {{fbdoc item="syntax"}}## Do **While** //condition// [//statement block//] Loop //or// Do [//statement block//] Loop **While** //condition// //or// **While** [//condition//] [//statement block//] **Wend** ## {{fbdoc item="desc"}} While specifies that a loop block will continue if the ##//condition//## following it evaluates as true. This ##//condition//## is checked during each loop iteration. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgDoloop Do...Loop]]## - ##[[KeyPgWhilewend While...Wend]]## {{fbdoc item="back" value="CatPgMisc|Miscellaneous"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 05:00:53 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: b0b9ecb4a5f2aed573db1d6af95a4e84 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 2910 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="WHILE"}}---- Control flow statement for looping {{fbdoc item="syntax"}}## **While** [//condition//] [//statement block//] **Wend** ## {{fbdoc item="desc"}} The ##**While**## statement will cause the following set of statements in the //statement block// to execute repeatedly if and while the expression //condition// evaluates to true. If //condition// evaluates to false when the WHILE statement is first executed, then the //statement block// is skipped and execution resumes immediately following the enclosing ##**Wend**## statement. If an ##[[KeyPgExit Exit]]## ##**While**## statement is encountered inside the //statement block//, the loop is terminated, and execution resumes immediately following the enclosing ##**Wend**## statement. If a ##[[KeyPgContinue Continue]]## ##**While**## statement is encountered, the rest of the //statement block// is skipped and execution resumes at the ##**While**## statement. Like all control flow statements, the ##**While**## statement can be nested, that is, it can be used in a statement block of another ##[[KeyPgWhile While]]## statement. //**note**: the ##**While**## //keyword// is also used in the ##[[KeyPgDoloop Do...Loop]]## statement to indicate the type of comparison. Used in this way, the DO statement becomes functionally equivalent to the WHILE statement, so do not confuse their enclosing keywords ##Loop## and ##**Wend**##, respectively.// {{fbdoc item="ex"}} In this example, a ##**While**## loop is used to reverse a string by iterating through it backward. The loop stops if index is less than 0 //(0 being the first index in the string)//. {{fbdoc item="filename" value="examples/manual/control/while-wend.bas"}}%%(freebasic) dim as string sentence '' string to reverse sentence = "The quick brown fox jumps over the lazy dog." dim as string ecnetnes dim as integer index index = len( sentence ) - 1 '' point to last character while( index >= 0 ) '' stop after first character ecnetnes += chr( sentence[index] ) '' append character to new string index -= 1 wend print "original: """ ; sentence ; """" print "reversed: """ ; ecnetnes ; """" end 0 %% {{fbdoc item="lang"}} - In the //[[CompilerOptlang -lang qb]]// and //[[CompilerOptlang -lang fblite]]// dialects, variables declared inside a WHILE..WEND loop have a function-wide [[ProPgVariableScope scope]] as in QB - In the //[[CompilerOptlang -lang fb]]// and //[[CompilerOptlang -lang deprecated]]// dialects, variables declared inside a ##**While**##..##**Wend**## block are visible only inside the block, and can't be accessed outside it. {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgExit Exit]]## - ##[[KeyPgContinue Continue]]## - ##[[KeyPgDoloop Do...Loop]]## {{fbdoc item="back" value="CatPgControlFlow|Control Flow"}} {{fbdoc item="title" value="WIDTH"}}---- Sets or gets the number of rows and columns of the display {{fbdoc item="syntax"}}## **Width** [//columns//] [, //rows//] **Width** **Lprint** //columns// **Width** {#//filenum// | //devicename// }, //columns// //result// = **Width** ( ) ## {{fbdoc item="param"}} ##//columns//## columns (in characters) for output ##//rows//## rows (in characters) for output ##//filenum//## file number to apply to ##//devicename//## device name to apply to {{fbdoc item="ret"}} Returns a 32 bit ##[[KeyPgInteger Integer]]## where the [[KeyPgHiword high word]] is the number of rows and the [[KeyPgLoWord low word]] is the number of columns currently set. {{fbdoc item="desc"}} Sets the maximum number of columns of characters of an output device (console, printer or text file). If text sent to the device reaches the width an automatic carriage return is generated. If the device is the console a second argument specifying maximum number of rows is allowed. On a Windows any values > 0 can be used in windowed mode. On DOS or Windows full-screen console, the valid dimensions depend on the capabilities of the hardware. Linux doesn't allow applications to change the console size. Using ##**Width**## as a function returns the current console width in the low word and the current height in the high word. In graphics modes ##**Width**## is used to indirectly select the font size by setting one of the height * width pairs allowed (See ##[[KeyPgScreengraphics Screen (Graphics)]]##). If ##//rows//## * ##//cols//## is an invalid combination, no changes are made to the screen display. Valid font heights are 8 pixels, 14 pixels and 16 pixels. The fonts all have a fixed width of 8 pixels. Using the ##**Width**## command forces a screen clear (##[[KeyPgCls Cls]]##) {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/console/width-func.bas"}}%%(freebasic) Dim As Integer w w = Width Print "rows: " & hiword(w) Print "cols: " & loword(w) %% {{fbdoc item="filename" value="examples/manual/console/width.bas"}}%%(freebasic) ''Set up a graphics screen const W = 320, H = 200 screenres W, H dim as integer twid, tw, th '' Fetch and print current text width/height: twid = width() tw = loword(twid): th = hiword(twid) print "Default for current screen (8*8)" print "Width: " & tw print "Height: " & th sleep width W\8, H\16 '' Use 8*16 font twid = width() tw = loword(twid): th = hiword(twid) print "Set to 8*16 font" print "Width: " & tw print "Height: " & th sleep width W\8, H\14 '' Use 8*14 font twid = width() tw = loword(twid): th = hiword(twid) print "Set to 8*14 font" print "Width: " & tw print "Height: " & th sleep width W\8, H\8 '' Use 8*8 font twid = width() tw = loword(twid): th = hiword(twid) print "Set to 8*8 font" print "Width: " & tw print "Height: " & th sleep %% {{fbdoc item="diff"}} - ##//columns//## was limited to ##40## or ##80##, while ##//rows//## could be ##25##, ##30##, ##43##, ##50## or ##60##, depending on the graphics hardware and screen mode being used. {{fbdoc item="see"}} - ##[[KeyPgLoWord Loword]]## - ##[[KeyPgHiword Hiword]]## - ##[[KeyPgCsrlin Csrlin]]## - ##[[KeyPgPos Pos]]## {{fbdoc item="back" value="CatPgConsole|Console Functions"}}{{fbdoc item="title" value="WINDOW"}}---- Sets new view coordinates mapping for current viewport {{fbdoc item="syntax"}}## **Window** [ [SCREEN] ( //x1//, //y1// )-( //x2//, //y2// ) ] ## {{fbdoc item="param"}} ##SCREEN## Optional argument specifying y coordinates increase from top to bottom. ##( //x1//, //y1// )-( //x2//, //y2// )## New floating point values corresponding to the opposite corners of the current viewport. {{fbdoc item="desc"}} ##**Window**## is used to define a new coordinates system. ##(//x1//,//y1//)## and ##(//x2//,//y2//)## are the new coordinates to be mapped to the opposite corners of the current viewport; all future coordinates passed to graphics primitive statements will be affected by this new mapping. If ##SCREEN## is omitted, the new coordinates system will be Cartesian, that is, with y coordinates increasing from bottom to top. Call ##**Window**## with no argument to disable the coordinates transformation. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/window.bas"}}%%(freebasic) screen 13 '' define clipping area view ( 10, 10 ) - ( 310, 150 ), 1, 15 '' set view coordinates window ( -1, -1 ) - ( 1, 1 ) '' Draw X axis line (-1,0)-(1,0),7 draw string ( 0.8, -0.1 ), "X" '' Draw Y axis line (0,-1)-(0,1),7 draw string ( 0.1, 0.8 ), "Y" dim as single x, y, s '' compute step size s = 2 / pmap( 1, 0 ) '' plot the function for x = -1 to 1 step s y = x ^ 3 pset( x, y ), 14 next x '' revert to screen coordinates window '' remove the clipping area view screen '' draw title draw string ( 120, 160 ), "Y = X ^ 3" sleep %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgScreengraphics Screen (Graphics)]]## - ##[[KeyPgViewgraphics View (Graphics)]]## - ##[[KeyPgPmap PMap]]## {{fbdoc item="back" value="CatPgGfxScreen|Screen Functions"}}{{fbdoc item="title" value="WINDOWTITLE"}}---- Sets the program window title {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgSub sub]] **Windowtitle** ( [[KeyPgByref byref]] //title// [[KeyPgAs as]] [[KeyPgString string]] ) ## {{fbdoc item="usage"}}## **""WindowTitle""** //title// ## {{fbdoc item="param"}} ##//title//## the string to be assigned as new window title. {{fbdoc item="desc"}} This statement is useful to change the program window title. The new title set will become active immediately if the program already runs in windowed mode, otherwise will become the new title for any window produced by subsequent calls to the ##[[KeyPgScreengraphics Screen (Graphics)]]## statement. If this function is not called before setting a new windowed mode via ##[[KeyPgScreengraphics Screen (Graphics)]]##, the program window will use the executable file name (without the extension) as title by default. This command has no effect for consoles. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/windowtitle.bas"}}%%(freebasic) 'Set the window title WINDOWTITLE "FreeBASIC example program" 'Set screen mode SCREEN 13 SLEEP %% {{fbdoc item="target"}} - Not present in DOS version / target of FreeBASIC {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Windowtitle""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgScreengraphics Screen (Graphics)]]## {{fbdoc item="back" value="CatPgGfxScreen|Screen Functions"}}{{fbdoc item="title" value="WINPUT()"}}---- Reads a number of wide-characters from console or file {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Winput**( [[KeyPgByval byval]] //num// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgString wstring]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Winput**( [[KeyPgByval byval]] //num// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByval byval]] //filenum// [[KeyPgAs as]] [[KeyPgInteger integer]] = 0 ) [[KeyPgAs as]] [[KeyPgString wstring]] ## {{fbdoc item="usage"}}## //result// = **Winput**( //num// [, [#]//filenum// } ) ## {{fbdoc item="param"}} ##//num//## Number of characters to read. ##//filenum//## File number of bound file or device. {{fbdoc item="ret"}} Returns a [[KeyPgWstring Wstring]] of the characters read. {{fbdoc item="desc"}} Reads a number of wide-characters from the console, or a bound file/device specified by ##//filenum//##. The first version waits for and reads ##//n//## wide characters from the keyboard buffer. Extended keys are not read. The characters are not echoed to the screen. The second version waits for and reads ##//n//## wide characters from a file or device. The file position is updated. ~&//Note: FreeBASIC does not currently support reading wide-characters from the console.// {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/console/winput.bas"}}%%(freebasic) dim char as wstring * 2 dim filename as string, enc as string dim f as integer line input "Please enter a file name: ", filename line input "Please enter an encoding type (optional): ", enc if enc = "" then enc = "ascii" f = freefile if open(filename for input encoding enc as #f) = 0 then print "Press space to read a character from the file, or escape to exit." do select case input(1) case " " 'Space if eof(f) then print "You have reached the end of the file." exit do end if char = winput(1, f) print char & " (char no " & asc(char) & ")" case chr(27) 'Escape exit do end select loop close #f else print "There was an error opening the file." end if %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect. {{fbdoc item="diff"}} - QB does not support Unicode {{fbdoc item="see"}} - ##[[KeyPgInputnum Input()]]## - ##[[KeyPgOpen Open]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}}{{fbdoc item="back" value="CatPgInput|User Input"}}{{fbdoc item="title" value="WITH"}}---- Statement block to allow implicit access to fields in a user defined type variable {{fbdoc item="syntax"}}## **With** //user_defined_var// //statements// **End With** ## {{fbdoc item="desc"}} The ##**With...End With**## block allows the omission of the name of a user defined variable when referring to its fields. It's a shorthand to save typing and avoid cluttering the source. ##**With**## can also be used with dereferenced pointers, as the second example shows. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/udt/with-1.bas"}}%%(freebasic) type rect_type x as single y as single end type dim the_rectangle as rect_type dim as integer temp, t with the_rectangle temp = .x .x = 234 * t + 48 + .y .y = 321 * t + 2 end with %% {{fbdoc item="filename" value="examples/manual/udt/with-2.bas"}}%%(freebasic) type rect_type x as single y as single end type dim the_rectangle as rect_type ptr the_rectangle = callocate( 5 * len( rect_type ) ) dim as integer loopvar, temp, t for loopvar = 0 to 4 with the_rectangle[loopvar] temp = .x .x = 234 * t + 48 + .y .y = 321 * t + 2 end with next %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__With""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgType Type]]## {{fbdoc item="back" value="CatPgUserDefTypes|User Defined Types"}}{{fbdoc item="title" value="WOCT"}}---- Converts a number to a Unicode octal representation {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""Woct""**( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgByte byte]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""Woct""**( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgByte byte]], [[KeyPgByval byval]] //digits// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""Woct""**( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgShort short]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""Woct""**( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgShort short]], [[KeyPgByval byval]] //digits// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""Woct""**( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""Woct""**( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgInteger integer]], [[KeyPgByval byval]] //digits// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""Woct""**( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgLongint longint]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **""Woct""**( [[KeyPgByval byval]] //number// [[KeyPgAs as]] [[KeyPgLongint longint]], [[KeyPgByval byval]] //digits// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] ## {{fbdoc item="usage"}}## //result// = **Woct**( //number// [, //digits// ] ) ## {{fbdoc item="param"}} ##//number//## Number to convert to octal representation. ##//digits//## Desired number of digits in the returned string. {{fbdoc item="ret"}} The Unicode octal representation of the number, truncated or padded with zeros ("0") to the specified number of digits, if specified. {{fbdoc item="desc"}} Returns the octal [[KeyPgWstring Wstring]] (Unicode) representation of ##//number//##. Octal digits range from 0 to 7. If you specify ##//digits//## > 0, the result string will be exactly that length. It will be truncated or padded with zeros on the left, if necessary. The length of the returned string will not be longer than the maximum number of digits required for the type of ##//number//## (3 characters for ##[[KeyPgByte byte]]##, 6 for ##[[KeyPgShort short]]##, 11 for ##[[KeyPgInteger integer]]##, and 22 for ##[[KeyPgLongint longint]]##) {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/woct.bas"}}%%(freebasic) print Woct(54321) print Woct(54321, 4) print Woct(54321, 8) %% will produce the output: %%152061 2061 00152061 %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Woct""**##. {{fbdoc item="target"}} - Unicode (w)strings are not supported in the DOS port of FreeBASIC. {{fbdoc item="diff"}} - In QBASIC Unicode was not supported. {{fbdoc item="see"}} - ##[[KeyPgWbin Wbin]]## - ##[[KeyPgWhex Whex]]## {{fbdoc item="back" value="CatPgString|String Functions"}}{{fbdoc item="title" value="WRITE"}}---- Outputs a comma-separated list of values to the screen {{fbdoc item="syntax"}}## **Write** [ //expressionlist// ] ## {{fbdoc item="param"}} ##//expressionlist//## Comma-separated list of items to print {{fbdoc item="desc"}} Outputs the values in ##//expressionlist//## to the screen. The values are separated with commas, and strings are enclosed in double quotes. Numeric values greater than zero (0) and less than one (1) are prefixed with a zero (0) if none is given (e.g., a value of ##-.123## will be output as ##-0.123##). Extra zeroes are truncated. If no expression list is given, **Write** outputs a carriage return. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/console/write.bas"}}%%(freebasic) dim i as integer = 10 dim d as double = 123.456 dim s as string = "text" write 123, "text", -.45600 write write i, d, s %% will produce the output: %% 123,"text",-0.456 10,123.456,"text" %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgWritePp Write #]]## - ##[[KeyPgPrint Print]]## {{fbdoc item="back" value="CatPgConsole|Console Functions"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 05:01:06 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 5252c659ce91259f6b92f661ceee13d1 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 611 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="WRITE (File Access)"}}---- File access specifier {{fbdoc item="syntax"}}## Open //filename// As String For Binary Access **Write** As #//filenum// As Integer ## {{fbdoc item="desc"}} Specifier for the ##[[KeyPgAccess Access]]## clause in the ##[[KeyPgOpen Open]]## statement. ##**Write**## specifies that the file is accessible for output. {{fbdoc item="ex"}} See example at ##[[KeyPgAccess Access]]## {{fbdoc item="diff"}} - None known. {{fbdoc item="see"}} - ##[[KeyPgAccess Access]]## - ##[[KeyPgOpen Open]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}} {{fbdoc item="title" value="WRITE #"}}---- Outputs a comma-separated list of values to a text file or device {{fbdoc item="syntax"}}## **Write #** //filenum// **,** [ //expressionlist// ] ## {{fbdoc item="param"}} ##//filenum//## File number of an open file or device. ##//expressionlist//## Comma-separated list of items to print {{fbdoc item="desc"}} Outputs the values in ##//expressionlist//## to the text file or device bound to ##//filenum//##. The values are separated with commas, and strings are enclosed in double quotes. Numeric values greater than zero (0) and less than one (1) are prefixed with a zero (0) if none is given (e.g., a value of ##-.123## will be output as ##-0.123##). Extra zeroes are truncated. If no expression list is given, ##**Write #**## outputs a carriage return (note that the comma after ##//filenum//## is still necessary, even if no expression list is given). The purpose of ##**Write #**## is to create a file that can be read back by using [[KeyPgInputPp Input #]]. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/fileio/write.bas"}}%%(freebasic) const filename as string = "file.txt" dim filenum as integer = freefile() if 0 <> open(filename, for output, as filenum) then print "error opening " & filename & " for output." end -1 end if dim i as integer = 10 dim d as double = 123.456 dim s as string = "text" write #filenum, 123, "text", -.45600 write #filenum, write #filenum, i, d, s %% will produce the file: %% 123,"text",-0.456 10,123.456,"text" %% {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgWrite Write]]## - ##[[KeyPgPrintPp Print #]]## - ##[[KeyPgInputPp Input #]]## {{fbdoc item="back" value="CatPgFile|File I/O Functions"}}{{fbdoc item="title" value="WSPACE"}}---- Fills a certain length of a wstring with spaces (" ") {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Wspace**( //count// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] ## {{fbdoc item="usage"}}## //result// = **Wspace**( //count// ) ## {{fbdoc item="param"}} ##//count//## An integer type specifying the length of the string to be created. {{fbdoc item="ret"}} The created wstring. An empty string will be returned if ##//count//## <= 0. {{fbdoc item="desc"}} ##**Wspace**## creates a wstring (wide character string- Unicode) with the specified number of spaces. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/wspace.bas"}}%%(freebasic) DIM A AS WSTRING *14 A="x"+wspace(10)+"x" 'prints x x %% {{fbdoc item="target"}} - Unicode (w)strings are not supported in the DOS port of FreeBASIC. {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Wspace""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgSpace Space]]## {{fbdoc item="back" value="CatPgString|String Functions"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 05:01:14 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: 8de27417422eef9cb78fbd96d82a4b16 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 3839 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="WSTR"}}---- Returns a wide-character string representation of a number or ASCII character string {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Wstr** [[KeyPgOverload overload]] ( [[KeyPgByval byval]] //n// [[KeyPgAs as]] [[KeyPgByte byte]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Wstr** ( [[KeyPgByval byval]] //n// [[KeyPgAs as]] [[KeyPgUbyte ubyte]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Wstr** ( [[KeyPgByval byval]] //n// [[KeyPgAs as]] [[KeyPgShort short]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Wstr** ( [[KeyPgByval byval]] //n// [[KeyPgAs as]] [[KeyPgUshort ushort]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Wstr** ( [[KeyPgByval byval]] //n// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Wstr** ( [[KeyPgByval byval]] //n// [[KeyPgAs as]] [[KeyPgUinteger uinteger]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Wstr** ( [[KeyPgByval byval]] //n// [[KeyPgAs as]] [[KeyPgLongint longint]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Wstr** ( [[KeyPgByval byval]] //n// [[KeyPgAs as]] [[KeyPgUlongint ulongint]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Wstr** ( [[KeyPgByval byval]] //n// [[KeyPgAs as]] [[KeyPgSingle single]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Wstr** ( [[KeyPgByval byval]] //n// [[KeyPgAs as]] [[KeyPgDouble double]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Wstr** ( [[KeyPgByref byref]] //str// [[KeyPgAs as]] [[KeyPgString string]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Wstr** ( [[KeyPgByval byval]] //str// [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgPtr ptr]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] ## {{fbdoc item="usage"}}## //result// = **Wstr**( //number// ) //or// //result// = **Wstr**( //string// ) ## {{fbdoc item="param"}} ##//number//## Numeric expression to convert to a wide-character string. ##//string//## String expression to convert to a wide-character string. {{fbdoc item="ret"}} Returns the wide-character representation of the numeric or string expression. {{fbdoc item="desc"}} ##**Wstr**## converts numeric variables to their wide-character string representation. It is the wide-character equivalent to ##[[KeyPgStr Str]]##. ##**Wstr**## also converts ASCII character strings to Unicode character strings. If a wide-character string is given, that string is returned unmodified. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/wstr.bas"}}%%(freebasic) #if defined( __FB_WIN32__ ) #include "windows.bi" #endif Dim zs As ZString * 20 Dim ws As WString * 20 zs = "Hello World" ws = WStr(zs) #if defined( __FB_WIN32__ ) MessageBox(null, ws, WStr("Unicode 'Hello World'"), MB_OK Or MB_ICONINFORMATION) #else print ws print WStr("Unicode 'Hello World'") #endif %% {{fbdoc item="target"}} - DOS does not support ##**Wstr**##. {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Wstr""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgStr Str]]## - ##[[KeyPgWstring Wstring]]## {{fbdoc item="back" value="CatPgCasting|Converting Data Types"}}{{fbdoc item="back" value="CatPgString|String Functions"}} {{fbdoc item="title" value="WSTRING"}}---- Standard data type: wide character string {{fbdoc item="syntax"}}## [[KeyPgDim dim]] //variable// [[KeyPgAs as]] **Wstring** * //size// [[KeyPgDim dim]] //variable// [[KeyPgAs as]] **Wstring** [[KeyPgPtr ptr]] ## {{fbdoc item="desc"}} A ##**Wstring**## is a fixed-size array of wide-chars that never overflows if the size is known at compile-time. It has no descriptor, and does never resize unless it's a pointer and ##[[KeyPgAllocate Allocate]]##/##[[KeyPgReallocate Reallocate]]##/##[[KeyPgDeallocate Deallocate]]## are used directly. The end of the string is marked by the character 0, so that character must never be part of a ##**Wstring**## or the content will be truncated. This type is provided for support non-Latin based alphabets. Any intrinsic string function like ##[[KeyPgLeft Left]]## will work with ##**Wstring**##s too, as will any string operator. Besides ASCII files with Unicode escape sequences (\u), FreeBASIC can parse UTF-8, UTF-16LE, UTF-16BE, UTF-32LE and UTF-32BE source files. The FreeBASIC text file functions can read and write Unicode files in different encodings, provided the ##[[KeyPgEncoding encoding]]## is specified when the file is opened. The text is automatically converted to the internal encoding at read and converted back to the file encoding at write. ##[[KeyPgSizeof sizeof]]##( ##**Wstring**## ) returns the number of bytes used by a ##**Wstring**## character in the current platform. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/datatype/wstring.bas"}}%%(freebasic) dim as wstring * 14 str1 => "hello, world" print str1 print len(str1) 'returns 12, the length of the string it contains print sizeof(str1) 'returns 14 * sizeof(wstring), the number of bytes used by the variable %% {{fbdoc item="filename" value="examples/manual/datatype/wstring2.bas"}}%%(freebasic) dim as wstring ptr str2 str2 = allocate( 14 * len(wstring) ) *str2 = "hello, world" print *str2 print len(*str2) 'returns 12, the length of the string it points to %% {{fbdoc item="target"}} Support for wstrings relies in the C runtime library available in the platform and the internal format may vary. - Unicode is not supported in the DOS port of FreeBASIC. In this port a character takes up always 1 byte and ##[[KeyPgWstring Wstrings]]## will behave as standard ASCII ##[[KeyPgZstring Zstrings]]## - On Win32 wstrings are encoded in UCS-2 (UTF-16 LE) and a character takes up 2 bytes. - On Linux wstrings are encoded in UCS-4 and a character takes up 4 bytes. {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Wstring""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgString String]]## (data type) - ##[[KeyPgZstring Zstring]]## (data type) - ##[[KeyPgWstring Wstring]]## (data type) - ##[[KeyPgStringFunction String]]## (function) - ##[[KeyPgWstringFunction Wstring]]## (function) - ##[[KeyPgWspace Wspace]]## - ##[[KeyPgWstr Wstr]]## - ##[[KeyPgWchr Wchr]]## - ##[[KeyPgWbin Wbin]]## - ##[[KeyPgWhex Whex]]## - ##[[KeyPgWoct Woct]]## - ##[[KeyPgWinput Winput()]]## {{fbdoc item="back" value="CatPgStdDataTypes|Standard Data Types"}}{{fbdoc item="back" value="CatPgString|String Functions"}} {{fbdoc item="title" value="WSTRING (Function)"}}---- Fills a wstring with a certain length of a certain wide character {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Wstring**( //count// [[KeyPgAs as]] [[KeyPgInteger integer]], //ch_code// [[KeyPgAs as]] [[KeyPgInteger integer]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Wstring**( //count// [[KeyPgAs as]] [[KeyPgInteger integer]], //ch// [[KeyPgAs as]] [[KeyPgWstring wstring]] ) [[KeyPgAs as]] [[KeyPgWstring wstring]] ## {{fbdoc item="usage"}}## //result// = **Wstring**( //count//, //ch_code// ) //or// //result// = **Wstring**( //count//, //ch// ) ## {{fbdoc item="param"}} ##//count//## An integer specifying the length of the wstring to be created. ##//ch_code//## An integer specifying the Unicode char to be used to fill the wstring. ##//ch//## A wstring whose first character is to be used to fill the wstring. {{fbdoc item="ret"}} The created wstring. An empty wstring will be returned if either ##//ch//## is an empty string, or ##//count//## <= 0. {{fbdoc item="desc"}} ##**Wstring**## generates a temporal wstring filled with ##//count//## copies of an [[Unicode Unicode]] character. This string can be printed or assigned to a previously ##[[KeyPgDim Dim]]##ed ##**Wstring**##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/strings/wstring.bas"}}%%(freebasic) PRINT WSTRING( 4, 934 ) PRINT WSTRING( 5, Wstr("Indeed") ) end 0 %% <<ΦΦΦΦ IIIII<< ::c:: {{fbdoc item="target"}} - Unicode (w)strings are not supported in the DOS port of FreeBASIC {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Wstring""**##. {{fbdoc item="diff"}} - QBasic does not support [[Unicode Unicode]] {{fbdoc item="see"}} - ##[[KeyPgString String]] (data type)## - ##[[KeyPgWspace Wspace]]## - ##[[KeyPgWstring Wstring]] (data type)## {{fbdoc item="back" value="CatPgString|String Functions"}}{{fbdoc item="title" value="XOR"}}---- Parameter to the ##[[KeyPgPutgraphics Put]]## graphics statement which uses a bit-wise ##[[KeyPgOpXor Xor]]## as the blitting method {{fbdoc item="syntax"}}## **Put** [ //target//, ] [ STEP ] ( //x//,//y// ), //source// [ ,( //x1//,//y1// )-( //x2//,//y2// ) ], **Xor** ## {{fbdoc item="param"}} ##**Xor**## Required. {{fbdoc item="desc"}} The ##**Xor**## method combines each source pixel with the corresponding destination pixel, using the bit-wise ##[[KeyPgOpXor Xor]]## function. The result of this is output as the destination pixel. This method works in all graphics modes. There is no mask color, although color values of ##0## (##[[KeyPgRgba RGBA]](0, 0, 0, 0)## in full-color modes) will have no effect, because of the behavior of ##[[KeyPgOpXor Xor]]##. In full-color modes, each component (red, green, blue and alpha) is kept in a discrete set of bits, so the operation can be made to only affect some of the channels, by making sure the all the values of the other channels are set to ##0##. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/gfx/put-xor.bas"}}%%(freebasic) ''open a graphics window ScreenRes 320, 200, 16 ''create a sprite containing a circle Const As Integer r = 32 Dim c As Any Ptr = ImageCreate(r * 2 + 1, r * 2 + 1, 0) Circle c, (r, r), r, RGBA(255, 255, 255, 0), , , 1, f ''put the three sprites, overlapping each other in the middle Put (146 - r, 108 - r), c, xor Put (174 - r, 108 - r), c, xor Put (160 - r, 84 - r), c, xor ''free the memory used by the sprite ImageDestroy c ''pause the program before closing Sleep %% {{image class="center" title="Put Xor example output" url="/images/put-xor.png"}} {{fbdoc item="diff"}} - None {{fbdoc item="see"}} - ##[[KeyPgOpXor Xor]]## - ##[[KeyPgPutgraphics Put (Graphics)]]## {{fbdoc item="back" value="CatPgGfx2D|2D Drawing Functions"}}{{fbdoc item="title" value="YEAR"}}---- Gets the year from a [[ProPgDates Date Serial]] {{fbdoc item="syntax"}}## [[KeyPgDeclare declare]] [[KeyPgFunction function]] **Year** ( [[KeyPgByval byval]] //date_serial// [[KeyPgAs as]] [[KeyPgDouble double]] ) [[KeyPgAs as]] [[KeyPgInteger integer]] ## {{fbdoc item="usage"}}## #include "vbcompat.bi" //result// = **Year**( //date_serial// ) ## {{fbdoc item="param"}} ##//date_serial//## the date {{fbdoc item="ret"}} Returns the year from a variable containing a date in [[ProPgDates Date Serial]] format. {{fbdoc item="desc"}} The compiler will not recognize this function unless ##vbcompat.bi## is included. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/dates/year.bas"}}%%(freebasic) #include "vbcompat.bi" dim a as double = dateserial (2005, 11, 28) + timeserial(7, 30, 50) print format(a, "yyyy/mm/dd hh:mm:ss "); year(a) %% {{fbdoc item="diff"}} - Did not exist in QB. This function appeared in PDS and VBDOS {{fbdoc item="see"}} - [[ProPgDates Date Serials]] {{fbdoc item="back" value="CatPgDate|Date and Time Functions"}} HTTP/1.1 200 OK Date: Sat, 17 May 2008 05:01:23 GMT Server: Apache/1.3.37 (Unix) mod_gzip/1.3.26.1a mod_fastcgi/2.4.2 mod_auth_passthrough/1.8 mod_log_bytes/1.2 mod_bwlimited/1.4 FrontPage/5.0.2.2635.SR1.2 mod_ssl/2.8.28 OpenSSL/0.9.7a PHP-CGI/0.1b Cache-Control: no-cache ETag: a10bed6f0fe851fd8b7e657dbd6ec9a9 Expires: Thu, 19 Nov 1981 08:52:00 GMT Pragma: no-cache X-Powered-By: PHP/4.4.4 Content-Length: 2531 Keep-Alive: timeout=6, max=99 Connection: Keep-Alive Content-Type: text/plain {{fbdoc item="title" value="ZSTRING"}}---- Standard data type: 8 bit character string {{fbdoc item="syntax"}}## [[KeyPgDim dim]] //variable// [[KeyPgAs as]] **Zstring** * //size// [[KeyPgDim dim]] //variable// [[KeyPgAs as]] **Zstring** [[KeyPgPtr ptr]] ## {{fbdoc item="desc"}} A ##**Zstring**## is a C-style fixed-size array of chars. It has no descriptor so it's faster to pass it as an argument to functions. FreeBASIC avoids any overflow that could occur, by truncating the contents. A ##**Zstring**## [[KeyPgPtr ptr]] can point to a standard ##**Zstring**##, also can be used to implement an "user-managed" ##**Zstring**##, in this case ##[[KeyPgAllocate Allocate]]##/##[[KeyPgReallocate Reallocate]]##/##[[KeyPgDeallocate Deallocate]]## must be used to size-resize-dispose it and is up to the user to avoid overflows . The end of the string is marked by a character 0 ASCII, this is automatically managed by the FreeBASIC string handling functions. A character 0 ASCII must never enter in the text of a ##**Zstring**## or it will be truncated, as no descriptor exists . In a ##**Zstring**##, ##[[KeyPgLen Len]]## returns the size of the contained string and ##[[KeyPgSizeof Sizeof]]## returns the space allocated to the ##**Zstring**##. This type is provided for easy interfacing with C libraries and to also replace the fixed-length strings, that can't be managed through pointers. Any intrinsic string functions like ##[[KeyPgLeft Left]]## will work with ##**Zstring**##'s too, plus any string operator. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/datatype/zstring.bas"}}%%(freebasic) dim as zstring * 14 str1 => "hello, world" print str1 print len(str1) 'returns 12, the size of the string it contains print sizeof(str1) 'returns 14, the size of the variable %% {{fbdoc item="filename" value="examples/manual/datatype/zstring2.bas"}}%%(freebasic) dim as zstring ptr str2 str2 = allocate( 14 ) *str2 = "hello, world" print *str2 print len(*str2) 'returns 12, the size of the string it contains print sizeof(*str2) 'returns len(zstring), the size of the variable %% {{fbdoc item="lang"}} - Not available in the //[[CompilerOptlang -lang qb]]// dialect unless referenced with the alias ##**""__Zstring""**##. {{fbdoc item="diff"}} - New to FreeBASIC {{fbdoc item="see"}} - ##[[KeyPgString String]]## - ##[[KeyPgWstring Wstring]]## {{fbdoc item="back" value="CatPgStdDataTypes|Standard Data Types"}}{{fbdoc item="back" value="CatPgString|String Functions"}}