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
function on.charIn(char)
    if string.len(input) <= 25 then   -- limit of 25 chars
        input = input..char   -- concatenate
        platform.window:invalidate()   --screen refreh
function on.backspaceKey()
    input = string.usub(input,0,-2)  -- deleting last char

Bye !

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

  1. To be more flexible, I’ve found that in on.backspaceKey()

    The line:
    input = string.usub(input,0,string.len(input)-1)

    should be:
    input = string.usub(input,0,-2)

    The reason is that string.len() does not seem to handle strings with UTF-8 encoded characters above 0x7f correctly.

    For instance if the user types in “cos(30” then the degree symbol from the “?!” key, then types backspace to delete the degree symbol (UTF-8: c2 b0), when you execute the code: string.usub(input,0,string.len(input)-1), you get the full original string returned, it does not eliminate the degree symbol from the string.

    I have also found that even if the degree symbol is not the last character, the code string.usub(input,0,string.len(input)-1) returns the full original string.

    After some trial and error, I found that string.usub(input,0,-2) does indeed account for the UTF-8 encoding and removes the last character for the expanded character set.

Leave a Reply