Plua ドキュメンテーション
1. 導入
Plua は Lua 4.0.1 (に加えて小さな IDE) を Palm Computing のプラットフォームに移植したものです。Lua は TeCGraf - the Computer Graphics Technology Group of PUC-Rio, Brazil でデザインされたプログラミング言語です。
Lua についての詳しい情報は [Lua] にあります。(注意: 私は TeCGraf や PUC-Rio とは無関係です)
このソフトウェアは完全に無保証です。ですから、自己責任で使用してください。 Plua はリバースエンジニアリングやどんな方法でも変更することはできません。Plua をソフトウェア集に含める場合は、オンラインであるかどうかに関わらず、まず作者に許可を求めてください。Plua を売ったり再配布したりするために Plua を変更することは許されていません。
Plua is Copyright (c) 2001-2005 Marcio M. Andrade.
2. 操作
Plua は 2 つの異なるモードで使用することができます。最初のひとつは素早い 読み込み-評価-表示 のループを提供します。このモードではプログラムを入力してすぐに評価させることができます。画面の下半分にプログラムを入力すると結果が上半分に表示されます。入力中のプログラムを評価するには、Run ボタンをタップします。入力中のプログラムを消すには、Clear ボタンをタップします。
例えば、テキストフィールドにこのプログラムを入力した場合:
print("Result = ", 2*3)
Plua は結果エリアに以下の内容を表示するでしょう:
Result = 6
ふたつめのモードも Lua のプログラムを実行することができますが、2 つの違いがあります:
- プログラムは MemoPad のレコード、Doc ファイル、ストリームファイルあるいは VFS カードに保存されたファイルから取り出されます。
- 結果を表示するためにスクリーン全体が使用できます。
ファイル選択画面にアクセスするためには File ボタンをタップします。右上で 4 つのファイルタイプ(Memo、Doc、Stream、Card)から選択することができます。選択されたタイプの現存するプログラムのリストが表示されます。
Lua コードの Memo を作成する場合、"-- " (引用符は不要で、後ろにスペースが必要です)で始まり、プログラム名(通常はひとつの単語)が ".lua" で終了していなくてはなりません。そうでないと、Plua で表示されないでしょう。Doc、Stream、VFS ファイルも同様に ".lua" で終了していなければなりません。
リストからひとつプログラムを選び、Run ボタンをタップして実行します。Plua は全画面モードに切り替わり、プログラムを実行します。プログラムが終了したとき、Plua はプログラム選択画面に戻ります。終了する前にプログラムを止めたい場合には、アプリケーションアイコンをタップします。Plua は VFS ファイルを拡張カードの /PALM/Programs/Plua/src から探します。
Compile ボタンはプログラムを PRC ファイルにコンパイルするために使用されます。生成された PRC は他のプログラムと同じようにアプリケーションランチャーから実行することができます。しかしながら、Plua もしくは PluaRT(Plua ランタイム)がインストールされている必要があることに注意してください。Plua アプリケーションを実行したいだけならば両方をインストールする必要はありません。Plua もランタイムもインストールされていない状態でコンパイルしたプログラムが実行された場合、エラーメッセージが表示されてプログラムは停止します。生成された PRC はあらかじめ準備された固定のアイコンになります。プログラムを実行するためにコンパイルが必須ではないことに注意してください。Plua 内でプログラムを実行したいだけならば、Run ボタンを使うことができます。Compile ボタンはあなたのプログラムからスタンドアロンの RPC を生成したい場合だけに使うべきです。
Main ボタンをクリックするとメイン画面に戻ります。メモ(Memo)については、さらに 2 つのボタンがあります: New と Edit で、それぞれメモを作成、編集するためのものです。Doc については、同じように Edit ボタンがあります。このボタンをタップすると、Plua はサードパーティアプリケーションの SrcEdit を起動し、doc ファイルを編集することができます。このアプリケーションがインストールされていない場合は何も起こりません。
初期設定(Preference)はメニューの Preferences からアクセスすることができます。"Read-only-mode" がチェックされている場合、データベースへの書き込みアクセスや削除は中止され、エラーメッセージが表示されるでしょう。"Clear output" がチェックされている場合、Clear ボタンは出力エリアも消去します。
Plua のオンラインヘルプシステムは PalmOS の標準の "Find" ボタンからアクセスできます。メイン画面やメモの編集中に Find ボタンをクリックすると、Plua はすべての関数名を表示するダイアログを開きます。関数名を選択して Goto をタップすれば Plua は関数のリファレンスを表示します。Index ボタンをクリックすると、すべての関数名がもう一度表示されます。Done をタップするとヘルプダイアログを閉じます。メイン画面やメモの編集中に、Find ボタンをタップする前にまず単語を選択しておくこともできます。この場合には、ヘルプダイアログは直接関数のリファレンスを開きます。ヘルプシステムを使用するためには、まず pluahelp.prc をインストールしなければなりません。
3. テクニカルノート
完全な Lua パッケージを移植するために大変な努力をしています。ソースコードのいくつかの部分はほとんどそのままですが、それ以外の部分は PalmOS のアーキテクチャにあうように大きく変更されています。
3.1. 互換性
Plua は PalmOS 3.1 以降を必要とします。インデックスカラーのサポート(2 ビット、4 ビット、8 ビット)には少なくとも PalmOS 3.5 が必要です。それ以外のバージョンでは、ハードウェアがグレースケールをサポートしている場合でも画面はモノクロ(カラーは 0=white と 1=black)と見なされます。
3.2. 標準の Lua ディストリビューションと比較したときの制限事項
- 以下の標準入出力ライブラリ(liolib)の関数は存在しません: debug, execute, getenv, rename, setlocale, tmpname。日付関数は部分的に実装されています(いくつかのフォーマットオプションは存在しません)。
- "stdin" - 標準入力ストリーム の概念はありません。プログラムはファイルからデータを読み込むことができますが、ユーザの入力からはできません。ユーザの入力はペン/キーイベントや UI コンポーネントへの操作に制限されています。
- 数の基数は 10 進数だけがサポートされています。
- ほとんどの標準数学ライブラリ(lmathlib)の関数は正しく動作するために MathLib(サードパーティのライブラリ)を必要とします。
3.3. 標準の Lua ディストリビューションからの拡張機能
標準の Lua ライブラリの関数に加えて、Plua は PalmOS 独自の機能にアクセスするための追加関数を提供しています。以下のリストでは、オプションのパラメータを角括弧 [] であらわしています。
データベース入出力関数:
- listdb(creator, type [,suffix]): 指定されたタイプとクリエータ、オプションの拡張子に一致するすべてのデータベースのテーブルを返します。タイプとクリエータは 4 文字の文字列か、すべてを受け付ける空の文字列です。
- opendb(name, mode): PalmOS データベースを開きます。モードは "r" で読み込み専用のアクセス、"r+" で読み/書きのアクセス、"w" で書き込み専用のアクセスとなります。モードが読み込み専用でない場合、データベースが存在しなければ作成されます。この関数は開かれたファイルへのハンドルとデータベースに存在するレコード数を返します。このハンドルは他のデータベース入出力関数において最初のパラメータとして使用されます。エラーが起こった場合、nil を返します。
- closedb(f): データベースを閉じます。成功した場合 true を、エラーが起こった場合は nil を返します。
- getdbcat(f, n): すでに開かれているデータベース f からカテゴリ n (n は 0 から 15)の名前を返します。
- setdbcat(f, n, "cat"): すでに開かれているデータベース f のカテゴリ n (n は 0 から 15)の名前を "cat" に設定します。設定されたカテゴリ名を返します。
- openrec(f, i): すでに開かれているデータベース f からインデックス i のレコードを開きます。レコードのサイズか、もしエラーが起こったときは nil を返します。
- createrec(f, size): creates a new record with given size in (already open) database f. The record is added at the end of the database. The created record is NOT automatically opened, so it is necessary to call openrec() to open the just created record before using it. Returns the index of the new record or nil if an error ocurred.
- deleterec(f, i): deletes the record with index i from (already open) database f. The record can not be open when it is deleted. Returns true if success or nil if an error occurred.
- closerec(f): closes the current open record of (already open) database f. Returns true if success or nil if an error occurred.
- resizerec(f, i, size): resizes the record with index i from (already open) database f to the specified size. If the record beeing resized is the currently open record, it is closed, resized and then reopened. Returns true if success or nil if an error occurred.
- getreccat(f, i): returns the category number for record index i from already open database f.
- setreccat(f, i, n): sets the category number to n for record index i on already open database f. Returns the category number just set.
- pgetprefs("creator", id): returns a string with the preferecences specified by creator and id, or nil if it does not exist.
- psetprefs("creator", id, prefs): sets the preferecences specified by creator and id to the given string prefs. Returns nothing.
ディレクトリ関数:
- opendir(name): VFS ディレクトリを読み込み用に開きます。開かれたディレクトリのハンドルを返します。
- closedir(f): ディレクトリを閉じます。成功すれば true を、エラーが起これば nil を返します。
- readdir(f): ディレクトリエントリを読み込みます。エントリの名前とタイプ(4=ディレクトリ、8=標準ファイル、10=リンク)を返します。
- mkdir(name): VFS ディレクトリを作成します。成功すれば true を、エラーが起これば nil を返します。
- listdir(name [, suffix]): VFS ディレクトリにある指定されたファイル名(name)のテーブルを返します。オプションのパラメータが設定された場合は指定された拡張子(suffix)のファイルだけを返します。
リソース関数:
- popenres("type", id [, file]): opens the resource with specified type (4 character string) and id. The resource is searched in all open databases or, if the optional file parameter is passed, only in the database named "file". Returns a number identifying the resource.
- pcloseres(r): closes the resource identified by number r. The number r is returned by the popenres() function. Returns nothing.
- pgetres(r [, start [, end]]): returns a string with the contents of the resource identified by number r. You can optionally specify just a substring of the resource, with the start and end parameters. The number r is returned by the popenres() function. Returns a string with the resource.
- pgetsize(r): returns the size of the resource identified by number r. If the resource is a bitmap, two additional numbers are returned: the width and the height of the bitmap. The number r is returned by the popenres() function.
- pdrawbmp(r [, mode]): draws the bitmap identified by the numbner r in the current cursor position. The cursor is advanced to the right of the bitmap. The optional mode parameter affects how pixels are transfered to screen (0=paint, 1=erase, 2=mask, 3=invert, 4=overlay, 5=paint inverse). The number r is returned by the popenres() function. Returns nothing.
シリアル入出力関数:
- openser(name, baud [,mode]): 新しいシリアルマネージャを使って IO ポートを開きます。現在のところ、名前(name)は "serial0" か "ir0" が使用できます。これらはそれぞれシリアルポートまたは赤外線ポートを開きます。baud は数値を、オプションの mode は "8N1" (デフォルト)や "7E1" といった文字列を指定します。最初の文字はワードサイズ(5、6、7、8)を、2 番目の文字はパリティ(N、E、O)を、3 番目の文字はストップビットの数(1、2)を指定します。開かれたポートのハンドルか、エラーが起こったときは nil を返します。Palm OS はひとつ以上のポートを開くことを許可しないことに注意してください(シリアルか赤外線のいずれかを開くことができますが、両方同時に開くことはできません)。
- closeser(f): 開かれたシリアルポートを閉じます。成功すれば true を、失敗すれば nil を返します。
低レベルのグラフィック関数:
- pmode(): 4 つの数を返します: スクリーンの幅、スクリーンの高さ、スクリーンの色深度、スクリーンがカラーをサポートしているかどうかをあらわす 1 か 0 の数字です。スクリーンの高さは、対話型モードではフルスクリーンモードの半分になります。
- pclear([c]): スクリーンを背景色もしくはオプションの色 c で消去し、カーソルを 0,0 に移動します。何も返しません。
- pcolor(fg [,bg]): 前景色(fg)とオプションで背景色(bg)を設定します。何も返しません。
- prgb(r, g, b): (赤(Red),緑(Green),青(Blue)) のコンポーネントに相当する色を返します。
- ppos(): 2 つの数字、現在のカーソルの位置 x,y を返します。
- pmoveto(x, y): スクリーンのカーソルを x,y の位置に移動します。
- pline(x1, y1, x2, y2 [,c]): x1,y1 から x2,y2 へ前景色あるいはオプションで指定された色 c で線を引きます。
- plineto(x, y [,c]): 現在の(カーソルの)位置から x,y へ前景色あるいはオプションで指定された色 c で線を引きます。
- pset(x, y [,c]): x,y の位置に前景色あるいはオプションで指定された色 c のピクセルを描きます。
- pget(x, y): x,y の位置のピクセルの色の値を返します。
- prect(x, y, dx, dy [,c]): x,y から dx,dy ピクセル広がる長方形を描きます。前景色あるいはオプションで指定された色 c が使用されます。
- pbox(x, y, dx, dy [,c]): x,y から dx,dy ピクセル広がる塗りつぶされた長方形を描きます。前景色あるいはオプションで指定された色 c が使用されます。
- pcircle(x, y, rx, ry [,c]): x,y を中心とする楕円を描きます。rx,ry は x,y 方向の半径で、前景色あるいはオプションで指定された色 c が使用されます。円を描くためには、rx=ry とします。
- pdisc(x, y, rx, ry [,c]): x,y を中心とする塗りつぶされた楕円を描きます。rx,ry は x,y 方向の半径で、前景色あるいはオプションで指定された色 c が使用されます。円を描くためには、rx=ry とします。
- pfill(x, y, [,c]): x,y のピクセルから前景色あるいはオプションで指定された色 c で塗りつぶしを行います。最初のピクセルと異なる色のところまでを塗りつぶします。何も返しません。
- pfont(f): sets the text font to number f. Returns two numbers with the "average" width of a character and the height of a character, both in pixels. Note that PalmOS fonts are not fixed-width fonts, so if the returned width is used in calculations, you get just an approximation.
- ptextwidth(text): returns the width of the text string in pixels.
- pheading(g): turns the graphical "turtle" to the specified heading g (in degrees). 0 points to the right, 90 points up, and so on. Returns nothing.
- pturn(g): turns the graphical "turtle" g degrees. g can be positive or negative and it is added to the current heading. Returns nothing.
- pwalk(d): draws a line from the current cursor position, with extent d and following the current "turtle" heading. The cursor is positioned at the end of the line. Returns nothing.
- pgetbuffer(x, y, dx, dy): saves in a buffer the pixels delimited by a rectangle at x,y, extending dx,dy pixels. Returns a number identifying the saved buffer.
- pnewbuffer(dx, dy): creates an blank buffer extending dx,dy pixels. Returns a number identifying the new buffer.
- pputbuffer(id, x, y [, mode]): draws a saved buffer at coordinates x,y. The optional mode parameter affects how pixels are transfered to screen (0=paint, 1=erase, 2=mask, 3=invert, 4=overlay, 5=paint inverse). Returns nothing.
- pusebuffer([id]): sets a selected buffer for drawing. If the argument is missing, the screen is selected for drawing. Returns nothing.
- pfreebuffer(id): frees the saved buffer. Returns nothing.
- pwritebuffer(filename [,id]): writes buffer identified by id into file filename. If id is not specified the current screen is written. Returns the resulting file size or nil in case of error.
- preadbuffer(filename): reads a buffer from file filename. Returns a number identifying the new buffer, its width and its height. In case of error, nil is returned.
- pclip(x, y, dx, dy): sets the clipping region to the rectangle at x,y, extending dx,dy pixels. If no parameter is passed the clipping region is reset. Returns nothing.
UI 関係の関数:
- ptitle([text]): 現在のフォームのタイトルを設定します。フルスクリーンモードでのみ動作します。パラメータが省略されたとき、タイトルが消去されます。
- pmenu(t): メニュー項目を定義します。現在のところ常に存在する固定のメニュー項目が存在します: "About Plua"。pmenu(0 に文字列のテーブルを渡すことによって追加のメニュー項目を定義することができます。文字列がコロンを伴った文字で始まっている場合、この文字は項目のショートカットとして使われます。
- plabel(text): 現在のカーソルの位置に与えられたテキストでラベルを作成します。カーソルはコンポーネントの右に位置します。コンポーネントの ID、あるいは作成できなかった場合には nil が返されます。
- pbutton(text [,bmpId]): 現在のカーソルの位置に与えられたテキストでボタンを作成します。カーソルはコンポーネントの右に位置します。オプションの bmpId が渡され、PalmOS のバージョンがグラフィックコントロールをサポートしている場合、与えられたビットマップのリソース ID によるグラフィックボタンが代わりに作成されます。コンポーネントの ID、あるいは作成できなかった場合には nil が返されます。
- ppbutton(text [,g [, bmpId]]): creates a pushbutton with given text in the current cursor position. Pushbutons can be optionally placed in a given group number g. The cursor is positioned to the right of the component. If the optional bmpId is passed and the PalmOS version supports graphic controls, a graphic button with the given bitmap resource ID is created instead. Returns the ID of the component or nil if it could not be created.
- prbutton(text [,bmpId]): creates a repeating button with given text in the current cursor position. The cursor is positioned to the right of the component. If the optional bmpId is passed and the PalmOS version supports graphic controls, a graphic button with the given bitmap resource ID is created instead. Returns the ID of the component or nil if it could not be created.
- pcheckbox(text): creates a pushbutton with given text in the current cursor position. The cursor is positioned to the right of the component. Returns the ID of the component or nil if it could not be created.
- pselector(text [,bmpId]): creates a selector trigger with given text in the current cursor position. The cursor is positioned to the right of the component. If the optional bmpId is passed and the PalmOS version supports graphic controls, a graphic button with the given bitmap resource ID is created instead. Returns the ID of the component or nil if it could not be created.
- pslider(width, range [,value]): creates a slider control with the specified width in pixels. The slider values go from 0 to range-1. The optional value parameter is the initial slider value. The cursor is positioned to the right of the component. Returns the ID of the component or nil if it could not be created.
- pfield(lines, cols, max [,text [, e, u]]): 現在のカーソルの位置に与えられた行数と桁数のテキストフィールドを作成します。フィールドは最大で max 文字までを受け付けます。フィールドはオプションで指定されたテキストで初期化されます。オプションのパラメータ "e" と "u" はフィールドが編集可能かどうかと下線が引かれるかどうかをそれぞれ指定するための値です。値 nil は偽をあらわし、nil でない値は真をあらわします。これらのパラメータが渡された場合、text パラメータも渡されなければなりません。カーソルはコンポーネントの下に位置します。コンポーネントの ID、あるいは作成できなかった場合には nil が返されます。1 行以上のフィールドについては、ユーザが表示可能な行数よりも多くのテキストを入力した場合にスクロールバーがフィールドの右に自動的に配置されます。
- pfieldattr(id, e, u): sets the attributes of an existing field identified by the given ID. The next two parameters are the same as in pfield(). Returns nothing.
- psetfocus(id): sets the focus to the field identified by the given ID. Works only with text fields. Returns nothing.
- plist(lines, cols, t [,sel]): creates a list with given number of lines and columns in the current cursor position. The list is filled with the elements of table t. Optionally the selected element is set to index sel. The cursor is positioned to the right of the component. Returns the ID of the component or nil if it could not be created.
- ppopup(t [,sel]): creates a popup list in the current cursor position. The list is filled with the elements of table t. The size is automatically adjusted. Optionally the selected element is set to index sel. The cursor is positioned to the right of the component. Returns the ID of the component or nil if it could not be created.
- pgettext(id): 与えられた ID で指定されたコンポーネントのテキストからなる文字列を返します。ラベル、ボタン、プッシュボタン、連続ボタンとチェックボックスについては、テキストはコンポーネントのラベルです。フィールドについては、テキストは現在の内容です。リストについては、テキストは現在選択されている要素です。
- psettext(id, text): 与えられた ID で指定されたコンポーネントのテキストを設定します。ボタン、プッシュボタン、連続ボタン、チェックボックス、ラベル、フィールド、リストに作用します。ラベルについては、新しいテキストの長さが現在の長さよりも長くない場合にのみ変更されます。リストについては、テキスト変数はテーブルでなければなりません。何も返しません。
- pinserttext(id, text): inserts a string text in the field identified by the given ID. Returns nothing.
- pgetstate(id): returns a number with the state of the component identified by the given ID. For pushbuttons and checkboxes, the number is 1 if selected, 0 if not selected. For lists and popups, the number is the index of the selected item. For fiels, two numbers are returned: the start and ending position of the selected text.
- psetstate(id, n): sets the state (or index for lists and popups) of the component identified by the given ID. Works with pushbuttons, checkboxes lists and popups. Returns nothing.
- psetstate(id, start [,end]): if only start is passed, sets the insertion point of the field identified by the given ID. If end is also passed, selects a portion of the field text (from start to end). Returns nothing.
- pnl(): カーソルを (x,y) に移動させます。x は一番左の位置、y は現在の "行" にある "もっとも高い" コンポーネントの下です。何も返しません。
- ptab([n]): カーソルを右に 8 ピクセル進めます。これは同じ行の UI のコンポーネントを分類するのに便利です。n が指定された場合カーソルは 8*n ピクセル進みます。何も返しません。
- pdestroy(): 現在スクリーンにあるすべての UI コンポーネントを破棄します。何も返しません。
- palert(text): 指定されたテキスト(text)の情報ダイアログを開きます。ユーザーはダイアログを閉じるために Ok ボタンを押さなければなりません。何も返しません。
- pconfirm(text): 指定されたテキスト(text)の確認ダイアログを開きます。ユーザーはダイアログを閉じるために Yes または No ボタンを押さなければなりません。Yes が押された場合は 1 を、No が押された場合は nil を返します。
- pinput([text [,initial]]): オプションで指定されたテキスト(text)をタイトルにした入力ダイアログを開きます。2 つめのオプションパラメータは入力の初期値を定義します。ユーザーは 255 文字までを入力することができます。ユーザーはダイアログを閉じるために Ok または Cancel ボタンを押さなければなりません。Ok が押された場合は入力された文字列を、Cancel が押された場合は nil を返します。
- pselectdate([text [, y, m, d]]): PamOS の日付選択ダイアログを開きます。text はオプションのタイトルを、y、m、d はダイアログに最初に表示される年、月、日を指定します。選択された年、月、日の 3 つの数字をこの順番で返すか、Cancel が押された場合は nil を返します。
- pselecttime([text [, h, m]]): PamOS の時間選択ダイアログを開きます。text はオプションのタイトルを、h と m はダイアログに最初に表示される時間と分を指定します。選択された時間と分の 2 つの数字をこの順番で返すか、Cancel が押された場合は nil を返します。
- pselectcolor(text, c): PalmOS の色選択ダイアログを開きます。text はダイアログのタイトルを、c はダイアログに最初に表示される色を指定します。フルスクリーンモードでのみ、また PalmOS 3.5 以上でのみ動作します。Ok が押された場合は選択された色の番号を返し、Cancel が押された場合は nil を返します。
- pgsi(): 現在のカーソルの位置に Graffiti State Indicator を作成します。フルスクリーンモードで、かつ PalmOS 3.5 以降の場合にのみ動作します。何も返しません。
- pdialog(x, y, dx, dy, title): pops up an empty dialog at position x,y with dimensions dx,dy. Controls can be created inside the dialog. The dialog must be closed with pdestroy.
イベント関数:
- pevent([n]): イベントが発生するまで停止します。イベントはハードボタンを押したというイベント、ペン入力イベント、UI コントロールの選択や、IO 待ちがある場合に発生します。最初の戻り値は常にイベントのタイプです: penDown、penUp、penMove、keyDown、ctlSelect、ctlRepeat、popSelect、lstSelect、menuSelect、ioPending、sampleStop のいずれかです(これらの定数は定義済みです)。ペンイベントの場合、さらに 2 つの数値が返されます: カーソル位置の x,y です。キーイベントの場合、さらに 1 つの数値が返されます: キーコードです。UI コントロールイベントの場合、さらに 2 つの数値が返されます: コントロール ID とコントロールの状態(1=選択されている、0=選択されていない)です。リストイベントとポップアップイベントの場合、さらに 2 つの数値が返されます。リスト ID と選択されたエレメントです。メニューイベントの場合、メニューアイテムのインデックス(1 から始まる)も返されます。IO 待ちイベント(ほかには何も返されない)はプログラムが IO をポーリングなしに待つための効率的な方法です。オプションのパラメータ n が指定された場合、pevent() は最大で n ミリ秒の間イベントを待ちます。イベントが何も起こらなかった場合、定数 nilEvent を返します。
サウンド関数:
- pbeep(n): plays the system sound identified by the number n. Returns nothing.
- psound(freq,len [,volume]): plays a tone with frequency freq (in Hz), duration len (in millisenconds), and optionally volume (0-64). Returns nothing.
- pplaysample(filename [,volume]): WAV ファイルにおさめられたサンプリングされたサウンドを再生します。ボリューム(volume)(0 から 64)が指定されなかった場合、システムの Game ボリュームが使用されます。サウンドの継続時間を秒単位で返すか、エラーが起こった場合は nil を返します。サウンドの再生が終わると sampleStop イベントが発生します。
- pstopsample(filename [,volume]): サンプリングされたサウンドの再生を止めます。何も返しません。
ビット単位の操作関数:
- andb(n1, n2): 整数 n1 と n2 のビット単位の AND を返します。
- orb(n1, n2): 整数 n1 と n2 のビット単位の OR を返します。
- xorb(n1, n2): 整数 n1 と n2 のビット単位の XOR を返します。
- notb(n): 整数 n のビット単位の NOT を返します。
バイナリデータ関数:
- pack("format", data): packs the elements of table data into a binary string, and the returns this string. The binary data format is specificed by the string argument format, in which each letter refers to a different encoding: B=8 bits unsigned integer; W=big endian 16 bits unsigned integer; L=big endian 32 bits unsigned integer; F=big endian 32 bits float; D=big endian 64 bits double; S=variable length string, ended with ASCII null.
- unpack("format", string): unpacks a binary string encoded with pack() and returns a table with the decoded elements.
その他の関数:
- psleep(s): 実行を s 秒間(s は整数)停止します。何も返しません。
- pcopy(s): 文字列 s をクリップボードにコピーします。何も返しません。
- ppaste(): クリップボードの内容の文字列を返します。
- pmem(): 使用中のメモリと総メモリを KB 単位で返します。
- loadlib(name): libkit で作られた C ライブラリを読み込みます。読み込まれたライブラリを識別する数値を返すか、エラーが起こった場合は nil を返します。
- removelib(id): loadlib で読み込まれた C ライブラリを解放します。何も返しません。
組み込み定数:
- _VERSION: Lua のバージョン番号からなる文字列 (これは標準の Lua の機能です)。
- _PLUA_VERSION: Plua のバージョン番号からなる文字列。
- _OS_VERSION: PalmOS のバージョン番号からなる文字列。
4. 簡単なチュートリアル
このセクションはあなたがすでに Lua 言語をよく知っていることを仮定し、Palm プラットフォームに関連した点に焦点をあわせます。言語 Lua を知らない場合でも、心配することはありません。そのホームページにたくさんのドキュメントがあります。ドキュメントを読まずにすぐにプログラミングを始めたいのであれば、以下はいくつかのティップスです:
- コメントは -- で始まり、行の最後まで続きます。
- 行は ";" で終わりません。
- 変数は宣言する必要はありません。
- 変数には型はありませんが、値にはあります。値は数値、文字列、関数とテーブルがあります。値は可能な場合正しい型に自動的に変換されます。例えば、1+"2" というコードは 3 と評価されます。
- 文字列の結合は .. という演算子で行われます。例えば、"abc".."def" というコードは "abcdef" と評価されます。
- 複数の代入がサポートされています。例えば、x,y=2,3,4 というコードは x に 2 を、y に 3 を割り当てます。使われてない値は破棄されます(この例では 4 のように)。
- 関数は複数の値を返すことができます。例えば、関数 f が 2 つの値を返す場合、これらは x,y=f() で得ることができます。
- 式のリストを print 関数を使って表示することができます: print(123,"abc",4*5,sin(45))
- 提供されているサンプルを見てください。
- Lua を使ってもっとたくさんのことができます。さあ、ドキュメントを読みましょう :-)
4.1. ディスプレイ
Plua はあなたのデバイスの画面をビットマップディスプレイとして扱うため、個々のピクセルを指定することができます。"標準出力" もディスプレイに割り当てられていますので、print() や write() を使えば文字がディスプレイに表示されます。Plua は現在のカーソル位置を数字のペア (x,y) に保存します。この位置はディスプレイに何かを書くたびに更新されます。
以下の命令は
pline(0,0,19,19)
(0,0) の位置から (19,19) までの直線を描き、カーソル位置を (19,19) に更新するでしょう。次の命令は
write("abc")
(19,19) の位置を開始位置とする "abc" という文字列を表示し、カーソルは (19,19+d) に移動されるでしょう。d は現在のフォントで描かれた文字列 "abc" の横幅をピクセル単位で表したものです。
カーソル位置の他に、Plua は前景色と背景色とフォントを保存します。下記の例は "Plua" という文字列を黒字に赤で太字フォントで描きます:
pcolor(prgb(255,0,0), prgb(0,0,0))
pfont(1) print("Plua")
Plua は 1 ビットのモノクロディスプレイ、2 ビットか 4 ビットのグレースケールディスプレイ、8 ビットのカラーディスプレイで動作します。前景色と背景色は、カラーが使用できないときには最も近いグレースケールトーンに割り当てられます。pmode() 関数を呼ぶことにより、デバイスのディスプレイ特性を調べることができます:
width, height, depth, hasColor = pmode()
print(width, height, depth, hasColor)
width と height はピクセル単位でのディスプレイ解像度です。depth は 1、2、4、8 のいずれかで、ディスプレイがカラーをサポートしている場合 hasColor は 1 になり、サポートしていなければ 0 になります。カラーデバイスにおいては、prgb() 関数を使って指定された赤、緑、青の成分からなる色のインデックスを調べることができます。下記の例は標準のカラーパレットを使った 8 ビットのカラーデバイスで実行すれば 125 が表示されるでしょう。
red = prgb(255,0,0)
print(red)
Plua は Logo のような "タートル" ポインタをサポートしています。pwalk() と pturn() を使って線を描きながらディスプレイを歩き回ることができます。下記の例はディスプレイを消去し、ディスプレイの中心にカーソルを移動して小さな螺旋を描きます。
pclear() w,h = pmode() pmoveto(w/2,h/2)
for d = 1,20,1 do
pwalk(d) pturn(-40)
end
下記の例はビットマップを表示する方法を示しています。11000 はいくつかの Palm ROM に格納されている "Taxi" ビットマップのリソース ID です。
pclear()
bmp = popenres("Tbmp", 11000)
pdrawbmp(bmp)
pcloseres(bmp)
ディスプレイに関する最後の注意事項です: 画面の右端まで書いても折り返しはされず、画面の一番下の行に書いても画面はスクロールしません。
4.2. ユーザインタフェース
標準の PalmOS の UI コンポーネントは簡単に作成し、やり取りすることができます。これをおこなうための通常の方法はいくつかのコンポーネントを作成し、その後 UI イベントを待つイベントループに入ることです。以下の例がまさにこれを行っています:
textField = pfield(1,20,20)
lengthButton = pbutton("Length") pnl()
while 1 do
ev,id = pevent()
if ev == ctlSelect and id == lengthButton then
print(strlen(pgettext(textField)))
end
end
pfield() と pbutton() 関数はそれぞれ 1 行のテキストフィールドとボタンを作成します。pnl() 関数はカーソルをボタンの下に移動させます。無限ループの中で pevent() が呼ばれ、これで UI イベントが発生するまでアプリケーションは停止します。我々の例では、"Length" ボタンが押されたときにイベント(ctlSelect)が発生します。pevent() はイベント ID とコンポーネント ID (この場合はボタンの ID)を返します。プログラムは pgettext() を用いてテキストフィールドの内容を取得し、その長さを表示します。
注意: このプログラムは無限ループに入りますので、これを止めるにはアプリケーションアイコンをタップするしかありません。
以下の例は pinput()、palert()、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
アプリケーションにメニューを設定するためには、以下のように pmenu() を使用します。
pmenu({"O:Open", "Preferences", "-", "Q:Quit"})
メニューには 4 つのアイテムが現れるでしょう: 固定の "About Plua" アイテム、固定の区切り、"O" のショートカットがついた "Open" アイテム、ショートカットなしの "Preferences" アイテム、区切り、"Q" のショートカットがついた "Quit" アイテムです。制限事項: 現在のところ pmenu() は PalmOS 3.5 以降でのみ動作します(それ以前のバージョンは動的にメニューを設定することができません)。また、フルスクリーンモードでのみ動作し、同じメニューバーにひとつ以上のメニューを定義することはできません。pmenu() はいつでも呼び出すことができ、現在のメニューを新しいもので置き換えます。
メニューアイテムが選択された(About アイテムを除く)とき、pevent() から menuSelect イベントが返ります。上の例では、"Preferences" が選択されたとき、pevent() は menuSelect と 2 を返すでしょう。これは、ユーザーが定義した 2 つめのアイテムが選択されたことを意味します。
4.3. データベース入出力
PalmOS は本当のファイルシステムを持っていませんが、Plua は Lua バーチャルマシンに基礎となる OS が I/O をサポートしているように見せかけます。"標準出力(stdout)" 識別子はディスプレイにマッピングされ、"標準エラー出力(stderr)" 識別子はダイアログボックスにマッピングされ、stderr に書き込まれたものを表示します。
標準的なファイルは PalmOS の File Stream API を用いて実装されています。このため、Lua プログラムは通常通りファイルを開き、作成し、読み書きすることができます。データベースタイプやクリエータを知ることなく。以下の例がそのことを示しています:
f = openfile("MyOutput", "w")
write(f, "This is being written to a PalmOS stream database")
closefile(f)
データベース MyOutput が書き込み用に開かれ(もし存在しなければ作成されます)、文字列が書き込まれ、閉じられます。
PalmOS のデータベースを直接操作するための関数も存在します。もしそうしたいならば。それらは上記の "標準の Lua ディストリビューションからの拡張機能" セクションにリストされています。以下の例はすべての MemoPad レコードについて、それぞれのレコードの 1 行目を表示します:
f,n = opendb("MemoDB", "r")
for i = 0,n-1,1 do
openrec(f, i)
s = read(f, "*l")
print(s)
end
closedb(f)
read() 関数は Lua ライブラリの標準 I/O に属します。I/O 関数はストリームファイルにも標準のデータベースにも同じように働きます。標準のデータベースの場合、それぞれのレコードはサブファイルのように働き、すなわち、EOF 状態になったとき、最初から最後まで読み込まれたということです。データベースからの読み込みを続けるためには、次のレコードを開くために openrec() を呼び出さなければなりません。
opendb() に有効なモードは以下の通りです:
- "r": データベースを読み込み用に開きます。
- "r+": データベースを読み込みと書き込み用に開きます。データベースが存在しない場合には作成されます。この場合、クリエータは Plua のものが引き継がれ、タイプは常に 'data' となります。
- "w": データベースは書き込み用に開きます。データベースが存在しない場合には作成されます。この場合、クリエータは Plua のものが引き継がれ、タイプは常に 'data' となります。
最初の 2 つのモードには "b" を追加することができます("rb" や "r+b" というように)。これはバイナリモードを意味します。レコードがバイナリモードで読み込まれるとき、最後の文字が ASCII 0(ヌル文字)の場合この最後の文字は無視されます。この機能は、MemoPad のようなアプリケーションはいつもレコードの最後にヌル文字を書き込むため、なくてはならないものです。あるケースではヌル文字を無視しなければなりませんが、ほかのケースでは(バイナリデータのような場合)重要です。
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:
- ENOENT (2): そのようなファイルまたはディレクトリは存在しない
- EIO (5): 入出力エラー
- EBADF (9): 不正なファイル記述子
- ENOMEM (12): メモリ確保ができない
- EACCES (13): 権限がない
- EEXIST (17): ファイルが存在する
- EINVAL (22): 無効な引数
- EMFILE (24): ファイルが開かれ過ぎ
- EFBIG (27): ファイルが大きすぎる
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. シリアル入出力
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. 統一された入出力
ひとつ前のセクションでは正規のデータベース、ストリームデータベース、シリアル入出力を扱う方法を説明しました。それぞれの PalmOS の API について新しい関数を作る代わりに、Plua は標準的な Lua の関数(openfile、read、write、closefile)を使って統一された入出力操作をサポートしています。統一された入出力は VFS、TCP/IP、そして新しいシリアルマネージャによってアクセス可能なすべてのデバイスをサポートしています。下記のテーブルはサポートされているすべてのオプションをあらわしています。
タイプ | 構文 | 例 |
ストリームデータベース | openfile("name", "mode") | openfile("MyDatabase", "r+") |
Doc データベース | openfile("name", "mode") | openfile("MyDoc", "r") |
Memo データベース | openfile("memo:name", "mode") | openfile("memo:Data", "w") |
シリアルマネージャ | openfile("srm:device:baud:word") | openfile("srm:serial0:9600:8N1", "w") |
VFS ファイル | openfile("vfsn:path", "mode") | openfile("vfs0:/Palm/Programs/Readme.txt", "r") |
TCP ソケット | openfile("tcp:host:port") | openfile("tcp:www.lua.org:80") |
UDP ソケット | openfile("udp:host:port") | openfile("udp:host.com:7") |
4.6. バイナリデータ
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.7. ライブラリ
コンパイルされた Plua アプリケーションをライブラリとして使うことができます。便利な Lua の関数のセットがあり、他の開発者に提供したいとしましょう。すぐわかる方法はソースコードを配布することですが、他の選択肢もあります: メモ帳(MemoPad)や Doc ファイルに関数を書き、通常のアプリケーションと同じようにコンパイルします。例えば、生成された PRC が "MyLib" という名前ならば、他のアプリケーションは dofile("MyLib") とするだけで関数を読み込むことができます。あなたの "ライブラリ" を配布するには、コンパイルしたときに作られた "MyLib.prc" という PRC を配布します。
C ライブラリをビルドして Plua と連携させるための説明は、 libkit の例を参照してください。
[原文]