Plua

1. Introduction

Plua is a port of Lua 4.0 (plus a small IDE) for the Palm Computing platform. Lua is a programming language designed at TeCGraf, the Computer Graphics Technology Group of PUC-Rio, Brazil.

More information on Lua can be found at Lua. (NOTE: I have no affiliation with TeCGraf or PUC-Rio)

THIS SOFTWARE COMES WITH ABSOLUTELY NO WARRANTY, SO USE IT AT YOUR OWN RISK. Plua can not be reverse engineered or modified in any way. To include Plua in any software collection, online or not, first contact the author for permission. No one is allowed to sell or charge for redistributing Plua.

Plua is Copyright (c) 2001 Marcio M. Andrade.

2. Operation

Plua can be used in two different modes. The first one provides a quick read-eval-print loop. In this mode you can type a program and have it evaluated immediatelly. You type a program in the lower half of the screen and the results are printed in the upper half. To evaluate the current program, tap the Run button. To clear the current program, tap the Clear button.

For example, if you type in the text field this program:

print("Result = ", 2*3)
Plua will print the following in the result area:
Result =   6
The second mode also allows you to run Lua programs, but with two differences:

To select a program in a MemoPad record, tap the Memo button. To select a program in a DOC file, tap the Doc button. IMPORTANT: if you create a MemoPad record with Lua code, it MUST start with "-- " (without the quotes and with a trailing space) and then the program name (usually a single word) ended with ".lua", otherwise it will not be visible in Plua. DOC files must also end in ".lua".

In either option, a list of current available programs is displayed.

Select one program on the list and tap the Run button to run it. Plua will switch to a full screen mode and run the program. When it is finished Plua will return to the program selection screen. If you want avoid the automatic return to the selection screen, you can add a pevent() function as the last statement of your program. If you want to stop a program before it is finished tap the Applications icon. Note that when a program is running the Power-off button will not respond.

If you do not want to run a program, tap the Back button to return to the main screen.

The button Compile is used to compile a program into a PRC file. The generated PRC is a standalone application that can be accessed like any other one in the Application Launcher. Note however that Plua or PluaRT (the Plua runtime) needs to be installed. You do not need to install both if you just want to run Plua applications. If neither Plua nor the runtime is installed and a compiled program is run, an error message will be displayed and the program will be aborted. Generated PRCs have a fixed pre-defined icon.

Note that it is not necessary to compile a program in order to run it. If you just to want to run a program from within Plua, you can use the Run button directly. The Compile button should be used only when you want to generate a standalone PRC with your program.

Preferences are accessible via Menu/Preferences in the main screen. If "Read-only mode" is checked, all attempts to open a database for writing or removing a database will be aborted, and an error message will be displayed. If "Clear output" is checked, the Clear button also clears the output area.

3. Technical notes

A great effort was put on porting the complete Lua 4.0 package. Some portions of the source code were kept almost intact, while others have been heavily modified, in order to fit the PalmOS architecture.

3.1. Compatibility

Plua requires PalmOS 3.1 or greater (Plua was not tested on PalmOS 3.2, and since it is NOT a superset of PalmOS 3.1, it may not work). Indexed color support (2-bit, 4-bit or 8-bit) requires at least PalmOS 3.5. On other OS versions the screen is considered monochromatic (colors are 0=white, 1=black), even if the hardware supports grayscale.

3.2. Limitations when compared to the standard Lua distribution

3.3. Extensions to the standard Lua distribution

In addition to the functions of standard Lua libraries, Plua provides additional functions to access PalmOS specific features. In the following lists, optional parameters are denoted by square brackets.

Database I/O functions:

Resource functions: Serial I/O functions: Low-level graphical functions: UI-related functions: Event functions: Sound functions: Bitwise operator functions: Binary data functions: Misc functions: Built-in constants:

4. A small tutorial

This section assumes that you are already familiar with the Lua language, and focuses on issues related to the Palm platform. If you don't know the language Lua, don't worry. There is a lot of documentation on its home page. If you really want to start programming right away without reading the docs, here are a few tips:

4.1. Working with the display

Plua handles your device screen as a bitmapped display where individual pixels can be addressed. The "stdout" is also mapped to the display, so when you use print() or write() the characters are written to the display. Plua stores the current cursor position in a pair of numbers (x,y). This position is updated whenever you write to the display.

The statement

pline(0,0,19,19)
will draw a line from position (0,0) to (19,19) and will update the current cursor position to (19,19). If the next statement is
write("abc")
the string "abc" will be printed starting at position (19,19) and the cursor will be placed at (19,19+d), where d is the width in pixels of string "abc" written with the current font.

