Tag Archives: lua

FormulaPro v1.2 is here !

Hi,

I guess some of you already know about TI-Planet’s (mainly Jim Bauwens and I) FormulaPro. For those who don’t know (yet !), it’s been announced at the end of june (2012) here (english), here (french), on the tinspire google group… It’s a re-make&improved version of the original TI-89 “EEPro”, re-coded from scratch in Nspire-Lua (supporting any 3.x OS) : solve any kind of equations easily ! (right now, the default DB is about physics, but users can create their own set of formulas).
Well, I’ve updated it :D. It’s now in version 1.2 and here is the changes ( and a nice screenshot for you 😉 )
ImageChangelog :
– First, probably what you will notice the most : Animations ! Thanks to Levak’s animation framework 😉 So, this basically makes “screens” (frames) scrolling around, as seen in the .gif above.
– Re-did the Screen push/remove engine to work correctly with the animations.
– nSolve() used instead of solve() which makes the whole thing works on non-cas devices 🙂
– Rounding big numbers in the results
– Put the Reference part inside of FormulaPro (Tab key on home screen). We decided that we’ll stick with the “FormulaPro” name for now (and not EEPro-Nspire) since we won’t do the Analysis part very soon.
– Code reformatting
– Timer bugs fixes
– Resizing issues fixed
– List widget improvement -> last/first brings you to top/bottom when you press down/up. (<- respectively)
– ClearKey support for input widgets.
– Pre-calculate entered value in solver input if valid (so the user can enter calculations inside the input and it will work)
– Fixed bug about timer multiplier adjustment (depending on the version)
– support for both “-” symbols (minus and negative) inside solver

Download : 
http://tiplanet.org/forum/archives_voir.php?id=6034  or  https://github.com/adriweb/EEPro-for-Nspire/blob/master/FormulaPro.tns?raw=true

We’d love to hear any feedback Cheesy

 

The Nspire OS 3.2 has arrived !

Hi there ! Good news for Nspire Lua programmers, TI updated the Nspire OS to version 3.2, which is a great update for Lua scripting ! Indeed, it brings, along with some API changes, 2 main things : – An integrated SDK (Software Development Kit) to the Npire Computer Software, which enables you to program in Lua directly within the software. It features some auto-completion, syntax-coloring, a debugger etc. 🙂

Screenshot of the 3.2 Lua Script Editor
Lua Script Editor

– A Physics Engine… Yes ! You’ll now be able to create some great physics-based simulations for the Nspire, without having to code everything from scratch !

 

We encourage you to check out the Wiki (we are currently expanding it with the new functions) which has a page that summarizes all the changes to the API in OS 3.2, as well as the official API Documentation from TI. Have fun !

Starting with Lua programming on the Nspire

Hello and welcome to the tutorials index page!

You have several options to learn TI-Nspire Lua programming.

Inspired-Lua hosts several tutorials, but also links to other websites (like Steve Arnold’s). Here are some good resources:

We highly advise you to start…. by the beginning, and for that, click here for A-to-Z TI-Nspire Lua tutorials.

If you want to dive in the theory-based tutorials about Lua on the TI-Nspire, explaining how things actually work, head over here.

However, if you want to directly start Nspire-Lua scripting on a practice-based way, learning by example, you can go there.

Happy Lua programming on the TI-Nspire !

Leçon 1 : Premiers pas avec le Lua sur TI-Nspire

Aujourd’hui, Inspired-Lua vous propose une traduction et adaptation du guide de Steve Arnold que vous pouvez retrouver en cliquant ici. Depuis l’OS 3.0, les Ti-Nspire possèdent une nouvelle fonctionnalité en matière de programmation : le Lua. Ce dernier est un langage de programmation à la fois moderne et rapide. Les scripts écrits en Lua avec un simple éditeur de texte peuvent être convertis en .tns (format des documents TI-Nspire) à l’aide de TI-Nspire Scripting Tool . De tels scripts donnent de nouvelles possibilités étonnantes et puissantes pour la création de documents TI-Nspire afin d’apprendre ou d’enseigner.

