Repositories
The open-source compiler and IDEs behind MIDletPascal.
Overview
MIDletPascal is a small Pascal dialect that compiles straight to a runnable J2ME
.jar. This page is the complete language — its syntax, its types, and every one of
its built-in procedures and functions — checked line-for-line against the mp3cc
compiler that actually builds your code.
It turns a familiar-looking Pascal program into a J2ME MIDlet: you write .pas
source, the compiler translates it to Java bytecode and packs it into a .jar that
runs on any MIDP phone or emulator.
The language is deliberately small. It keeps the shape of Pascal — program,
begin/end, procedure, function, the usual control
flow — but drops much of the machinery of full Pascal so that the whole compiler and runtime
fit on a feature phone. Drawing, forms, sound, storage and networking are exposed as
built-in routines rather than library imports, so most programs need no
uses clause at all.
A few things to keep in mind before reading on:
- The language is case-insensitive for keywords and identifiers —
Begin, begin and BEGIN are the same.
- Drawing does not go to the screen directly. Graphics routines paint an off-screen
buffer; the buffer reaches the display only when you call
Repaint.
- Strings are a primitive type, not arrays of characters, and the first
character is at index 0.
- Every routine on this page was verified against the
mp3cc compiler.
Where the original 2005 manual and the compiler disagree, the compiler wins — the
unavailable badge marks the 4 documented routines this
build does not actually accept.
How a build works. The compiler emits M.class
(your program) plus any unit and record classes. Whenever your code calls into forms, real
numbers, storage, HTTP, sound or SMS, the compiler notes that a runtime helper class is
needed — FS, F/Real, RS, H,
P or SM. Those classes, and always FW.class, are added
to the JAR. The needs X badge on a
routine tells you which class it pulls in.
Program structure
A program is a header, an optional set of declarations, and a main body.
program programName;
{ constant declarations }
{ type declarations }
{ variable declarations }
{ procedure and function declarations }
begin
{ statements }
end.
The program header is optional in practice, but conventional. Declarations may
appear in any order and may be repeated. Execution starts at the main begin … end.
block — note the trailing period, which marks the end of the program.
Comments
Four comment styles are accepted. The first two are standard Pascal; the last two are
extensions of the mp3cc port:
{ curly-brace comment }
(* parenthesis-star comment *)
// line comment, to end of line (extension)
/* C-style block comment */ (extension)
No compiler directives. Unlike some Pascals, {$R+}
/{$V+}-style switches inside braces are ignored here. Real-number mode and canvas
type are chosen by the build, not by the source.
Data types
Ten built-in types, split into simple values and complex aggregates.
| Type | Kind | Description |
| boolean | simple | true or false. Operators: =, <>, and, or, xor, not. |
| char | simple | A single character. Comparable, and + concatenates two chars into a string. Use ord/chr to convert to and from the ASCII code. |
| integer | simple | 32-bit signed, roughly ±2,147,483,647. Operators include div, mod, shl, shr. |
| real | simple | Non-integer numbers, emulated in software (see Real numbers). Slower and larger than integers. |
| string | simple | A sequence of characters — a primitive, not an array. First char is at index 0. + appends a string, integer, char or boolean. |
| image | simple* | A bitmap, produced by LoadImage and the ImageFrom… functions. |
| command | simple* | A soft-key button, created with CreateCommand and read via GetClickedCommand. |
| recordStore | simple* | A handle to persistent storage (the RMS). See the Record Store routines. |
| http | simple* | An HTTP connection handle. See Http Connectivity. |
| resource | simple* | A read stream over a file bundled in the JAR. See Resource Files. |
| record | complex | A user-defined struct of named fields (below). |
| array | complex | A fixed, multi-dimensional array with explicit index ranges (below). |
* handle types: you receive and pass them around, but never inspect their internals.
record
A record groups several fields under one type. Access fields with .:
type heroType = record
positionX, positionY: integer;
health: integer;
end;
var hero: heroType;
begin
hero.positionX := hero.positionX + 1;
end.
Records cannot be copied whole. a := b; on two
record variables is rejected — assign field by field (a.x := b.x;). Arrays inside
records are also not supported.
array
Arrays are declared with explicit low/high bounds per dimension, and any number of dimensions:
type chessFieldType = array[1..8, 1..8] of integer;
var chessField: chessFieldType;
// or inline:
var field: array[1..15] of integer;
No bounds checking. Reading or writing outside the declared
range (e.g. a[7] in an array[1..5]) crashes the MIDlet at runtime.
You also cannot assign a value to a whole array — only to its elements.
Declarations
Constants, types and variables are introduced with const,
type and var blocks.
const
minutesInHour = 60;
famousQuote = 'To be or not to be';
type
number = integer;
point = record x, y: integer; end;
var
index: integer;
field: array[1..15] of integer;
p: point;
A const binds a fixed value to a name. A type block names new types —
aliases, records or arrays. A var block declares variables, which may use a named
type or an inline type. Variables declared at program level are global and visible inside every
procedure and function.
Statements
Assignment, procedure calls, and a compact set of control-flow constructs.
Where a construct takes a body, a single statement needs no begin/end;
several statements do.
Assignment
variable := expression;
for … to / downto … do
for i := 1 to 10 do
begin
sum := sum + i;
end;
for i := 10 downto 1 do drawText(integerToString(i), 0, i*10);
while … do
while (getKeyClicked = KE_NONE) do
delay(100);
repeat … until (and the forever extension)
repeat
delay(100);
until (getKeyClicked <> KE_NONE);
repeat
tick;
forever; { mp3cc extension: an intentional infinite loop }
if … then … else
if condition then
begin
{ runs when condition is true }
end
else
begin
{ runs when condition is false }
end;
The else branch is optional.
break
Exits the innermost for, while or repeat loop. Using
break outside a loop is a compile error.
repeat
for i := 1 to 10 do
if doSomething(i) = -1 then break; { leaves the for loop }
until getClickedCommand <> emptyCommand;
Not supported. The case … of statement, the
with statement, sets, files and enumerated types are all recognised by the parser
only so it can reject them with a clear error. There is no case in MIDletPascal —
use a chain of if … else if instead.
Procedures & functions
A procedure returns nothing; a function returns a value by assigning to its own
name (or to result).
procedure twoArgs(a: integer; b: string);
var len: integer; { local — re-created on every call }
begin
len := length(b);
n := a + len; { n is a global }
end;
function multiply(a, b: integer): integer;
begin
multiply := a * b; { classic Pascal: assign to the function name }
end;
function square(x: integer): integer;
begin
result := x * x; { mp3cc extension: the result keyword }
end;
Recursion
Functions and procedures may call themselves.
function factorial(n: integer): integer;
begin
if n = 1 then
factorial := 1
else
factorial := n * factorial(n - 1);
end;
forward declarations
If two routines call each other, declare one forward so it is visible before its
body appears:
procedure b(y: integer); forward;
procedure a(x: integer);
begin b(x); end;
procedure b(y: integer);
begin a(y); end;
Differences from standard Pascal.
- Procedures and functions cannot be nested — one may not be declared inside another.
- No
var parameters. Every parameter is passed by value; a var keyword in a parameter list is ignored with a warning.
- The
exit keyword (an extension) returns early from a routine — or acts like Halt in the main block.
Units & libraries
Split a program across files with units, or reach into raw MIDP API that
MIDletPascal doesn't wrap by writing a library unit in Java.
Pascal units
A unit is compiled separately and pulled in with uses:
uses mymath, ui;
// resolve a name defined in two units:
mymath.square(5);
A MIDletPascal unit has the familiar unit / interface /
implementation shape. The initialization section runs at startup;
a finalization section is not supported. Unit names must be at least
two characters.
Library units (Java)
When you need a MIDP API call that the language does not expose, write a library
unit in Java. It compiles to a Lib_<name>.class that the compiler
reads directly, so you can call Java from Pascal.
Rules for a library unit.
- The class must not be in any package, and the name must be
Lib_
followed by an all-lowercase name (Java is case-sensitive — Pascal is not).
- Every exported member must be
public static.
- Parameters and return values may only be: int
String Image
Command RecordStore
InputStream (and
void return). Anything else is rejected.
- Library units hold functions and procedures only — no types, no variables.
- The compiled class goes in the global
Libs directory (or the project's own
library directory, which is searched first).
// Lib_mylib.java — compiled & preverified with the WTK, then dropped in Libs/
public class Lib_mylib {
public static int square(int val) {
return val * val;
}
}
uses mylib;
var idx: integer;
begin
showForm;
idx := formAddString('5 squared is: ' + mylib.square(5));
delay(5000);
end.
To reach the current Display (for vibrate, backlight, and the like) a library unit
can also ship its own FW.java that exposes the live MIDlet object — see the
original manual's Advanced features chapter. Always wrap MIDP 2.0-only calls in a
try/catch so MIDP 1.0 phones don't crash.
Operators
Arithmetic, comparison, boolean and bitwise operators, plus a couple of
mp3cc additions.
| Group | Operators | Notes |
| Arithmetic | + - * / | On integers, / is the same as div (integer division). |
| Integer division | div mod | mod is the remainder of integer division. |
| Comparison | = <> < > <= >= | String comparison with =/<> is case-sensitive. |
| Boolean | and or xor not | not binds tightest; =, <, > bind loosest. |
| Bitwise shift | shl shr ushr | Also written <<, >>, >>>. ushr is an unsigned right shift (extension). |
| Concatenation | + | A string + a string / integer / char / boolean yields a string. |
| String / char index | [ ] | Index a string with an integer (0-based) — see GetChar. |
Literals. Integers may be written in hex with a leading
$ ($FF00). Characters can be given by code with #
(#65 or #$41). Strings use single quotes; a doubled quote
('') is an embedded quote. The port also accepts C-style double-quoted strings.
Real numbers
Phones have no floating-point unit, so real arithmetic is emulated —
it is slow and inflates the JAR. Two implementations are available, chosen by the build, not the source.
Fixed-point · F.class · default
Fast and compact. Low precision (a fixed number of
fractional bits). Selected with mp3cc -m1. Pulls in F.class.
Floating-point · Real.class
Much more precise, but slower and adds several KB to the
JAR. Selected with mp3cc -m2. Pulls in Real.class and
Real$NumberFormat.class.
Roughly twenty math routines (see the Math category) plus the
predefined constant pi operate on reals. Any routine that touches a real value is
marked needs F / Real.
Compiler extensions
The mp3cc port (MIDletPascal 3.5) adds a handful of features on top
of the original 3.x language.
- Inline bytecode. A
bytecode … end block (or the deprecated
inline(…)) lets you write raw JVM opcodes, with labels, straight into a routine —
an escape hatch for hand-tuned code.
exit and result. exit returns early from a
routine (or halts in the main block); result is an alias for the function's return value.
forever. Terminates a repeat loop as an explicit infinite loop.
ushr / >>>. Unsigned right shift.
- Extra literal & comment syntax. C-style
// and /* */
comments, $ hex integers, # character codes, and double-quoted strings.
A silent build failure to know about. If the compiler process
is killed (a bad argument, or a binary that doesn't match the device), it can exit without
producing M.class. A JAR that contains only FW.class is not a working
build — a real toolchain checks that M.class exists and that the exit code is the
compiler's own error count.
Built-in routines
Function & procedure reference
Every built-in routine, grouped by area. Each card shows the signature the
compiler accepts, which runtime class it needs, and — where the manual provided one — an
example. Use the search box to filter by name.
No routine matches .
◧
Drawing
31
procedure DrawArc(x, y, width, height, startAngle, arcAngle: integer);
Draws the arc covering the specified rectangle. The arc starts at 'startAngle' and extends for 'arcAngle' degrees. The angle of 0° degrees is at 3 o'clock position. The angle of 90° is at 12 o'clock position.
Example
begin
DrawArc(0, 0, GetWidth, GetHeight, 0, 90);
Repaint;
Delay(1000);
end.
procedureDrawEllipse
Drawing
procedure DrawEllipse(x, y, width, height: integer);
Draws the outline of an ellipse covering the specified rectangle.
Example
begin
DrawEllipse(0, 0, GetWidth, GetHeight);
Repaint;
Delay(1000);
end.
procedureDrawImage
Drawing
procedure DrawImage(img: image; x, y: integer);
Draws the image to the display buffer. The 'x' and 'y' coordinates are the coordinates where the upper left corner of the image will be placed.
Example
begin
DrawImage(LoadImage('/logo.png'), 0, 0);
Repaint;
Delay(1000);
end.
procedureDrawLine
Drawing
procedure DrawLine(x1, y1, x2, y2: integer);
Draws the line between the point ('x1', 'y1') and the point ('x2', 'y2').
Example
begin
DrawLine(10, 15, 25, 35);
Repaint;
Delay(1000);
end.
procedureDrawRect
Drawing
procedure DrawRect(x, y, width, height: integer);
Draws the outline of the specified rectangle.
Example
begin
DrawRect(5, 5, 20, 20);
Repaint;
Delay(1000);
end.
procedureDrawRoundRect
Drawing
procedure DrawRoundRect(x, y, width, height, arcWidth, arcHeight: integer);
Draws the outline of the specified rounded corner rectangle.
Example
begin
DrawRoundRect(5, 5, 20, 20, 2, 2);
Repaint;
Delay(1000);
end.
procedureDrawText
Drawing
procedure DrawText(text: string, xPos, yPos: integer);
Draws the text 'text' to the display buffer. The 'xPos' and 'yPos' are coordinates of the upper left corner of the text-bounding box.
Example
begin
SetColor(255, 0, 0);
DrawText('Hello world', 0, 0);
Repaint;
Delay(1000);
end.
procedureFillEllipse
Drawing
procedure FillEllipse(x, y, width, height: integer);
Fills the ellipse covering the specified rectangle.
Example
begin
FillEllipse(0, 0, GetWidth, GetHeight);
Repaint;
Delay(1000);
end.
procedureFillRect
Drawing
procedure FillRect(x, y, width, height: integer);
Fills the specified rectangle.
Example
begin
FillRect(5, 5, 20, 20);
Repaint;
Delay(1000);
end.
procedureFillRoundRect
Drawing
procedure FillRoundRect(x, y, width, height, arcWidth, arcHeight: integer);
Fills the specified rounded corner rectangle.
Example
begin
FillRoundRect(5, 5, 20, 20, 2, 2);
Repaint;
Delay(1000);
end.
functionGetColorBlue
Drawing
function GetColorBlue: integer;
Returns the blue component value of the current color. function GetColorBlue: integer;
Example
begin
SetColor(0, 0, 127);
if GetColorBlue <> 127 then
begin
DrawText('This should never happen', 0, 0);
Repaint;
end;
Delay(1000);
end.
functionGetColorGreen
Drawing
function GetColorGreen: integer;
Returns the green component value of the current color. function GetColorGreen: integer;
Example
begin
SetColor(0, 127, 0);
if GetColorGreen <> 0 then
begin
DrawText('This should never happen', 0, 0);
Repaint;
end;
Delay(1000);
end.
functionGetColorRed
Drawing
function GetColorRed: integer;
Returns the red component value of the current color. function GetColorRed: integer;
Example
begin
SetColor(127, 0, 0);
if GetColorRed <> 127 then
begin
DrawText('This should never happen', 0, 0);
Repaint;
end;
Delay(1000);
end.
functionGetColorsNum
Drawing
function GetColorsNum:integer;
Returns the number of different colors that the device display can show. function GetColorsNum:integer;
functionGetHeight
Drawing
function GetHeight: integer;
Returns the height (in pixels) of the display area. function GetHeight: integer;
Example
begin
DrawEllipse(0, 0, GetWidth, GetHeight);
Repaint;
Delay(1000);
end.
functionGetImageHeight
Drawing
function GetImageHeight(img: image): integer;
Returns the height of the given image in pixels.
functionGetImageWidth
Drawing
function getImageWidth(img: image): integer;
Returns the width of the given image in pixels.
Example
begin
DrawEllipse(0, 0, GetWidth, GetHeight);
Repaint;
Delay(1000);
end.
functionGetStringHeight
Drawing
function GetStringHeight(text: string): integer;
Returns the height (in pixels) for showing the 'text' on display in the current font.
Example
var text: string;
height: integer;
begin
text := 'Text to display';
height := GetStringHeight(text);
DrawText(text, 0, (GetHeight - height)/2);
Repaint;
Delay(1000);
end.
functionGetStringWidth
Drawing
function GetStringWidth(text: string): integer;
Returns the width (in pixels) for showing the 'text' on display in the current font.
Example
var text: string;
width: integer;
begin
text := 'Text to display';
width := GetStringWidth(text);
DrawText(text, (GetWidth - width)/2, 0);
Repaint;
Delay(1000);
end.
function GetWidth: integer;
Returns the width (in pixels) of the display area. function GetWidth: integer;
Example
begin
DrawEllipse(0, 0, GetWidth, GetHeight);
Repaint;
Delay(1000);
end.
functionImageFromBuffer
Drawingneeds S
function ImageFromBuffer(buffer: string; length: integer): image;
Decodes an image (PNG/JPEG) held in a string buffer — for example one read from a resource or received over HTTP — into an image value. Undocumented in the original manual but present in the compiler.
functionImageFromCanvas
Drawingneeds S
function ImageFromCanvas(x: integer; y: integer; width: integer; height: integer ): image ;
Creates the image from the part of the drawing canvas.
functionImageFromImage
Drawingneeds S
function ImageFromImage(sourceImg: image; x: integer; y: integer; width: integer; height: integer ): image ;
Creates the image from the part of another image.
functionIsColorDisplay
Drawing
function IsColorDisplay:boolean;
Returns true if the device display can show colors; otherwise returns false. function IsColorDisplay:boolean;
functionLoadImage
Drawing
function LoadImage(resource: string): image
Loads the image from the resource and returns an 'image' object. To access the file inside the JAR archive (the file added as a resource into the MIDletPascal project), the 'resource' parameter must begin with '/' character. If the resource name is invalid, the application will fail.
Example
begin
DrawImage(LoadImage('/icon.png'), 0, 0);
Repaint;
Delay(1000); { wait 1 second before the MIDlet terminates }
end.
procedure Plot(x, y:integer);
Sets the color of a single pixel to the current color.
Example
begin
SetColor(255, 0, 0);
Plot(5, 10);
Repaint;
Delay(1000);
end.
procedure Repaint;
Repaints the device display. All drawing functions (such as drawLine, drawText, fillRect etc.) do not draw directly to the device display. The drawing functions draw to the off-screen buffer, and the procedure 'repaint' copies the off-screen buffer to the device display. The repainting is a time-consuming procedure so it should be called as rarely as possible. procedure Repaint;
Example
begin
DrawText('Hello world', 0, 0);
Repaint;
Delay(1000);
end.
procedure SetClip(int x, int y, int width, int height);
Sets the clipping area for the subsequent drawing operations. All drawing operations which take place outside of the clipping area rectangle will be ommited.
Example
begin
// draw the ellipse
SetColor(0, 0, 0);
FillEllipse(0, 0, GetWidth, GetHeight);
Repaint;
Delay(2000);
// draw ellipse again with setClip called before
SetClip(10, 10, 15, 25);
FillEllipse(0, 0, GetWidth, GetHeight);
Repaint;
Delay(2000);
end.
procedureSetColor
Drawing
procedure SetColor(red, green, blue:integer);
Set the color to be used for drawing all the subsequent graphical elements. The 'red', 'green' and 'blue' components can take values between 0 and 255. For example, the black color representation is (0, 0, 0), bright red is (255, 0, 0), and white is (255, 255, 255).
Example
begin
SetColor(0, 0, 255); { set the color to bright blue }
DrawText('Hello world', 0, 0);
Repaint;
Delay(1000);
end.
procedureSetDefaultFont
Drawing
procedure SetDefaultFont;
Sets the current font to the default font used on the device. Note that some devices use only one font, so calling setDefaultFont will have no effect on those devices. procedure SetDefaultFont;
procedure SetFont(fontFace, fontStyle, fontSize);
Sets the font to be used for displaying text. The 'fontFace' can be any of the following predefined constants:
- FONT_FACE_SYSTEM
- FONT_FACE_MONOSPACE
- FONT_FACE_PROPORTIONAL
The 'fontStyle' can be any of the following predefined constants:
- FONT_STYLE_PLAIN
- FONT_STYLE_BOLD
- FONT_STYLE_ITALIC
- FONT_STYLE_UNDERLINE
These styles may be combined together using the logical operator or. For exaple, to create the font that is bold and underlined, use (FONT_STYLE_BOLD or FONT_STYLE_UNDERLINE) as the value for the font style. The font size can be any of the following predefined constants:
- FONT_SIZE_SMALL
- FONT_SIZE_MEDIUM
- FONT_SIZE_LARGE
Note that some devices use only one font, so calling setFont will have no effect on those devices.
Example
begin
SetFont(FONT_FACE_SYSTEM,
FONT_STYLE_BOLD or FONT_STYLE_UNDERLINE,
FONT_SIZE_LARGE);
DrawText('Hello world', 0, 0);
Repaint;
Delay(1000);
end.
⌨
Keypad Access
3
functionGetKeyClicked
Keypad Access
function GetKeyClicked: integer;
Returns the code of the last clicked key on the keypad, or KE_NONE if no key is pressed. The standard key codes have predefined constant values:
- KE_KEY0
- KE_KEY1
- KE_KEY2
- KE_KEY3
- KE_KEY4
- KE_KEY5
- KE_KEY6
- KE_KEY7
- KE_KEY8
- KE_KEY9
- KE_STAR
- KE_POUND
function GetKeyClicked: integer;
Example
begin
while GetKeyClicked <> KE_STAR do
begin
Delay(100);
end;
end.
functionGetKeyPressed
Keypad Access
function GetKeyPressed: integer;
Returns the code of the key that is currently pressed, or KE_NONE if no key is pressed. The standard key codes have predefined constant values:
- KE_KEY0
- KE_KEY1
- KE_KEY2
- KE_KEY3
- KE_KEY4
- KE_KEY5
- KE_KEY6
- KE_KEY7
- KE_KEY8
- KE_KEY9
- KE_STAR
- KE_POUND
function GetKeyPressed: integer;
Example
begin
while GetKeyPressed <> KE_STAR do
begin
Delay(100);
end;
end.
functionKeyToAction
Keypad Access
function KeyToAction(keyCode: integer): integer;
getKeyClicked and getKeyPressed functions return the key code of the key pressed. However, different devices have different key mappings. For example, one device may have FIRE key return key code 100, and the other device may have its FIRE key return key code 120. To avoid this problem, you can use the keyToAction function that translates the key code into mapped game actions. keyToAction can return any of the following predefined values:
- GA_NONE
- GA_UP
- GA_DOWN
- GA_LEFT
- GA_RIGHT
- GA_FIRE
- GA_GAMEA
- GA_GAMEB
- GA_GAMEC
- GA_GAMED
Example
begin
while KeyToAction(getKeyClicked) <> GA_FIRE do
begin
Delay(100);
end;
end.
◷
Date and Time
11
procedureDelay
Date and Time
procedure Delay(millis: integer);
Suspends the execution of a program for the given time in milliseconds. To display a message on to the screen, wait 2 seconds, and then close MIDlet, use the following code:
Example
begin
DrawText('Hello world', 0, 0);
Repaint;
Delay(2000);
end.
functionGetCurrentTime
Date and Time
function GetCurrentTime: integer;
Returns the current time in seconds since midnight 1.1.1970. The returned value (the number of seconds) can be used as argument to call functions such as GetMonth or GetHour. function GetCurrentTime: integer;
Example
var time: integer;
text: string;
begin
time := GetCurrentTime;
text := 'Current time is ' + GetHour(time);
text := text + ':'+ GetMinute(time);
text := text + ':' + GetSecond(time);
DrawText(text, 0, 0);
Repaint;
Delay(1000); { wait 1 second before MIDlet terminates }
end.
functionGetDay
Date and Time
function GetDay(time: integer): integer;
Returns the day in the month for the given time (time is represented in seconds since 1.1.1970. and can be retrieved by calling GetCurrentTime function). The returned value is between 1 and 31.
functionGetHour
Date and Time
function GetHour(time: integer): integer;
Returns the hour for the given time (time is represented in seconds since midnight 1.1.1970 and can be retrieved by calling GetCurrentTime function). The returned value is between 0 and 23.
Example
var time: integer;
text: string;
begin
time := GetCurrentTime;
text := 'Current time is ' + GetHour(time);
text := text + ':' + GetMinute(time);
text := text + ':' + GetSecond(time);
DrawText(text, 0, 0);
Repaint;
Delay(1000); { wait 1 second before MIDlet terminates }
end.
functionGetMinute
Date and Time
function GetMinute(time: integer): integer;
Returns the minute for the given time (time is represented in seconds since midnight 1.1.1970 and can be retrieved by calling GetCurrentTime function). The returned value is between 0 and 59.
Example
var time: integer;
text: string;
begin
time := GetCurrentTime;
text := 'Current time is ' + GetHour(time);
text := text + ':' + GetMinute(time);
text := text + ':' + GetSecond(time);
DrawText(text, 0, 0);
Repaint;
Delay(1000); { wait 1 second before MIDlet terminates }
end.
functionGetMonth
Date and Time
function GetMonth(time: integer): integer;
Returns the month number for the given time (time is represented in seconds since 1.1.1970. and can be retrieved by calling GetCurrentTime function). The returned value is between 1 and 12.
functionGetRelativeTimeMs
Date and Time
function GetRelativeTimeMs: integer;
Return the current time in milliseconds. Note that the return value is 32-bit integer that can represent only 2^32 milliseconds, which is a little bit over 48 days. So every 48 days, this value is reset and starts counting from 0. Do not use this function to determine the current date, but it can be used for implementing timers in an application. Consider a simple game (such as Tetris, for example) that needs to move the block down each second. Also, the game should move the block left or right when the user presses the left/right key on the keypad. The main program loop could be implemented as follows: function GetRelativeTimeMs: integer;
Example
...
lastSavedTime := GetRelativeTimeMs; { initialize the timer }
repeat
{ read and process the keypad input }
key := GetKeyClicked;
if KeyToAction(key) = GA_LEFT then moveLeft;
if KeyToAction(key) = GA_RIGHT then moveRight;
{ check if 1 second has passed }
if ((GetRelativeTimeMs - lastSavedTime) > 1000)
or (GetRelativeTimeMs < lastSavedTime) { check if the timer is reset after 48 days }
then
begin
lastSavedTime := GetRelativeTimeMs;
moveDown;
end;
until gameOver;
...
functionGetSecond
Date and Time
function GetSecond(time: integer): integer;
Returns the second for the given time (time is represented in seconds since midnight 1.1.1970 and can be retrieved by calling GetCurrentTime function). The returned value is between 0 and 59.
Example
var time: integer;
text: string;
begin
time := GetCurrentTime;
text := 'Current time is ' + GetHour(time);
text := text + ':' + GetMinute(time);
text := text + ':' + GetSecond(time);
DrawText(text, 0, 0);
Repaint;
Delay(1000); { wait 1 second before MIDlet terminates }
end.
functionGetWeekDay
Date and Time
function GetWeekDay(time: integer): integer;
Returns the day in week for the given time (time is represented in seconds since 1.1.1970. and can be retrieved by calling GetCurrentTime function). Returned value is 1 for Sunday, 2 for Monday, etc (7 is Saturday).
functionGetYear
Date and Time
function GetYear(time: integer): integer;
Returns the year for the given time (time is represented in seconds since 1.1.1970. and can be retrieved by calling GetCurrentTime function).
functionGetYearDay
Date and Time
function GetYearDay(time: integer): integer;
Returns the day in year for the given time (time is represented in seconds since midnight 1.1.1970. and can be retrieved by calling GetCurrentTime function). Returned value is between 1 and 366.
∑
Math
19
function Abs(n: integer): integer;
Returns the absolute value of the given number.
functionAcos
Mathneeds F / Real
function Acos(num: real):real;
Returns the arc cosine of a number, in the range 0 to pi (in radians).
functionAsin
Mathneeds F / Real
function Asin(num: real):real;
Returns the arc sine of a number, in the range -pi/2 to the pi/2 (in radians).
functionAtan
Mathneeds F / Real
function Atan(num: real):real;
Returns the arc tangent, in the range from -pi/2 to pi/2 (represented in radians).
functionAtan2
Mathneeds F / Real
function Atan2(y,x: real):real;
Converts the rectangular coordinates (x,y) into polar coordinates (r, theta). This method computes the phase theta by computing an arc tangent of y/x in the range of -pi to pi.
functionCos
Mathneeds F / Real
function Cos(num: real):real;
Returns the cosine of the given number (represented in radians).
functionExp
Mathneeds F / Real
function Exp(num: real):real;
Returns the Euler's number 'e' raised to the value of 'num'.
functionFrac
Mathneeds F / Real
function Frac(num: real):real;
Returns the fraction of a number (the fraction of 1.234 is 0.234).
functionLog
Mathneeds F / Real
function Log(num: real):real;
Returns the natural logarithm of the given number.
functionLog10
Mathneeds F / Real
function Log10(num: real):real;
Returns the logarithm base 10 of the given number.
functionPow
Mathneeds F / Real
function Pow(a, b: real):real;
Returns the value of 'a' raised to the power of 'b'.
functionRabs
Mathneeds F / Real
function Rabs(num:real):real;
Returns the absolute value of the real number.
functionSin
Mathneeds F / Real
function Sin(num: real):real;
Returns the sine of the given number (represented in radians).
function Sqr(n: integer): integer;
Returns the square of the given number.
functionSqrt
Mathneeds F / Real
function Sqrt(num: real):real;
Returns the square root of the given number.
functionTan
Mathneeds F / Real
function Tan(num: real):real;
Returns the tangent of an angle represented in radians.
functionToDegrees
Mathneeds F / Real
function ToDegrees(num: real):real;
Converts the angle from radians into degrees.
functionToRadians
Mathneeds F / Real
function ToRadians(num: real):real;
Converts the angle from degrees into radians.
functionTrunc
Mathneeds F / Real
function Trunc(num: real):integer;
Truncates the real number and returns only the integer part.
“”
String
10
function Copy(str1: string; begin, end: integer): string;
The function returns the substring of the given string which starts at position 'begin' and ends at position 'end'-1. For example, copy('MIDletPascal', 2, 5) returns 'Dle'. Note that this is different from the classic Pascal function copy. Strings in MIDletPascal are slightly different than strings in regular Pascal: the index of the first character in string is 0 in MIDletPascal.
functionGetChar
Stringneeds S
function GetChar(str: string; pos:integer): char;
Returns the character at a given index within the string. The first character in a string is at index 0. If 'pos' is larger than the length of the string, character with ASCII code '0' is returned.
functionIntegerToString
String
function IntegerToString(val: integer): string;
Converts integer into string representation of the same number.
Example
var i: integer;
s: string;
begin
i := 15;
s := IntegerToString(i);
s := '' + i; // this has the same effect as the previous statement
end.
function Length(str: string): integer;
Retuns the length of the given string. Strings in MIDletPascal are slightly different than strings in regular Pascal: the index of the first character in string is 0 in MIDletPascal.
function Locase(str: string): string;
Returns the copy of the 'str' string with all letters in lowercase.
function Pos(str1, str2: string): integer;
Returns the position of the first occurence of 'str2' in 'str1', or -1 if 'str2' does not occur in 'str1'. The comparison is case-sensitive.
functionSetChar
Stringneeds S
function SetChar(str: string; c: char; pos:integer): string;
Returns the string that is identical to 'str' except that it has character 'c' at position 'pos'. Position indexes start with zero. If 'pos' is larger then the length of the 'str', a copy of 'str' is returned.
functionStringToInteger
Stringneeds S
function StringToInteger(s:string):integer;
Transforms the string into an integer (base 10 is used). If the string 's' is not a valid integer, the function will return 0. The string 's' may contain only digits, except for the first character which may be a '+' or a '-' sign.
functionStringToReal
Stringneeds F / Real
function StringToReal(str:string; base:integer):real;
Transforms the string into the real number. The second parameter is the base for transformation.
function Upcase(str: string): string;
Returns the copy of the 'str' string with all letters capitalized.
▦
Record Store
13
functionAddRecordStoreEntry
Record Storeneeds RS
function AddRecordStoreEntry(rs: recordStore; data: string): integer;
The function adds 'data' into the record store 'rs'. The function returns the index inside record store at which 'data' is stored, or -1 if an error occured.
procedureCloseRecordStore
Record Storeneeds RS
procedure CloseRecordStore(rs: recordStore);
Closes an open record store.
procedureCloseRSEnumeration
unavailableRecord Store
procedure CloseRSEnumeration(rsEnumIdx: integer);
Not in this compiler build. Documented for MIDletPascal 3.5 but NOT compiled into this mp3cc build — the record-store enumeration API is absent from the parser. Iterate records by index with GetRecordStoreSize / ReadRecordStoreEntry instead.
Closes the record store enumeration created internally by calling EnumerateRecords. This procedure MUST be called when record store enumeration is no longer needeed; otherwise all phone resources will be reserved and record store will not be able to create enumerations any more.
procedureDeleteRecordStore
Record Storeneeds RS
procedure DeleteRecordStore(name: string);
Deletes the record store identified by its name. All data stored inside the record store will be lost. If the record store with the given name does not exist, nothing is deleted.
procedureDeleteRecordStoreEntry
Record Storeneeds RS
procedure DeleteRecordStoreEntry(rs: recordStore; index: integer);
Deletes the entry located at index 'index' inside the 'rs' recordStore. The procedure will do nothing if nothing exists at the given index.
procedureEnumerateRecords
unavailableRecord Store
function EnumerateRecords(rs: recordStore): integer;
Not in this compiler build. Documented for MIDletPascal 3.5 but NOT compiled into this mp3cc build — the record-store enumeration API is absent from the parser. Iterate records by index with GetRecordStoreSize / ReadRecordStoreEntry instead.
The function enumerates all nonempty records in the record store so that they can be iterated without reading the empty records. The function returns the index of the internal record store enumeration object that is used to access the enumerated data. The function will return -1 if enumeration failed.
Example
uses RSEnum;
var rs: recordStore;
entryIdx: integer;
rsEnumIdx: integer;
data: string;
begin
rs := OpenRecordStore('Test record store');
entryIdx := AddRecordStoreEntry(rs, 'First Entry');
entryIdx := AddRecordStoreEntry(rs, 'Second Entry');
entryIdx := AddRecordStoreEntry(rs, 'Third entry');
rsEnumIdx := EnumerateRecords(rs);
repeat
data := NextRecord(rsEnumIdx);
debug(data);
until data = '';
DeleteRecordStoreEntry(rs, 2);
UpdateRSEnumeration(rsEnumIdx);
repeat
data := NextRecord(rsEnumIdx);
debug(data);
until data = '';
CloseRSEnumeration(rsEnumIdx);
end.
functionGetRecordStoreNextId
Record Storeneeds RS
function GetRecordStoreNextId(rs: recordStore): integer;
Returns the entry index that will be given to the next record store entry created with 'AddRecordStoreEntry' function.
functionGetRecordStoreSize
Record Storeneeds RS
function GetRecordStoreSize(rs: recordStore): integer;
Returns the number of records in the record store.
procedureModifyRecordStoreEntry
Record Storeneeds RS
procedure GetRecordStoreSize(rs: recordStore; newData: string; index: integer);
Modifies existing record store entry identified by 'index'. The value of the record store entry is set to 'newData'.
procedureNextRecord
unavailableRecord Store
function NextRecord(rsEnumIdx: integer): string;
Not in this compiler build. Documented for MIDletPascal 3.5 but NOT compiled into this mp3cc build — the record-store enumeration API is absent from the parser. Iterate records by index with GetRecordStoreSize / ReadRecordStoreEntry instead.
Returns the next record from the record store enumeration. If there are no more records in the enumeration, returns an empty string.
functionOpenRecordStore
Record Storeneeds RS
function OpenRecordStore(name: string): recordStore;
Open the record store with the name 'name'. If the record store does not exist, an empty record store is created.
functionReadRecordStoreEntry
Record Storeneeds RS
function ReadRecordStoreEntry(rs: recordStore; index: integer): string;
Returns the data stored at index 'index' inside record store 'rs', or an empty string if nothing exists at the given index.
procedureUpdateRSEumeration
unavailableRecord Store
procedure UpdateRSEnumeration(rsEnumIdx: integer);
Not in this compiler build. Documented for MIDletPascal 3.5 but NOT compiled into this mp3cc build — the record-store enumeration API is absent from the parser. Iterate records by index with GetRecordStoreSize / ReadRecordStoreEntry instead.
Updates the record store enumeration so that it reflects the most recent state of the record store.
⇄
Http Connectivity
9
procedureAddHttpBody
Http Connectivityneeds H
procedure AddHttpBody(httpConn: http; data: string);
Appends 'data' to the http request message body. Only POST request may contain a non-empty body.
procedureCloseHttp
Http Connectivityneeds H
procedure CloseHttp(httpConn: http);
Closes an open http connection.
functionGetHttpResponse
Http Connectivityneeds H
function GetHttpResponse(httpConn: http):string;
Returns the data that has been sent by the server in a response to http request.
functionIsHttpOpen
Http Connectivity
function IsHttpOpen(httpConn: http):boolean;
Returns true if the 'httpConn' connection is already open.
functionOpenHttp
Http Connectivityneeds H
function OpenHttp(httpConn: http; url: string):boolean;
Opens the 'httpConn' connection to the 'url'. The 'url' must be in form 'http://servername[:port][/file]'. Returns true on success, or false if fails.
functionSendHttpMessage
Http Connectivityneeds H
function SendHttpMessage(httpConn: http): integer;
This function send the http request, waits for the response and returns http response code or -1 if an internal error occured. The complete list of HTTP response codes can be found on the Internet (generally, 200 means OK, codes between 400-499 denote client-side errors, and codes between 500-599 denote server-side errors).
procedureSetHttpMethod
Http Connectivityneeds H
procedure SetHttpMethod(httpConn: http; method:string);
Sets the method for the http request. The method can be any of the following:
✉
SMS Messaging
3
functionSmsIsSending
SMS Messagingneeds SM
function SmsIsSending: boolean;
Returns true if SMS subsystem is busy sending an SMS message, or false otherwise. function SmsIsSending: boolean;
functionSmsStartSend
SMS Messagingneeds SM
function SmsStartSend(destination: string; message:string): boolean;
Starts sending an SMS message. Returns true if SMS message has been sent to the SMS subsystem and if the subsystem is not sending another message. Returns false if the message was not sent to the SMS subsystem. 'destination' address must have the form: sms://<phone-number> SMS sending from J2ME is not supported on all devices. MIDletPascal tries to send SMS messages using Wireless Messaging API and Siemens API. The following example illustrates simple use of SMS functions:
Example
begin
if not SmsStartSend('sms://+5550000', 'Hello!') then Halt;
while SmsIsSending do // wait for the message to be sent
Delay(100);
if not SmsWasSuccessfull then Halt; // check if the message was sent //successfully
end.
functionSmsWasSuccessfull
SMS Messagingneeds SM
function SmsWasSuccessfull: boolean;
Returns true if the last SMS message was sent successfully. This function returning false can mean any of the following:
- the mobile phone does not support sending SMS messages from J2ME MIDlet
- the SMS destination address is invalid
- the operator refused to relay an SMS message
function SmsWasSuccessfull: boolean;
♪
Sound and Music
6
functionGetPlayerDuration
Sound and Musicneeds PMMAPI or MIDP2.0
function GetPlayerDuration:integer;
Returns the total duration (in milliseconds) of the music that was loaded into player. function GetPlayerDuration:integer;
functionOpenPlayer
Sound and Musicneeds PMMAPI or MIDP2.0
function OpenPlayer(resource:string; mimetype:string):boolean;
Opens a given resource file in the audio player. The resource is not played before 'startPlayer' is called. The function will return false if it did not succedd. 'mimetype' can be any of the following:
- wave files: audio/x-wav
- au files: audio/basic
- MP3 files: audio/mpeg
- MIDI files: audio/midi
Note that devices usually do not support all sound formats. Compatibility: the music functions will work only on MIDP-2.0 compatible mobile phones. MIDlets with sound support will CRASH on MIDP-1.0 phones!
Example
begin
if not OpenPlayer('/explosion.mid', 'audio/midi') then Halt;
if not SetPlayerCount(-1) then Halt;
if not StartPlayer then Halt;
Delay(5000);
end.
procedurePlayTone
Sound and MusicMMAPI or MIDP2.0
procedure PlayTone(note, duration, volume: integer);
Plays a single tone through the Mobile Media API. 'note' is the MIDI note number (0..127, 69 = A4 = 440 Hz), 'duration' is the length in milliseconds and 'volume' is 0..100. Undocumented in the original manual but present in the compiler.
functionSetPlayerCount
Sound and Musicneeds PMMAPI or MIDP2.0
function SetPlayerCount(loopCount:integer):boolean;
Sets the loop count for the player - the 'loopCount' is the number of times that the music should be played. This function should be called after 'openPlayer' and before 'startPlayer' is called. If 'loopCount' is set to -1, then the music will play forever.
functionStartPlayer
Sound and Musicneeds PMMAPI or MIDP2.0
function StartPlayer:boolean;
Starts playing the audio previously loaded by 'openPlayer'. Returns false if the player cannot be started. function StartPlayer:boolean;
Example
begin
if not OpenPlayer('/explosion.mid', 'audio/midi') then Halt;
if not SetPlayerCount(-1) then Halt;
if not StartPlayer then Halt;
Delay(5000);
end.
procedureStopPlayer
Sound and Musicneeds PMMAPI or MIDP2.0
procedure StopPlayer;
Stops the music that is currently played. procedure StopPlayer;
⛃
Resource Files
5
procedureCloseResource
Resource Filesneeds S
procedure CloseResource(res: resource);
Closes the given resource.
functionOpenResource
Resource Filesneeds S
function OpenResource(name: string):resource;
The function opens the resource file located within the application's JAR file. To add the resource file into the JAR file, select the Project->Insert resource menu.
Example
var res : resource;
byte : integer;
line : string;
index : integer;
begin
res := OpenResource('/data.txt');
if (resourceAvailable(res)) then
begin
byte := ReadByte(res);
line := ReadLine(res);
CloseResource(res);
end;
ShowForm;
index := FormAddString('Byte is: ' + chr(byte));
index := FormAddString('Line is: ' + line);
Delay(1000);
end.
functionReadByte
Resource Files
function ReadByte(res: resource):integer;
Reads the next byte from the given resource, or returns EOF if there is nothing to read or there was an error reading from the resource.
functionReadLine
Resource Files
function ReadLine(res: resource):string;
Reads the next line from the given resource, returns an empty string if there were no more lines to read or if there was an error reading from the stream. If there are empty lines in the resource, they will be skipped.
functionResourceAvailable
Resource Files
function ResourceAvailable(res: resource):boolean;
The function returns true if the given resource is available (e.g. if it was open correctly).
⚙
Misc
10
procedure Assert(cond: boolean);
This procedure test if the given condition is true. If the given condition fails (it is not true), then an assertion message is written to the standard debug output. More information about debug output can be found with the definition of debug procedure. The sample assetion message looks like this: Assertion failed at: Tetris.mpsrc:162
function Chr(n: integer): char;
Returns the character with the given ASCII code. Behavior is undefined if 'n' is larger than 127.
procedure Debug(s: string);
This procedure writes the given string to the simulator's standard output. It has no effect on the mobile device (except that the generated MIDlet is slightly larger).
function GetProperty(propertyName: string): string;
This procedure is used to get the information about the Java system. Consult the Java documentation for the list of available properties.
Example
begin
Debug(GetProperty('microedition.locale'));
end.
procedure Halt;
Terminates the MIDlet execution. procedure Halt;
functionIsMidletPaused
Misc
function IsMidletPaused: boolean;
Returns true if the MIDlet is in the paused state, otherwise false. When the MIDlet is started, it is not in the paused state. The MIDlet can enter paused state when, for example, the phone receives incoming call. Then the MIDlet enters paused state, the call is answered, and after the phone call the user may resume the MIDlet - after resuming the MIDlet is not in the paused state any more. Determining if the MIDlet is in the paused state may be useful in different applications. Consider, for example, a game that must be paused when the MIDlet is paused. The following code would do the trick: function IsMidletPaused: boolean;
Example
...
repeat
{ process keypad inputs and read the timer }
{ if the MIDlet is paused, wait until it is resumed }
while IsMidletPaused do
begin
Delay(100);
end;
until gameOver;
...
function Odd(n: integer): boolean;
Returns true if the given number 'n' is odd, false otherwise.
function Ord(c: char): integer;
Returns the ASCII character code for the given character.
function Random(n: integer): integer;
Returns the pseudorandom number between 0 and (n-1). The following function will return random boolean value; the probability that the returned value is true is 75 %.
Example
function randomBoolean: boolean;
begin
if Random(4) = 3 then
randomBoolean := false;
else
randomBoolean := true;
end;
procedure Randomize;
Reinitialize the random number generator. The MIDlet does this initialization when it is run; however, you may wish to reinitialize the random number generator at some time. procedure Randomize;
Lookup tables
Appendices
Predefined constants and key scan codes, for quick reference.
Predefined constants
Constants the compiler defines for every program — no declaration needed.
Game actions — returned by KeyToAction
| Constant | Value | Constant | Value |
| GA_NONE | 0 | GA_FIRE | 8 |
| GA_UP | 1 | GA_GAMEA | 9 |
| GA_DOWN | 6 | GA_GAMEB | 10 |
| GA_LEFT | 2 | GA_GAMEC | 11 |
| GA_RIGHT | 5 | GA_GAMED | 12 |
Key codes — standard on all phones
| Constant | Value | Constant | Value | Constant | Value |
| KE_NONE | 0 | KE_KEY4 | 52 | KE_KEY9 | 57 |
| KE_KEY0 | 48 | KE_KEY5 | 53 | KE_STAR | 42 |
| KE_KEY1 | 49 | KE_KEY6 | 54 | KE_POUND | 35 |
| KE_KEY2 | 50 | KE_KEY7 | 55 | | |
| KE_KEY3 | 51 | KE_KEY8 | 56 | | |
Fonts — for SetFont
| Face | Value | Style | Value | Size | Value |
| FONT_FACE_SYSTEM | 0 | FONT_STYLE_PLAIN | 0 | FONT_SIZE_MEDIUM | 0 |
| FONT_FACE_MONOSPACE | 32 | FONT_STYLE_BOLD | 1 | FONT_SIZE_SMALL | 8 |
| FONT_FACE_PROPORTIONAL | 64 | FONT_STYLE_ITALIC | 2 | FONT_SIZE_LARGE | 16 |
| | FONT_STYLE_UNDERLINED | 4 | | |
Font style values combine as a bitmask (e.g. bold + italic = 3).
Commands, text fields, choices, alerts, date fields
| Command type | # | Text field | # | Choice | # |
| CM_SCREEN | 1 | TF_ANY | 0 | CH_EXCLUSIVE | 1 |
| CM_BACK | 2 | TF_EMAIL | 1 | CH_MULTIPLE | 2 |
| CM_CANCEL | 3 | TF_NUMERIC | 2 | CH_IMPLICIT | 3 |
| CM_OK | 4 | TF_PHONENUMBER | 3 | DF_DATE | 1 |
| CM_HELP | 5 | TF_URL | 4 | DF_TIME | 2 |
| CM_STOP | 6 | TF_PASSWORD | 0x10000 | DF_DATE_TIME | 3 |
| CM_EXIT | 7 | GET / POST / HEAD | str | EOF | 1000 |
| CM_ITEM | 8 | pi | 3.14159… | alert types → | |
Alert types (passed to ShowAlert): ALERT_INFO,
ALERT_WARNING, ALERT_ERROR,
ALERT_ALARM, ALERT_CONFIRMATION.
HTTP methods GET, POST and HEAD are predefined string constants.
Key scan codes
The number keys, * and # report the same codes on every
phone. Navigation and soft keys do not — this is why KeyToAction exists.
Raw values from GetKeyPressed / GetKeyClicked by manufacturer:
| Key | Siemens | Sony Ericsson | Nokia | Motorola |
| 0 – 9 | 48–57 | 48–57 | 48–57 | 48–57 |
| * / # | 42 / 35 | 42 / 35 | 42 / 35 | 42 / 35 |
| Up | −59 | −1 | −1 | 1 (−1) |
| Down | −60 | −2 | −2 | 6 (−2) |
| Left | −61 | −3 | −3 | 2 (−3) |
| Right | −62 | −4 | −4 | 5 (−4) |
| Fire | −26 | −5 | −5 | 20 (−5) |
| Left soft-key | −1 | −6 | — | 21 |
| Right soft-key | −4 | −7 | — | 22 |
| Clear | — | −8 | −8 | 0 |