Besides the cursor position, Plua also stores the current foregroung color, the current background color and the current font. The following example writes the string "Plua" in red over black with the bold font:

pcolor(prgb(255,0,0), prgb(0,0,0))
pfont(1) print("Plua")
Plua works with 1-bit monochromatic displays, 2-bit or 4-bit grayscale displays and with 8-bit color displays. The foreground and background colors are mapped to the closest grayscale tone in your device, if color is not available. You can find the display properties of your device by calling the pmode() function:
width, height, depth, hasColor = pmode()
print(width, height, depth, hasColor)
Width and height are the display dimensions in pixels. Depth is 1, 2, 4, or 8, and hasColor is 1 if the display supports color, or 0 otherwise. On color devices, you can use the prgb() function to get the index of a color given its red, green and blue components. The example below will print 125 on 8-bit color device using the standard color pallete.
red = prgb(255,0,0)
print(red)
Plua supports a Logo-like "turtle" pointer. Using pwalk() and pturn() you can walk around the display drawing lines. The example below clears the display, positions the cursor at the middle of the display and draws a small expiral.
pclear() w,h = pmode() pmoveto(w/2,h/2)
for d = 1,20,1 do
  pwalk(d) pturn(-40)
end
The following example shows how to draw a bitmap. 11000 is the resource ID of the "Taxi" bitmap stored in Palm ROMs.
pclear()
bmp = popenres("Tbmp", 11000)
pdrawbmp(bmp)
pcloseres(bmp)
One final note on the display: writing at the end of a line does not make it to wrap, and writing at bottom line does not make the display to scroll up.

4.2. Working with User Interface

The standard PalmOS UI componentes can be easily created and interacted with. The usual way to do this is to create a few components and then enter a loop waiting for UI events. The following example does exactly this:
textField = pfield(1,20,20)
lengthButton = pbutton("Length") pnl()
while 1 do
  e,id = pevent()
  if e == ctlSelect and id == lengthButton then
    print(strlen(pgettext(textField)))
  end
end
The functions pfield() and pbutton() create a 1-line text field and a button, respectively. The pnl() function positions the cursor below the button. The infinite loop calls pevent(), which makes the application block until an UI event is generated. In our example, the "Length" button will generate the an event (ctlSelect) when it is pressed. pevent() returns this event ID and the component ID (in this case the ID of the button). The program uses pgettext() to retrieve the current contents of the text field and prints its length.

NOTE: since this program enters an infinite loop, the only way to stop it is to tap the Applications icon.

The example below shows pinput(), palert() and pconfirm().

s = pinput("Write something")
if s ~= nil then
  palert("You wrote "..s)
end

if pconfirm("Are you tired ?") then
  print("Me too")
else
  print("Me neither")
end
In order to set a menu for your application, you can use pmenu() as following.
pmenu({"O:Open", "Preferences", "-", "Q:Quit"})
The menu will have 4 items: the fixed "About Plua" item, a fixed separator, an "Open" item with "O" as shortcut, a "Preferences" item with no shortcut, a separator, and a "Quit" item with "Q" as shortcut. Limitations: currently pmenu() will work ONLY on PalmOS 3.5 or greater (earlier versions do not allow dynamic menu configuration), it works only in full-screen mode, and it is not possible to define more than one menu in the same menu bar. pmenu() can be called any time, and it will replace the current menu with the new one.

When one of the menu items is selected (except the About item), a menuSelect event is returned by pevent(). In the example above, if "Preferences" was selected, pevent() would return menuSelect and the number 2, meaning that the second user defined item was selected.

4.3. Working with file I/O

Although PalmOS does not have a true filesystem, Plua provides the Lua virtual machine the illusion that the underlying OS supports file I/O. The "stdout" descriptor is mapped to the display. The "stderr" descriptor is mapped to a dialog box that shows what was printed on stderr.

Regular files are implemented using the File Stream API of PalmOS, so Lua programs can open, create, read from and write to files normaly, without knowing about database types or database creators. The following example shows this:

f = openfile("MyOutput", "w")
write(f, "This is being written to a PalmOS stream database")
closefile(f)
The database MyOutput is open for writting (it is created if it does not exist), a string is written to it, and it is closed.

There are also functions that allow a program to manipulate a PalmOS database directly, if desired. They were listed in the section "Extensions to the standard Lua distribution" above. The example below iterates through all MemoPad records and prints the first line of each record:

f,n = opendb("MemoDB", "r")
for i = 0,n-1,1 do
  openrec(f, i)
  s = read(f, "*l")
  print(s)