Avec un peu d’expérience, les programmeurs de Lua peuvent créer d’incroyables programmes, auxquels l’imagination est la seule limite. A titre d’exemple, voici un tableau périodique des éléments réalisé par l’équipe de TI-Planet. Comme vous pouvez le voir, les possibilités sont énormes. Toutefois, même les débutants peuvent profiter des particularités offertes par le Lua dans des conditions plus limitées mais qui restent quand même puissantes. Ce tutoriel pour débutants offre de bonnes bases grâce auxquelles les élèves comme les enseignants pourront commencer à créer leurs propres documents !

L’objectif ici sera de commencer le Lua en affichant du texte. Des graphiques et des images dynamiques suivront plus tard.

Leçon 1.1: Premiers pas avec le Lua sur TI-Nspire

Pour cette première leçon, nous utiliserons le programme Oclua (On Calc lua) développé par Olivier Armand. Commencez par télécharger l’archive Oclua d’après ce lien . Ensuite, décompressez l’archive et transférez le fichier .tns sur votre calculatrice.

Gif Oclua
Oclua fonctionne à la fois sur la calculatrice et sur le logiciel TI-Nspire. Pour commencer à utiliser Oclua, ouvrez tout d’abord le fichier, puis créer une nouvelle application dans le classeur. (CTRL+I) Choisissez l’éditeur mathématique. Vous pourrez écrire le code en Lua ici. Ensuite, pour l’exécuter, vous n’aurez qu’à copier ce code et à le coller dans le premier onglet. (CTRL+A pour tout sélectionner, CTRL+C pour le copier, et enfin CTRL+V pour le coller) Rapide et facile à prendre en main, Oclua est idéal pour commencer à utiliser le Lua. Cette procédure est expliqué à travers l’image en gif ci-contre (Ignorez les deux lignes horizontales, elles sont dues au logiciel utilisé pour enregistrer l’animation – elles n’apparaîtront pas sur votre version du document). Toutefois, nous verrons par la suite que de meilleures solutions existent.

Les choses sérieuses commencent : nous allons créer votre première fonction en Lua ! Mais ne vous inquiétez pas, rien de bien compliqué. Tout d’abord, nous allons apprendre comment afficher du texte en Lua. Insérez une page éditeur mathématique comme nous l’avons vue. Recopiez-y le code ci-dessous

function on.paint(gc)
&nbsp; gc:drawString("hello world", 0, 20)
end

Notez que l’indentation (ajout d’espace/tabulation dans des scripts) n’est pas du tout obligatoire elle permet juste de mieux se retrouver dans de longues lignes de codes. (Ici elle n’a que peu d’intérêt mais il faut mieux prendre ces habitudes dès le départ)
Le Lua est un langage sensible à la casse c’est-à-dire que vous devez écrire exactement les fonctions comme montrées ici. Dans cet exemple, tout est en minuscules, excepté le « S » de String.
Vous devriez voir le texte « hello world » écrit en haut à gauche de la page. Voyons ce que l’on peut apprendre de cet exemple :

  • La structure pour définir une fonction est la même que dans beaucoup de langages.
function nom(argument)
&nbsp; quelques instructions
end
  • Dans notre exemple, nous avons utilisé une fonction standard du Lua appelée « on.paint ». Vous la rencontrerez dans la plupart (si ce n’est tous) les scripts en Lua. Lorsque vous utilisez cette fonction, elle affiche le texte sur l’écran.
  • « gc » signifie « graphics context ». (Contexte graphique :P) Il est utilisé quand des éléments graphiques de n’importe quel type sont employés. Vous pouvez voir dans cette fonction, l’unique ligne de code est définie par ce terme gc. Ne vous inquiétez pas, vous vous y habituerez vite !
  • La ligne d’instruction de cette fonction est assez explicative : gc:drawString (“hello world”,0,20). Dans le contexte graphique (gc) on va afficher (draw, dessiner) la chaîne de caractère (String) qui est “hello world” à la position (0,20) sur la fenêtre
  • Il faut savoir que le système de coordonnées à pour origine le coin en haut à gauche de l’écran. Ainsi, les coordonnées ne doivent pas être négative pour afficher correctement du contenu graphique. Dans notre exemple, le point choisi est (0,20). Si l’ordonnée était inférieure, le texte serait coupé.
