Anda di halaman 1dari 5

QBasic Language Quick Summary JPB 16/11/97 ----------------------------Commas are used to separate variables and parameters, Colons are

used to separate statements that appear on the same line. Don't use the underscore symbol < _ > in your variable names. DATA Types/Examples =================== Number of bytes % integer 2 bytes & long integer 4 bytes ! single precision 4 bytes # double precision 8 bytes $ string up to 32767 examples: num% integer count& long wage! single Range -32768 to 32767 -2147483648 to 2147483647 7 digits of sig. (default type) 15 digits of significance up to 32767 characters wage single balance# double names$ string

Note DEFtype statements give an alternative to using the symbols above but DATA-type suf. (%, &, !, #, or $) always takes precedence over a DEFtype. DEFINT DEFLNG DEFSNG DEFDBL DEFSTR letterrange letterrange letterrange letterrange letterrange [,letterrange]... [,letterrange]... [,letterrange]... [,letterrange]... [,letterrange]... variables that start with a letter from letterrange will all be of the specified type. example: DEFINT A-B,zz Anum Bnum Cnum zzNum (all integers)

You can also use the DIM statement to specify a type, examples: DIM DIM DIM DIM number AS DOUBLE address AS STRING code AS STRING * 10 apples AS INTEGER double precision type. variable length string. fixed length string (10 characters in this case). integer type

Mathematical operators Relational Operators ====================== ==================== + Addition = Equal to Subtraction <> Not equal to * Multiplication > Greater than / Division < Less than ^ Exponention (raising to a power) >= Greater than or equal to \ Integer division <= Less than or equal to MOD Remainder division Constants, variables and arrays =============================== CONST define a symbolic constant/s ex. CONST daysperweek = 7 DIM declares an array DIM var(1 to 5) DIM element(9) (element 0 to 9) TYPE create user defined types. ex. TYPE typename ... END TYPE ERASE reinitialize elements of a static array (deallocates dynamic arrays) DATA stores numeric or string data to be used with READ (DATA 1, 2, 3, 4) READ used to read values from a DATA statement and assign them to variables. RESTORE used to change the READ order back to the start (or some other point) OPTION BASE declare the min. value for array sub. (don't use, use DIM) REDIM changes the space allocated to dynamically defined array. SWAP exchanges the contents of two variables. ex. SWAP num(1),num(2) UBOUND(array[,dimension]) returns highest subscript value. LBOUND(array[,dimension]) returns lowest subscript value. Control program flow (expr means numeric expression) ==================== (... means one or more statement lines) (see also "Set traps for events and errors")

DO DO DO DO DO

... LOOP UNTIL UNTIL expr ... ... LOOP WHILE WHILE expr ... ... LOOP REM

expr LOOP expr LOOP always loop

Note: if the test is at the end of the statements then statements will be done at least once. example DO ... LOOP WHILE

FOR i = IF expr IF exp1 ON expr GOTO

1 TO 100 STEP v ... NEXT i (v is step value, if omitted is 1) THEN ... ELSE ... if expr true do 1st ... if false do 2nd ... THEN ... ELSEIF exp2 THEN ... ELSEIF exp3 THEN ... ELSE ... END IF GOSUB sub1, sub2, sub3 In this example expr should = 1 - 3 Go to line number or label (use sparingly, if at all) each case line looks for a match with test_exp. there is one of these to match each valid case. this is used for 'no match found' (ie. default). terminates case statements block.

SELECT CASE test_exp CASE expr1 ... CASE ELSE ... END SELECT

END (prog, close files) also used with DEF, FUNCTION, IF, SELECT, SUB, TYPE SYSTEM closes all files and returns to operating system (or qbasic). STOP stops the program at any point (does not close files). EXIT DO, EXIT FOR, EXIT SUB, EXIT FUNCTION (gives a break out point). Define and call Basic procedures ================================ CALL subname[(parameters)] used to call a QBasic procedure. SUB subname ... END SUB (use EDIT -> New SUB to create your subroutine). DECLARE SUB subname(parameters) the editor puts this in your main program. FUNCTION fname ... END FUNCTION define a function type procedure (use EDIT). DECLARE fname(arguments) (this line added to main prog by editor after save). GOSUB this is the older way to call a subroutine (CALL is the modern way). RETURN returns from subroutine, this must be used to return from a GOSUB. DEF FName[(arguments)]expression (older way to define functions). DEF FName[(arguments)] ... END DEF (used with more than one statment line). RUN run a program (the one in memory or a specified alternative). CHAIN "aprogram.bas" transfers to another program, best avoid, poor struct. COMMON variables used to transfer variables to a chained program. SHELL run a DOS program or go to DOS shell (if no prog name). SHARED STATIC gives access to a variable without passing it to a procedure. preserves a variable value between procedure calls.

Device input/output =================== INKEY$ gets code of key pressed (returns null string if no key pressed). INPUT Statement inputs values from keyboard, ex. INPUT "enter name",name$ LINE INPUT read entire line (including commas etc.) into a string. LPOS returns the current printer head position (in line buffer). PRINT writes to the screen display or a file. PRINT USING writes formatted output to screen or file. LPRINT similar to PRINT but output goes to line printer. LPRINT USING similar to PRINT USING but output goes to printer. SPC(num TAB(column) moves the cur. on to the spec. col.(PRINT and LPRINT) OPEN COM opens a communications port for input/output (baud rate etc.) STICK Function returns position of joystick A(x or y) or B(x or y). STRIG Function returns joystick trigger status (joystick buttons). INP returns a byte read from I/O port. OUT sends a byte to the specified port. WAIT pauses a program until a specified bit pattern received from a port. BEEP PLAY play a short tone via PC speaker to draw users attention. Statement play a tune specified by the command string.

PLAY(dummy_numeric_argument) returns number of notes in background queue. SOUND freq,duration makes a sound using specified parameters. SCREEN control ============== CLS clears text or graphics viewport ie. current screen (3 other options) SCREEN Statement defines the screen characteristics, color mode etc.. SCREEN Function returns ascii code (or color in graphics mode of location) COLOR used to set the color for text or graphics (ex. COLOR foreg,backg). PALETTE and PALETTE USING used to set the graphics colors (EGA VGA). WIDTH sets the number of columns on the screen (or other device, or file). VIEW PRINT defines the text mode scrolling region (topline to bottom line) CSRLIN returns the current line (row) position of the cursor. POS(dummy_argument) gets the current cursor column position. LOCATE row,column reposition the cursor. VIEW define a restricted area for displaying graphics (viewport). WINDOW used to adjust the logical dimensions of the current viewport. SCREEN 0 Background and Foreground Colors (background colors go up to 7). ========================================== Color number Background Foreground Color number Foreground 0 Black Black 8 Gray 1 Blue Blue 9 Light Blue 2 Green Green 10 Light Green 3 Cyan Cyan 11 Light Cyan 4 Red Red 12 Light Red 5 Magenta Magenta 13 Light Magenta 6 Brown Brown 14 Yellow 7 White White 15 Bright White (add 16 to color number to get flashing color. ex. 31=flashing white text)

Display graphic images ======================= CIRCLE used to draw a circle or ellipse. LINE used to draw a line or rectangle on the screen. PRESET set a pixel to the background color. PSET set a pixel to the foreground color. PAINT fill a graphic object on the screen with a color or a pattern. GET (Graphics) get the specified graphic rectangle and store in a file. PUT (Graphics) restore a graphic image (that was saved using GET). PCOPY used to copy contents of one screen page to another. PMAP used to map coordinates to logical or physical coordinates. POINT used to get the color of a pixel (or to get the pixel coordinates). DOS file system commands ========================= MKDIR directory$ makes a directory. CHDIR pathname$ changes directory. RMDIR directory$ deletes a directory. KILL file$ deletes a file (file$ can be "drive:\path\filename"). NAME oldfilename$ AS newfilename$ renames a file. File input/output ================= OPEN opens a file for input or output. CLOSE closes one or more files (opened by OPEN). GET (File I/O) reads a record from a random access file. PUT (File I/O) writes to a random access file (a record variable or buffer) WRITE writes data to sequential file. INPUT reads data from a sequential (or random) file. INPUT$ read (to a string) a sequence of characters from a file. LINE INPUT read all characters up to a <CR> from a sequential file.

EOF(file LOC returns the current position in a file (binary, random, or seq) LOF(file SEEK Function returns the current file pointer position. SEEK Statement sets the file pointer position for the next read or write. FILEATTR returns either the file mode (append etc.) or the DOS file handle. FREEFILE returns the next valid and unused file number. LOCK prevents access to all or specific portions of file by network process UNLOCK unlocks portions of a shared file for use by other network programs. Conversion functions for use with random access files ===================================================== MKI$(integer-expression%) MKI$, MKL$, MKS$, and MKD$ convert MKL$(long-integer-expression&) numbers to numeric strings that can be MKS$(single-precision-expression!) stored in FIELD statement string MKD$(double-precision-expression#) variables. CVI(2-byte-numeric-string) CVL(4-byte-numeric-string) CVI, CVL, CVS, and CVD CVS(4-byte-numeric-string) convert 'strings' back to numbers. CVD(8-byte-numeric-string) CVSMBF(4-byte-numeric-string) CVDMBF(8-byte-numeric-string) MKSMBF$(single) MKDMBF$(double) converts to IEEE format float (single). " " " " double(double). converts from IEEE format to string. " " " " " "

Memory Functions ================ CLEAR closes all files, inits. all variables and optionally sets stack size FRE returns the space available for strings, arrays or stack (""|-1|-2). PEEK(offset) returns the byte at the offset (in the current segment). POKE(offset,byte) place a byte in memory (within the current segment). BSAVE store a memory image of data or a program to a file (from current seg) BLOAD reload to memory data saved with BSAVE (to current segment). DEF SEG sets the segment value for subsequent PEEK, POKE, BLOAD, BSAVE VARSEG(variable) returns segment address of variable. VARPTR(variable) returns offset address of variable. Manipulate strings ================== ASC(s$) returns the numeric ascii code for first char. in string argument. CHR$(ascii_code) returns a one character string for the numeric argument. VAL(s$) returns the number value of a "string num representation". STR$(numeric_exp) returns a string representation (decimal) of the arg. HEX$(numeric_exp) " " " " (hexadecimal) " " . OCT$(numeric_exp) " " " " (octal) " " . LEN returns the number of char. in a string or bytes used by a variable. INSTR returns the position of the start of a string within a string. LEFT$(s$,n) returns n number of characters from the left of a string. RIGHT$(s$,n) returns n number of characters from the right of a string. MID$ Function returns a mid portion of a string at specified offset. MID$ Statement replaces a portion of a string with another string at offset. LSET left justifies a string. / also used with random access file buffers. RSET right justifies a string. \ and for converting variable record types. LTRIM$ removes the leading blank from a string(" hello" becomes "hello"). RTRIM$ removes the trailing blank from a string("hello " becomes "hello"). SPACE$(n) returns a string containing n space characters (an empty string). STRING$(n,ascii_value) similar to above but you can specify the fill char. UCASE$(s$) returns the string arg with all upper case lett.. LCASE$(s$) returns the string argument with all lower case letters. UCASE$(s$) returns the string argument with all upper case letters. Perform mathematical calculations (n can be a numeric expression)

================================= ABS(n) returns absolute value of n (ex. returns 5 for n = SGN(n) returns the sign of n (+1 if n is +ve, -1 if n is INT(n) returns the integer part of n (n=9.9 returns 9 n= FIX(n) returns the integer part of n (n=9.9 returns 9 n= SQR(n) returns the square root of n. LOG(n) returns x where e^x=n ie. the natural log of n. EXP(n) returns e to the power of n, exponential of n (the ATN(n) returns the COS(angle) returns SIN(angle) returns TAN(angle) returns CSNG(n) CDBL(n) CINT(n) CLNG(n) returns returns returns returns n n n n

5 or -ve, -9.9 -9.9

n = -5). 0 if n is = 0) returns -10). returns -9).

natural anti log).

angle (in radians) where n is the tangent of the angle. the cosine of angle (angle in radians). the sine of the angle (angle in radians). the tangent of the angle (angle in radians). as as as as a single precision value (number type conversion). a double precision value. an integer (uses rounding not truncating). an long integer (uses rounding not truncating).

RANDOMIZE initialise the random number generator (ex. RANDOMIZE TIMER). RND returns a single precision with a value between 0 and 0.99... (0 - <1). Set traps for events and errors =============================== ERDEV returns int error code from the last device that declared an error. ERDEV$ returns the name of the device that generated a critical error. ERL returns the line number before the one that generated an error. ERR returns the error code for the last error that occurred. ERROR simulates an error of the type specified (ex. ERROR 222). RESUME continue program execution from an error trapping handler. KEY (Event Trapping) enable/disable key event trapping for specified key. COM enables/disables data communication event trapping on specified port. PEN Statement enable/disable light pen event trapping PLAY{ON|OFF|STOP} enable/disable/pause play event trapping. STRIG Statement enable/disable joystick button event trapping. TIMER Statement enable/disable timer event trapping. ON ON ON ON ON ON ON KEY COM PEN PLAY STRIG TIMER TIMER Used to associate a subroutine with the specified event such as a key being pressed or when the specified number of seconds have passed. Note: these do not enable event trapping, the statements above are used to enable/disable event trapping. (go to 'error handler' on error condition)

ON ERROR GOTO Handler

Misc ==== REM Precedes a comment (you can also use <'>) KEY Statement assign a string to a function key. KEY Function display function key assignment. TIME$ Function returns a string containing the system time (as "hh:mm:ss"). TIME$ Statement used to set the system time (as "hh:mm:ss"). DATE$ Function returns a string containing the system date (as "mm-dd-yyyy"). DATE$ Statement used to set the system date (as "mm-dd-yyyy") TIMER Function returns the number of seconds since midnight. SLEEP(n) waits for n seconds (waits till key pressed if n=0 or n not given) VARPTR$(commandstring$) returns a string for use with the DRAW or PLAY func.

Anda mungkin juga menyukai