end
closedb(f)
The read() function belongs to the standard I/O Lua library. The I/O functions work with both stream files and regular databases. With regular databases, each record works like a sub-file, that is, they can be read from the begining to the end, when an EOF conditions is signaled. In order to continue to read the database, openrec() must be called to open the next record and so on.

The available modes for opendb() are:

The first two modes also accept the "b" suffix (like "rb" or "r+b"), which means binary mode. If a record is read in binary mode, the last character is ignored if it is ASCII 0 (nul). This is necessary because applications like MemoPad always write a nul as the last character of a record. In some cases this nul must be ignored, while in others (like binary data) it may be significant.

The standard dofile() function works with DOC files, MemoPad records and compiled applications. If there is a DOC file named "name.lua", for example, it can be included by using dofile("name.lua"). For MemoPad records, the record name must be prefixed with the string "memo:". If there is a record named "-- name.lua", for example, it can be included by using dofile("memo:name.lua"). For applications, the compiled lua code can be included by using dofile("appname"), where "appname" is the PRC name.

A note about error handling in file I/O: in case of success, the functions marked as returning true in fact return an userdata value (which is true, since any non-nil value is considered true in Lua). The value of this userdata is not important, it is used just to make it different from false (nil). In case of failure, all I/O functions (except for read) return two additional values besides nil. The second value is a string with the error message and the third value is the numeric error code. The error messages/codes are inspired on the Unix C Library (libc) errors. Currently the following errors may be reported:

For example, suppose opendb() is used to open a database, like in the following code:
f,n,e = opendb("Test", "r")
If there is a database named Test, f will be assigned a handle to the opened database, n will be assigned the number of records in the database and e will be assigned nil. However, if there is no databse named Test, f will assigned nil, n will be assigned the string "No such file or directory" and e will be assigned 2 (for ENOENT). This example illustrates how a function may return different number of values (and possibly of different types) depending on its execution.

4.4. Working with serial I/O

The function openser() opens an IO port known to the New Serial Manager. Currently only the serial (RS-232) and infrared (IrComm) ports are supported. The following example shows how to open the serial port and wait for data in a efficient way.
f = openser("serial0", 57600, "8N1")
while 1 do
  ev = pevent()
  if ev == ioPending then
    s = read(f, 8)
    print(s)
  elseif ev == penDown then
    break
  end
end
closeser(f)
When data is available at the serial port, the ioPending event is sent. Note that it is not possible to know how much data is available. The read() function reads at most 8 bytes and returns. If less than 8 bytes are available, read() returns them without blocking. If more than 8 bytes are available, they remaining bytes are hold in the Serial Manager buffer. In the next loop interaction, another ioPending event will be sent, and so on. In this example, the loop is stopped when the user taps anywhere in the screen with the pen.

The functions openser() and closeser() may also return the error messages/codes defined for file I/O.

4.5. Working with binary data

Most PalmOS applications save persistent data in one or more PDB's. This information is written in binary form, that is, a sequence of bytes usually representing the encoding of a C structure. In Lua, however, information is stored in numbers, strings and tables, and their internal binary representation is not relevant. In order to read and write binary data, Plua provides the functions pack() and unpack(). The following example shows the usage of these functions along with database access functions.

Storing a a table into a PDB record:

table = {25, "Plua", 3.1416, 9999}
data = pack("BSDW", table)
f = opendb("MyBinaryData", "wb")
index = createrec(f, strlen(data))
openrec(f, index)
write(f, data)
closedb(f)

According to the format string "BSDW", the number 25 (the first element) is packed as a byte, the string "Plua" is packed as a null-terminated string, the number 3.1416 is packed as a double and the number 9999 is packed as a 16 bit word. The returned data is a binary string of 1+5+8+2 = 16 bytes. This data is stored as record in the MyBinaryData PDB.

Reading the same record into a table:

f = opendb("MyBinaryData", "rb")
openrec(f, index)
data = read(f, "*a")
table = unpack("BSDW", data)
closedb(f)

After this, the returned table will have the same elements as the original one.

4.6. Working with libraries

Although Plua does not directly support the concept of libraries, there is a way to use compiled applications as libraries. Lets say you have a set of useful Lua functions and you want to make them available to other developers. The obvious way is to distribute the source code, but there is an alternative: place the functions inside a MemoPad record or DOC file and compile it just like a regular application. For example, if the generated PRC is named "MyLib", another application can simply use dofile("MyLib") to load the functions.

To distribute your "library", you have to distribute the PRC named "MyLib.prc" that was created when you compiled it. - New: pack() and unpack() functions to manipulate binary data. - New: user defined function _finish() is called when execution ends.