Vous devriez prendre quelques minutes pour découvrir cette première fonction et appliquer ce que vous venez d’apprendre. Essayez de déplacer le texte afin de comprendre le système de coordonnées. Essayez de centrer votre texte. Vous en apprendrez ainsi plus sur les dimensions de l’écran.
Cependant, vous verrez plus tard qu’un texte centré sur une plateforme (calculatrice, ordinateur) n’est pas forcément adapté à une autre. Mais alors, comment faire ? Nous allons voir cela dans la suite de notre cours ! En attendant, amusez-vous bien ! 🙂

Mais pourquoi ?

Il est peut-être temps de s’arrêter un instant et de se demander – Pourquoi s’ennuyer à faire cela ? Il y a d’autres façons beaucoup simples pour afficher du texte à l’écran.
Deux propriétés très importantes d’une fenêtre en Lua sur TI-Nspire, par opposition à une fenêtre classique dans l’éditeur mathématique :
  • Cliquez sur n’importe quelle fenêtre en Lua. Déplacez-la, essayez de l’éditer. C’est impossible. Le texte que vous affichez ne peut pas être édité par l’utilisateur du document. Dans l’éditeur mathématique, l’utilisateur peut bien sur changer – et en effet détruire – tout ce que l’auteur a pris le temps de faire. En plus, comme on peut le faire dans l’éditeur, le texte affiché peut être à la fois dynamique et statique. Donc on peut facilement créer de puissants outils d’apprentissage tout comme on peut le faire avec l’éditeur, mais dans un environnement plus sécurisé.
  • Dans la seconde partie de cette leçon, vous apprendrez à contrôler la taille de la police, la couleur et le style, et comment facilement centrer le texte sur une ligne, et même au centre de la fenêtre. En Lua, on a un contrôle significatif de la façon dont le texte est affiché – bien plus qu’en utilisant l’éditeur. En terme de couleurs, vous avez accés à des millions de couleurs !

Leçon 1.2: Un peu plus intéressant ?

Bon, retour au travail. Prêt pour la suite ?
Si vous n’êtes pas sur la page 1.2 d’Oclua, retournez-y. Nous allons ajouter quelques lignes à notre script on.paint.
function on.paint(gc)
&nbsp; gc:setFont("sansserif", "b", 12)
&nbsp; gc:setColorRGB(158, 5, 8)
&nbsp; gc:drawString("Ceci est mon texte", 20, 20)
end
A nouveau, étudiez ces quelques lignes – essayez de modifier les différentes valeurs. Vous allez vite vous rendre compte que setFont possède trois entrées :
  • la famille : « serif » ou « sansserif »
  • le style : « b » pour bold (gras) ; « r » pour regular (normal) ; « i » pour italic (italique) ; « bi » pour bold italic (gras et italique)
  • la taille

setColorRGBpermet d’accéder simplement à une multitude de couleurs : RGB signifie Red (rouge ; 255,0,0) Green (vert ; 0,255,0) Blue (bleu ; 0,0,255). Il y a de nombreuses couleurs entre ces valeurs, ou vous pouvez accéder à la liste en ligne ou juste télécharger le PDF que j’utilise. Mes couleurs fétiches sont burgundy (158, 5, 8 )> et navy (20, 20, 138), et qui vont très bien ensemble ! C’est vraiment mieux qu’une simple palette de 9 à 15 couleurs actuellement disponible sur TI-Npire !Si vous n’êtes pas perdu en lisant ce cours, c’est que vous êtes sur la bonne voie ! Nous allons finir cette leçon par une notion importante en Lua : centrer le texte. Nous en profiterons pour introduire les variables locales et globales.

Le Lua dispose de toutes sortes de commandes très utiles, comme platform.window:heigth() et platform.window:width().

Comme vous pouvez le deviner, ces commandes permettent de récupérer les valeurs actuelles de la fenêtre. Ainsi, platform.window:heigth() permet de connaître la hauteur de l’écran tandis que platform.window:width(). permet d’en connaître la largeur. Une nouvelle fois, faites bien attention aux majuscules et aux espaces ! Ici, tout est en minuscules.
Si on stock ces valeurs dans des variables, que nous appellerons w et h (pour width et height respectivement), nous pourrons les réutiliser hors de la fonction et dans un script plus grand. Mais nous aurons l’occasion d’y revenir un peu plus tard.

