Вы находитесь на странице: 1из 11

Lua Programming - Hackspire

http://hackspire.unsads.com/wiki/index.php/Lua_Programming

From Hackspire
The TI-Nspire allows, since OS v3.0, programming with the Lua language through a hidden application "TI.ScriptApp".
This page describes how to setup a Lua development environment and documents the currently known Lua functions for the
Nspire, and a brief description of how to use the functions.

File:See-the-link-here
The Hexadecimal view of all
the api functions, readable in
an extraded phoenix.raw file
(http://i.imgur.com
/LTznh.jpg)

1 Prerequisites
2 The following documentation is now maintained in the "Inspired Lua Wiki".
3 Please go there in order to have a full detailed documentation based on TI's information.
3.1 API
3.2 Standard Library
3.3 Concepts and Basics
3.4 GC (as in Graphics Context)
3.5 platform
3.6 cursor
3.7 document
3.8 clipboard
3.9 locale
3.10 image
3.11 timer
3.12 toolpalette
3.13 var
3.14 Events
3.15 D2Editor
3.16 External Links

1 / 11

2015. 05. 27. 10:43

Lua Programming - Hackspire

http://hackspire.unsads.com/wiki/index.php/Lua_Programming

Lua is only supported starting from OS v3.0.1. Creating Lua scripts is currently not officially supported by TI, you need one of the following third-party tools to
convert Lua scripts to TI-Nspire documents:
For any OS:
Luna (http://www.ticalc.org/archives/files/fileinfo/441/44113.html) (cross-platform) [forum (http://www.omnimaga.org/index.php?topic=9807.0) ]
For OS < 3.0.1: these tools won't work with the OS 3.0.2 since the format used is now blocked
LUAtoTNS.sh (http://www.ticalc.org/archives/files/fileinfo/437/43704.html) (bash script, works on Linux, Mac OS and Unix, or Windows + Cygwin or
Windows + MSYS).
maketns.py (http://www.mirari.fr/KbOD) (Python script, cross-platform)
lua2ti (http://www.omnimaga.org/index.php?action=downloads;sa=view;down=651) (Windows + .NET Framework v4.0)
lua2ti_linux (http://www.omnimaga.org/index.php?action=downloads;sa=view;down=652) (Linux (No longer requires Mono, it is now a native Linux
binary!))
You may also want to install Lua on your computer (http://www.lua.org/download.html) : luac -p can be used to check the syntax of your script before running
it on a TI-Nspire or an emulator.

Note: Neither the io nor os libraries are present for the TI-Nspire, which seems to be running a light version of Lua 5.1.4.
Here's a dump of a lot of functions available in the API : Link to the dump (http://adriweb.free.fr/upload/ti/dump.html) .
2 / 11

2015. 05. 27. 10:43

Lua Programming - Hackspire

http://hackspire.unsads.com/wiki/index.php/Lua_Programming

( This has been taken from a WoWWiki page (http://www.wowwiki.com/Lua_functions) - See the full, official documentation here (http://www.lua.org/manual
/5.1/manual.html) )
_G - Global Variable - A global variable (not a function) that holds the global environment (that is, _G._G = _G). Lua itself does not use this variable;
changing its value does not affect any environment, nor vice-versa. (Use setfenv to change environments.) - taken from Lua docs
assert(value[, errormsg]) - asserts a value evaluates to true. If it is, returns value, otherwise causes a Lua error to be thrown.
getfenv(function or integer) - Returns the table representing the stack frame of the given function or stack level.
getmetatable(obj, mtable) - Returns the metatable of the given table or userdata object.
next(table, index) - Returns the next key, value pair of the table, allowing you to walk over the table.
newproxy(boolean or proxy) - Creates a userdata with a sharable metatable.
print - print () - Receives any number of arguments, and prints their values to stdout, using the tostring function to convert them to strings. print is not
intended for formatted output, but only as a quick way to show a value, typically for debugging. For formatted output, use string.format. - taken from Lua
Docs
select(index, list) - Returns the number of items in list or the value of the item in list at index.
setfenv(function or integer, table) - Sets the table representing the stack frame of the given function or stack level.
setmetatable(obj, mtable) - Sets the metatable of the given table or userdata object.
tostring - tostring (e) - Receives an argument of any type and converts it to a string in a reasonable format. For complete control of how numbers are
converted, use string.format. If the metatable of e has a "__tostring" field, then tostring calls the corresponding value with e as argument, and uses the
result of the call as its result. - taken from Lua Docs.
type(var) - Returns the type of variable as a string, "number", "string", "table", "function" or "userdata".
unpack(table[, start][, end]) - Returns the contents of its argument as separate values.
xpcall(func, err) - Returns a boolean indicating successful execution of func and calls err on failure, additionally returning func's or err's results.

This part will explain you how the Lua actually works inside the OS and help you to figure out what you're doing when you write a script for the TI-Nspire.
Before reading this, you have to know all about the Lua basics.
The Lua is an interpreted script language which means that it isn't as fast as ASM/C programs, but is still better than the TI-BASIC. One good thing is that this
language is in a complete harmony with the OS with basic events and a powerfull graphic context. First, we have to understand how this works. Basicly the
script is launched before the executive engine. This means that we can neither evaluate expressions nor use some of the standard API (like platform, var) until
the engine is launched. Here is a call summary :
Launch string library

3 / 11

2015. 05. 27. 10:43

Lua Programming - Hackspire

http://hackspire.unsads.com/wiki/index.php/Lua_Programming

Launch math library


...
Open and launch User's Lua script
...
Launch var API (store, recall, ...)
Launch platform API (window, gc, ...)
...
Link events (pseudo code)
while(Exit)
------- Some OS routines here
---- Begin of Event link
buffer:captureDataFromKeyPad()
if buffer.charInput ~= "" then
on.charIn(buffer.charInput)
buffer.charInput= ""
end
if buffer.arrowKey ~= "" then
on.arrowKey(buffer.arrowKey)
buffer.arrowKey = ""
end
----- etc ...
if platform.window.isInvalidate then
platform.gc():purge()
on.paint(platform.gc())
platform:paint()
platform.window.isInvalidate = false
end
----- End of Event link

---

(N) some underground routines to catch events


(N)

--

(N)

--

(N)

--

(N)

-- (N) Empty buffer before starting to draw


-- save all the things we have to draw
-- (N) draw all those things
-- say that the window has been drawn

end

Note : the (N) commented line only indicates the meaning of the routine. Those functions don't really exist.
Now we can understand how everything is linked, just by a main loop. This helps you to understand that you don't have to code a loop yourself, because the
screen wouldn't be refreshed. This also helps to see when the screen gets refreshed. In other words, we cannot use niether gc nor platform.gc() (which are the
same) in order to draw somthing on the screen if we are outside of on.paint() (except if your outside function is called within on.paint() ). This also means that
we don't need to pass gc as parameter, because we can rather use platform.gc() for any functions called within on.paint(). This is exactly what the
BetterLuaAPI library for Nspire (https://github.com/adriweb/BetterLuaAPI-for-TI-Nspire/blob/master/BetterLuaAPI.lua) does.
Here is an example of a simple Lua program that displays a message only when a key is pressed (and let the screen blank otherwise).
function on.paint(gc)

4 / 11

2015. 05. 27. 10:43

Lua Programming - Hackspire

http://hackspire.unsads.com/wiki/index.php/Lua_Programming

if message then
gc:setFont("sansserif", "r", 10)
-gc:drawString(message, 0, 0, "top")
-message = nil
-timer.start(1)
-- start a
end

initialize font drawing


display the message at (0, 0) coordinates
erase the message
timer to exit on.paint() but keep in mind that we have to redraw the screen

end
function on.timer()
timer.stop()
platform.window:invalidate()
end
function on.charIn(ch)
message = "Hello World !"
platform.window:invalidate()
end

-- store a message
-- force display

When you open the document, the script is read once. It initializes and overwrites all the functions and globals with the ones you defined. Thus, message is nil.
Once the on.paint() event is called, message is nil, thus, nothing is done. When you press a key that calls on.charIn() (see below for more information),
message is now "Hello World" and we tell the platform that the screen has to be refreshed. Then, on.paint() is called again, message is not nil then we display
it, erase message and launch a timer. Why is that ? Because if we call platform.window:invalidate() right there, we won't refresh the screen. Why again ? Just
look at the pseudo-code above. We set the window as drawn after each call of on.paint(). Thus a timer is necessary to manually recall on.paint() and exit the
on.paint() function to draw the screen. When the timer is ended, on.timer() is called and we refresh the screen. The screen is then redrawn but there is nothing
to draw because message is nil. Thus, the graphic context lets the screen blank.

Note: You need to add gc: before each of these commands in order to use them. ex. gc:setAlpha(...). You can also call gc like this :
platform.gc():setAlpha(...). Then you can use the gc library in a function where gc is not passed as an argument. but this function *has* to be called within
on.paint(gc)
The maximum screen resolution available to Lua programs is 318 by 212 pixels.
begin clipRect(?, x, y, width, height) drawArc(x, y, width, height, start angle, finish angle) Note, to draw a circle, use drawArc(x - diameter/2, y - diameter/2, diameter,diameter,0,360) where
x and y are the coordinates of the middle.
drawImage(image,x,y) First argument in format TI.Image, x and y the coords.
drawLine(xstart, ystart, xend, yend) Draws a line starting at the point (xstart,ystart) and ending at the point (xend, yend)
drawPolyLine(int list1 [,int list2, .., int listN]) Draws a shape from a list contaning successively the x and y coordinates of each point the line have to
draw.
5 / 11

2015. 05. 27. 10:43

Lua Programming - Hackspire

http://hackspire.unsads.com/wiki/index.php/Lua_Programming

For example
drawPolyLine({0,0, 0,100, 100,100, 100,0, 0,0})

and
drawRect(0,0,100,100)

do the same. If there are multiple argument (which can be 4 elements list to represent lines), each list has to contain an even number of element.
drawRect(x, y, xwidth, yheight) Draws a rectangle at (x,y) with the x side being xwidth long and the y side being yheight long
drawString(string, x, y, PositionString) PositionString is the strings anchor point and can be bottom, middle, or top.
fillArc(x, y, width, height, start angle, finish angle) see drawArc
fillPolygon(int list1 [,int list2, .., int listN]) see drawPolyLine
fillRect(x, y, width, height) see drawRect
finish getStringHeight(string)
getStringWidth(string)
isColorDisplay Bool (Read-only) Returns 1 if color, 0 if not.
setAlpha(int) - where the argument is an int between 0 and 255. Sets the transparency.
setColorRGB(red, green, blue) RGB values are integers, from 0 to 255.
setFont(font, type, size), with font : {sansserif, "serif", ..}, type {b, r, i}, size(int)
setPen(size, smooth) size {thin, medium, "thick"}, smooth {smooth, "dotted", "dashed"}

These are mainly read-only. These work by writing "platform." in front of them. Example : "platform.window:invalidate()"
apilevel() : Returns the version of the API. Currently (OS 3.0.1) returns 1.0.0.
window
*width() - Returns the width of the window. Ex : platform.window:height()
*height() - Returns the height of the window
*invalidate() - Repaints the window (it calls on.paint(gc))

6 / 11

2015. 05. 27. 10:43

Lua Programming - Hackspire

http://hackspire.unsads.com/wiki/index.php/Lua_Programming

isDeviceModeRendering() Returns true or false whether the unit is "rendering" or not


gc - Other way to call gc. Use it like that : platform.gc():setAlpha(...) for example. This is useful when you're in a function outside on.paint(gc) (but this
function has to be called within on.paint(gc).
isColorDisplay() Returns true if the unit the code is being run on has a color display (-> Nspire CX), and false otherwise.

hide() - hides the cursor (mouse pointer)


set(string) - string can be one of those : (interrogation, crosshair, text, pointer, link select, diag resize, wait busy, hollow pointer, rotation, pencil, zoom
box, arrow, zoom out, dotted arrow, clear, animate, excel plus, mod label, writing, unavailable, resize row, resize column, drag grab, hand open, hand
close, hand pointer, zoom in, dilation, translation).
show() - Shows the cursor on screen

markChanged() - Flag the document as "changed" so the user has to save it after using it.

addText(string) - adds plain text to the clipboard


getText() - gets the plain text contained in the clipboard

name() - Returns the current language the calculator is set in, formatted as ISO-639 (i.e : "fr", "en", "it" ...).

__gc() - Do not use ! Causes crash : (Invalid memory access of location 0x0 eip=0x465cc7ac / Bus error) but thats probably just when calling in TI's
emulator.
copy(image, width, height) - returns a new Image which has a new scale. Width is the final width, Heigth, the final height of the image.
To make a relative scale, use image.copy(image, scaleX * image.width(image), scaleY * image.height(image))

7 / 11

2015. 05. 27. 10:43

Lua Programming - Hackspire

http://hackspire.unsads.com/wiki/index.php/Lua_Programming

height(image) - returns the height of the image given in parameter


new(string) - Creates a new image from the string given in parameter (see TI.Image). Call it with img = image.new("...")
width(image) - returns the width of the image given in parameter

getMilliSecCounter() - Returns the amount of milliseconds elapsed since last calculator reboot. (in TI's Computer software, returns an absolute negative
time)
start(int) - Starts a timer with 1 second.
stop() - Stops a timer

enable(string)
enableCopy()
enableCut()
enablePaste()
register(table)

list() - returns a list of all the variables in the entire Activity


monitor(var) - linked to event on.varChange
recall(string) - returns the variable value which name is given in parameter
recallstr(string) - returns the variable value converted to string which name is given in parameter
store(string, value) - store in the variable, which name is given in parameter, the value
unmonitor(var) - stops monitoring a variable

on.paint(gc) is called when the GUI is painted. 'gc' is the Graphics Context (see above)
on.resize() is called when the window is rezised
on.timer() is called when the timer has been finished. Here an example of using timer to play an animation :

8 / 11

2015. 05. 27. 10:43

Lua Programming - Hackspire

http://hackspire.unsads.com/wiki/index.php/Lua_Programming

x = 1
animating = false
function on.paint(gc)
gc:setFont("sansserif", "r", 10)
gc:drawString(tostring(x), 0, 0, "top")
if animating then
x = x + 1
timer.start(0.5)
end
end
function on.charIn(ch)
animating = not animating -- switch state
platform.window:invalidate() -- recall graph engine
end
function on.timer()
timer.stop()
platform.window:invalidate() -- recall graph engine
end

on.arrowKey(key) is called when an arrow key from the clickPad/TouchPad is pressed (right, left, up, down)
on.arrowLeft() is called when the left arrow is pressed
on.arrowRight() is called when the right arrow is pressed
on.arrowUp() is called when the up arrow is pressed
on.arrowDown() is called when the down arrow is pressed
on.up() -- probably for the touchpad up motion
on.down() -- probably for the touchpad down motion
on.enterKey() is called when the enter key is pressed.
on.escapeKey() is called when the escape key is pressed.
on.tabKey() is called when the tab key is pressed.
on.deleteKey() is called when the delete key is pressed.
on.backspaceKey() is called when the clear key is pressed.
on.returnKey() is called when the return key is pressed.
on.contextMenu() is called when the combo-key Ctrl Menu is pressed.
on.backtabKey() is called when the combo-key Maj Tab is pressed.
on.clearKey() is called when the combo-key Ctrl Clear is pressed.
on.help() is called when the combo-key Ctrl H is pressed.

9 / 11

2015. 05. 27. 10:43

Lua Programming - Hackspire

http://hackspire.unsads.com/wiki/index.php/Lua_Programming

on.charIn(string) is called when the Nspire detects a non arrow key being pressed. ch is the character it detect. If you want to auto start an event in the
file linked to key r(like a reset) put on.charIn(r) where you want. This Lua program lets you display the value of a valid non arrow key :
c =
function on.charIn(ch)
c = ch
platform.window:invalidate() -- we force the screen draw
end
function on.paint(gc)
gc:setFont(sansserif, r, 10)
gc:drawString(c, 0, 0, top)
end

on.blink() ? is called when the focus is lost on the page (like launching the document, changing page etc...)
on.create() ? is called when the script gets created.
on.deactivate() ? is called when the focus is lost on the page (like launching the document, changing page etc...)
on.activate() ? is called when the focus is on the page (like launching the document, changing page etc...)
on.mouseDown(x, y) is called when we press the left mouse button. X and Y are the pressed point coordinates.
on.mouseUp() is called when we release the left mouse button.
on.mouseMove() is called when the mouse moves
on.grabDown() ? (software only ?)
on.grabMove() ? (software only ?)
on.grabUp() ? (software only ?)
on.rightMouseDown() ? (software only ?)
on.rightMouseUp() ? (software only ?)
on.cutEnabled() ? (software only ?)
on.copyEnabled() ? (software only ?)
on.pasteEnabled() ? (software only ?)
on.cut() ? (software only ?)
on.copy() ? (software only ?)
on.paste() ? (software only ?)

10 / 11

2015. 05. 27. 10:43

Lua Programming - Hackspire

http://hackspire.unsads.com/wiki/index.php/Lua_Programming

newRichText() creates a new RichText object (default values : x, y, width, height = 0)


resize(width, height)
move(x, y)
setText(string)
getText() returns the RichText value
setReadOnly(bool) bool : true/false : If true, the content becomes read-only, i.e. non-editable.
setFormattedText() - ?
Example of a valid function using the D2Editor
function createRichTextBox
box = D2Editor.newRichText()
box:move(50, 50)
box:resize(50, 50)
box:setText("Hello World !")
end

An interesting page about LUA code optimization, that can be really useful, especially for calculators : Lua Performance (http://trac.caspring.org
/wiki/LuaPerformance)
Retrieved from "http://hackspire.unsads.com/wiki/index.php/Lua_Programming"
This page was last modified on 15 August 2011, at 08:58.
Content is available under GNU Free Documentation License 1.2.

11 / 11

2015. 05. 27. 10:43

Вам также может понравиться