Voici deux nouvelles fonctions tout aussi importantes : getStringHeight et getStringWidth. Comme leurs noms l’indiquent, elle permettent de déterminer la largeur et la hauteur d’une chaîne de caractères.

function on.paint(gc)
&nbsp; local h=platform.window:height()
&nbsp; local w=platform.window:width()
&nbsp; gc:setFont("sansserif", "b", 12)
&nbsp; gc:setColorRGB(158, 5, 8)
&nbsp; local sw = gc:getStringWidth("Ceci est mon texte")
&nbsp; local sh = gc:getStringHeight("Ceci est mon texte")
&nbsp; gc:drawString("Ceci est mon texte", w/2 - sw/2, h/2 + sh/2)
end
On commence par définir les dimensions de la fenêtre avec w et h. On peut aussi obtenir les dimensions de la chaîne de caractères
Maintenant, pour centrer la chaîne :
  • Horizontalement : on prend le centre de la fenêtre (w/2) puis on recule de la moitié de la largeur de la chaîne de caractères (w/2 – sw/2).
  • Verticalement : on suit la même procédure, à une différence près : verticalement, on compte à l’envers en Lua : plus on va bas, plus le nombre est grand ; plus on va haut, plus il est faible ! (h/2 + sh/2)

Et maintenant ?

C’est tout pour cette leçon – à vous de jouer !
Pourquoi ne pas essayer d’aligner votre texte à droite ? Jetez un œil au centrage que nous venons de réaliser et inspirez-vous-en pour aligner le texte à droite et à gauche.
Et pour le placer en haut ou en bas ? Comment feriez vous ? Essayez différentes couleurs !Dans la prochaine leçon, nous apprendrons à donner vie à notre texte et à utiliser une table pour organiser plusieurs lignes de texte de façon structurée sur votre page !

How to have a nice little “input” function in Lua…

(improved version of Nick Steen’s website’s example)

You could be quite surprised by the fact that there isn’t any native way to have a keyboard text input function on the Nspire Lua API. Indeed, it’s a little weird since this is often used for many types of programs (whether in games for typing the username, or other apps to type user data etc.).

Anyway, don’t worry, you can program it yourself with a little piece of code to add to your script ! It actually catches the keypresses with the on.charIn function, and stores what the user types in a string (appending it). You then just have to display this string on the screen and that’s all.

If you want the user to be able to delete some letters, just add some code to the on.backspaceKey function, and that’s all !

In the example below, we set a character limit to 25, but that’s totally up to you.

Well, here’s the complete code ready to be used :

input = ""   
 
function on.paint(gc)
    gc:drawString(input,5,5,"top")  -- display string
end
 
function on.charIn(char)
    if string.len(input) <= 25 then   -- limit of 25 chars
        input = input..char   -- concatenate
        platform.window:invalidate()   --screen refreh
    end
end
 
function on.backspaceKey()
    input = string.usub(input,0,-2)  -- deleting last char
    platform.window:invalidate()  
end

Bye !

End of the Nspire Lua Contest

Some time ago, we announced a contest : Nspire programming in Lua . This was a large scale contest since the total sum of the prizes was of about € 750, including three awesome TI-Nspire CAS CX !

The contest is now over !

With not less than 14 Lua programs submitted, we think this is a great success for a language so “new” on the TI-Nspire calculator!

We would like to thank all participants, regardless of their results!

The judges (Levak, Critor and myself) are going to analyze everything you have done in the coming days, and the results should be there soon !

In the meantime, here is the list (just name + Screenshot) of entries received.

We recall that these programs, unless otherwise stated on the download page are subject to the following license : CC BY-SA 2.0 . Not respecting the terms of this license will result in legal consequences. The authors of the respective programs can change their licence at their will by contacting us by e-mail, of course.

Games : 7


Bobby Carrot – – – – Loïc P.

Image
Labyrinthe – – – – David L.


Reversi (Othello) – – – – Deep Thought.

Image
MasterMind – – – – Nick V.


TI-Cran – – – – Julien R.


Nspired Phoenix Lua – – – – Florent D.


Tactical Wars CX – – – – Rehn C.

Mathematics: 4


TabVar 3 – – – – JayTe.


LuaCS – – – – Jonathan L.


LogoMagic – – – – Jim B.


ABA Logique – – – – Loulou54.

Physics/Chemistry: 3


Planétarium – – – – Bastien V.

Image
FormulaOne – – – – Naji A.

Image
Formules de Chimie – – – – Paul J.

 

Well, while waiting for the results to come, fell free to comment on these programs !

Once again, congratulations to all !

Graphical chemical reaction analysis (Nspire Lua)

(By the way, don’t think that I’m talking about me at the third-person : this is a translation I’ve done of the original TI-Planet article 😉 )

Another exclusive TI-Planet program today!

Our dear member Adriweb, after releasing the Chemical Reaction analysis program for TI-83 + / 84 + ( http://tiplanet.org/forum/archives_voir.php?id=1308 ) , has now programmed its Nspire version ! This is a first on this calculator, especially as it profits from the main new feature offered by the OS 3 : Lua Scripting, like the program TabVar 3, presented yesterday.

This .tns document actually consists of two parts:

-> You run the program (TI-Basic) avancement() and follow the steps to provide information on the chemical reaction to be studied.

-> Go to the next tab and watch the table drawn in detail and in color (Nspire CX only) !

A screenshot?

1320062663avancementnspire.jpg

This program is open source and licensed under the Creative Commons BY-SA 2.0.

Source code : https://github.com/adriweb/Tableau-d-Avancement-LUA/blob/master/TableauAvancement.lua

Link the topic of TIPlanet (more info + download ….): http://tiplanet.org/forum/viewtopic.php?f=43&t=8385

Download link directly : http://tiplanet.org/index.php?mod=archives&ac=voir&id=3754

(Click on the “Telecharger” button)

TI-Planet.org : the website that creates smart programs !

By the way, Happy Halloween;-)

TabVar v3, the ultimate function analysis tool !

Hi everybody,

Today is a great day!

Indeed, for the lucky owners of a TI-Nspire with OS >= 3, JayTe has made an awesome program that combines the simplicity of the TI-Basic with the power of Lua, for our pleasure …
Here is … TabVar 3 !
Yes, the famous program that makes all your work in depth and draws a beautiful variations table (“Tableau de variations” in french), the perfect function analysis tool !!

“Hmm, Doesn’t that exist already ?” You might say.
It does, actually, The idea is not new.
Chronologically, it has indeed been made by Adriweb, the first one for Nspire, and then, TabVar v1 and v2, by JayTe, whose engine is based originally on Adriweb’s program, but everything was done much further by integrating more and better function analysis functions and algorithms.

This program exceeds by far its competitors. No other .tns could can hope to compete so far.

The outstanding feature of this version is that this program (launched exclusively on TI-Planet) deeply uses the features offered by the OS 3 by integrating a dynamic Lua script for an optimal view of the variation table, which for once is completely graphical. No need to have weird graphical hacks to correctly display what we need …

We will not make you wait any longer… Here’s a screenshot of TabVar:

and details of preliminary calculations (click for larger image):

So far, you will not find a more reliable engine (although nothing is perfect, of course, complex functions can be studied incompletely …)
You can, for example, try fairly complex functions, such as polynomial, rational, with or without asymptote(s) and strange behavior with or without limits …
In short, for a high school student (or other!) It’s more than perfect 🙂

Download link: http://tiplanet.org/forum/archives_voir.php?id=3751

Thank you Who?
Thank you Jayte!

Do not forget, this program is by far the most reliable and practical for the studies of functions ..
A small screenshot to prove that point ?
(Example : TabVar v3 against a competitor for the same function f(x)=1/x)

Yep, do not trust bad imitations if you want a good grade!

TI-Planet.org, the reference website to find everything you need and what you dream of!

Save a high score (or anything) without cheating possibility !

In this tutorial we’re going to take a look at a pretty interesting feature of the TI-Nspire framework in Lua : save and restore any kind of data directly in Lua, that lets us playing around with a high score for a game or any other configuration data for a more complex program.

Example : You just released a wonderful game. You’d like to share it with your friends, that way they can challenge you thanks to your high-scores system. But how is that working?

The first way you could think of is to use the var API. Therefore, we save the high score in the document as a global variable (math variable).

Your high score system is done ! Hum … wait a second, one of your friend managed to score 10 000 000 points to your game ! What the heck ? He simply modified the global variable you’re using as an high score, since it’s freely accessible via a Calculator application. Here, it is not hard to cheat !

A second way is to protect the first one by using math.eval() which lets us launch any TI-Basic instruction, as the Lock one for example. Then, if we do like so :

math.eval("Unlock highscore")
var.store("highscore", highscore)
math.eval("Lock highscore")

our high score variable will be write protected. But, since Lock is a TI-Basic command, it can be launch outside the Lua program. Things aren’t going to be better.

What about looking for a specific Lua command ? Actually, there is var.monitor() that probes a specified variable and checks if this variable will be changed. If so, on.varChange() event is called. This lets us to control any variable changes.

Here is an example :

function on.create()
  if not var.recall("highscore") then
    highscore = 0
    var.store("highscore", highscore)
  end
  var.monitor("highscore")
end
 
function on.varChange(list)
  for k, v in pairs(list) do
    if k == "highscore" then
      if var.recall(k) ~= highscore then
        return 1 -- it is an external change, block modifications
      else
        return 0 -- it is an internal change, allow modifications
      end
    end
  end
  return 0 -- allow modifications of other monitored variables if any
end

This code will disallow any external modification of the highscore variable, with the following error message :

Cannot accept change : Invalid input

Obviously, if you have to do this for multiple variable, for example configuration data, don’t do this since it is a heavy and repetitive method …
It is at this moment that we take a look to the documentation. We can see two trivial events : on.save() & on.restore().
In fact, this event couple does exactly what we expected to do from the beginning !

Actually, when the widget get closed (when we close the document, or copy/cut the widget) the on.save() event is called. You have to define on.save() to make it return any kind of value (boolean, number, string, table etc …). The next time the widget will open (when we open the document, or paste the widget), the on.restore() event will be called, with the data returned by on.save() as the parameter !

Here we are, easy-going :

function on.save()
  return highscore
end
 
function on.restore(data)
  if type(data) == "number" then
    highscore = data
  end
end
 
function on.create()
  if not highscore then
    highscore = 0 -- first time we initialize highscore
  end
end

Great TI-Nspire Lua Contest 2011

The contest is now over, thanks to everybody who participated !

 

The websites Inspired-Lua and TI-Planet, with our partner R. JARRETY (where you can order your TI calcs with great TI-Planet prices), are organizing a new, great contest  in  a scale never seen before !

First, for the first time in the history of our site, the competition crosses the borders of France and whatever your country of residence, you can take part in it !

Moreover, the prize is absolutely amazing and unprecedented :
-> 3 TI-Nspire CAS CX <- , so that’s three times more likely to win!

 

No, you’re not dreaming !

You only have to create a Lua program for TI-Nspire in connection with one of these three categories:

  • Mathematics
  • Physics and Chemistry
  • Games

You’ll need an Nspire OS (or software) 3.0 or later (preferably 3.0.2 – see links).

The only requirement is that your program is suitable for a French user. If your program displays text, use single common words in a foreign language is tolerated.

Use Google Translate if needed.

To participate, simply send an email to    info @ tiplanet . org by November 7th, 2011 23:59 GMT +2 (DST French) with these information :

  • your full name
  • your full address
  • a valid email address
  • which is *only* used to send your reward

  • the chosen category
  • an archive as an attachment

The attached archive will contain:

  • the program format ‘tns’
  • source code
  • a description in a file ‘readme.txt’
  • possibly documentation (format and contents are free)

You can submit only one program for the competition, so you can participate in only one category. Choose the right one wisely !

However, it is perfectly possible to update an already submitted or even change the program or the category you chose just by sending a new email to participate, since only the last one received will be taken into account.

Good luck to everybody !

Links:

Official Rules
Inspired-Lua (documentation & Lua ressources)
TI-Planet (help & resources)
Lua generator, “Luna”
OS 3.0.2 for TI-Nspire
OS 3.0.2 for TI-Nspire CAS
OS 3.0.2 for TI-Nspire CX
OS 3.0.2 for TI-Nspire CX CAS
TI-Nspire 3.0.2 Software student for PC (free for 30 days)
TI-Nspire 3.0.2 Software student for Mac (free for 30 days)
TI-Nspire 3.0.2 Software teacher for PC (free for 90 days)
TI-Nspire 3.0.2 Software teacher for Mac (free for 90 days)