iLua Toolbox Help

A Glimpse of iLua Toolbox In-App Documentation

iLuaBox  ·  iLua Toolbox  ·  Socket Toolbox  ·  SQL Toolbox  ·  Vox Toolbox

1 - Toolbox Reference

The iLua Toolbox adds several utility functions for controlling iLuaBox core behaviour such as screen mode, printing to the input screen, and reading the device file directory.

1.1 – Functions

ilua.attributes (filepath [,aname])

Returns a table with the file attributes corresponding to filepath (or nil followed by an error message in case of error).

If the second optional argument is given, then only the value of the named attribute is returned (this use is equivalent to ilua.attributes(filepath).aname, but the table is not created and only one attribute is retrieved).

Attribute mode is a string, all the others are numbers, and the time related attributes use the same time reference of os.time. The attributes are described as follows:

  • "mode": string representing mode type (file or directory)
  • "access": time of last access
  • "modification": time of last modification
  • "change": time of last status change
  • "size": file size in bytes


ilua.chdir (path)

Changes the current working directory to the given path.

Returns true in case of success or nil plus an error string.

Access is not permitted beyond iLuaBox's sandboxed environment.


ilua.currentdir ()

Returns a string with the current working directory or nil plus an error string.


ilua.cls (screen)

Clears the contents of the user-interface screen, specified by screen as follows:

  • 0: clears the OUTPUT screen
  • 1: clears the INPUT screen


iter, dirobj = ilua.dir (path)

Lua iterator over the entries of a given directory.

Each time the iterator is called with dir_obj it returns a directory entry's name as a string, or nil
if there are no more entries. You can also iterate by calling dir_obj:next(), and explicitly close the
directory before the iteration finished with dir_obj:close().

Raises an error if path is not a directory.


ilua.fsattributes (filepath [,aname])

Identical to ilua.attributes except that it obtains information about the file system.

If the second optional argument is given, then only the value of the named attribute is returned (this use is equivalent to ilua.fsattributes(filepath).aname, but the table is not created and only one attribute is retrieved).

Attribute mode is a string, all the others are numbers, and the time related attributes use the same time reference of os.time. The attributes are described as follows:

  • "blocks": total storage size in blocks
  • "blocksize": block size in bytes
  • "free": free storage size in blocks


ilua.inputtext

Sets or returns a string representing the text currently displayed in the input screen area.

Typical stdio routines are bypassed and the _INPUTBUFFERSIZE global variable is ignored.


ilua.mkdir (dirname)

Creates a new directory with . The argument is the name of the new directory.

Returns true if the operation was successful; in case of error, it returns nil plus an error string.

Directories cannot be created outside of iLuaBox's sandboxed environment.


ilua.out2in (...)

Receives any number of arguments, and prints their values to the INPUT user-interface screen, using the tostring function to convert them to strings.
ilua.out2in is not intended for formatted output, but only as a quick way to show a value, typically for debugging or listing a file's contents for editing. For formatted output, use string.format.


ilua.outputtext

Sets or returns a string representing the text currently displayed in the output screen area.

Typical stdio routines are bypassed and the _OUTPUTBUFFERSIZE global variable is ignored.


ilua.peerenabled

Returns a boolean value indicating whether peer messaging is (true) or isn't (false) enabled.

Peer messaging can only be enabled by the user from within the Settings app. The device peer name and group must be set prior to enabling peer messaging.

iLuaBox peer-to-peer messaging creates and manages an ad-hoc Bluetooth or local wireless network for exchanging information with other iLuaBox users. The peer name and group must be configured prior to enabling peer messaging. Once configured and enabled, wireless connections are made automatically and data can be sent and received using the ilua.sendmessage and ilua.receivemessage functions.


ilua.peergroup

Returns a string representing the peer group used with peer messaging.

Only peers belonging to the same group are found nearby over Bluetooth or Wi-Fi. The peer group can only be set from within the Settings app.


ilua.peername

Returns a string representing the name of the device used with peer messaging.

The device name can only be set from within the Settings app. Every device in the same peer group must use a unique peer name.


ilua.peers

Returns a table of strings representing the names of peers that are wirelessly connected to the device. Names are sorted in ascending alphabetical order.

Only peers belonging to the same group are found nearby over Bluetooth or Wi-Fi. The device name and peer group are set using the Settings app. Connections are made automatically if peer messaging is enabled.


contents, sender, time = ilua.receivemessage ()

Returns the contents string, sender name string, and time of the oldest message in the incoming peer message queue.

iLuaBox automatically receives and queues messages that were addressed specifically to the device or were broadcast by another peer to the entire group. The returned message is removed from the queue and subsequent calls will return the next oldest message in the queue.

Like all Lua strings, the contents value is an array of characters that can contain any 8-bit value, including embedded zeros ('\0').

The time value corresponds to the time the message was received, and is compatible with values produced by the os.time function.

Only nil values are returned if there are no messages in the message queue.


ilua.sendmessage (contents [, dest [, reliable]])

Sends a message to one or more peers in the same group.

The contents argument is a string representing the body of the message. Like all Lua strings, the contents argument is an array of characters that can contain any 8-bit value, including embedded zeros ('\0').

The dest argument is a string or array of strings representing the peer name(s) of the message destination. If the dest argument is a nil value or not provided, the message will be sent to all connected peers within the same group as the sending device.

The reliable argument is a boolean value indicating if the message is (true) or isn't (false) sent
reliably. A reliable message is continuously sent until it is successfully received by the intended recipients, or until the connection
times out. If the reliable argument is false or not provided, the message is sent only once and without confirmation.
Note that if reliable is given, then dest must be given as well.


ilua.setscreenmode (screen)

Sets the user-interface screen mode, specified by screen as follows:

  • 0: Maximum output screen mode
  • 1: Maximum input screen mode
  • 2: Split input-output screen mode (also set when orientation changes)


ilua.sleep (interval)

iLuaBox sleeps for the given time interval. This value is measured in seconds.


ilua._DESCRIPTION

A variable (not a function) of the 'ilua' global table that holds a string containing the description of the iLua Toolbox.


ilua._NAME

A variable (not a function) of the 'ilua' global table that holds a string containing the name of the iLua Toolbox.


ilua._VERSION

A variable (not a function) of the 'ilua' global table that holds a string containing the current version of the iLua Toolbox.

2 – Code Snippets

Below are listings of the sample files included with iLuaBox that utilize iLua Toolbox functionality.
If these files are not present, completely exit from iLuaBox and enable the 'Restore Examples' setting
from the Settings app. Then restart iLuaBox.

  • "hello.lua":
    the sample code that iLuaBox runs after a new installation.
    -- hello.lua
    
    ------------------------------------------------------------------
    --  Import dependencies
    ------------------------------------------------------------------
    local ilua = require("ilua")
    
    -- Greet our user
    ilua.cls(0)
    ilua.setscreenmode(2)
    print("Hello World!")
    print(os.date("Today is %A, %B %d, %Y"))
    print(os.date("The time is %I:%M:%S %p"))
    
    -- Add convenience functions
    dofile("extras.lua")
    
    -- Show version information
    ver()
    
    -- Show getting started comments
    print("\nA few functions were added from extras.lua:")
    print(" ls()   - lists files and sizes")
    print(" cat()  - lists file contents")
    print(" ver()  - prints iLua version")
    print(" edit() - choose file to edit\n")
    
    -- Advise user if new version
    ilua.loadData()
    if _IVERSION ~= ilua._DATA.lastVersion then
      ilua._DATA.lastVersion = _IVERSION
      ilua.saveData()
      print("\nThis is a new version of iLuaBox.")
      print("See what's new in iLuaBox Help.")
      print("Also check Toolbox Info for updates.")
    end
    
    -- Sign off
    print("\nHave fun! from the iLuaBox Team :)")
    

  • "extras.lua":
    includes a few convenience functions.
    -- extras.lua
    
    ------------------------------------------------------------------
    --  Import dependencies
    ------------------------------------------------------------------
    local ilua = require("ilua")
    
    -- ls convenience function lists files and sizes
    function ls(options)
      options = options or ""  -- 'l'=long format
      ilua.cls(0)
      ilua.setscreenmode(2)
      print("Current directory: "..ilua.currentdir().."\n")
      local d = {}
      local maxName, maxSize, index = 0, 0, 0
      for file in ilua.dir(".") do
        table.insert(d, file)
        local attr = ilua.attributes (file)
        maxName = math.max(maxName, (string.len(file)))
        maxSize = math.max(maxSize, 
    	  (string.len(tostring(attr["size"]))))     
      end
      for file in ilua.dir(".") do
          index = index+1
          local attr = ilua.attributes (file)
          -- print entry in long format
          if (string.find(options, "l") ~= nil) then
            print(
              string.format("%2d: %-"..maxName.."s %"..maxSize.."d %s", 
              index, file, attr["size"],
              os.date("%x %X", attr["modification"])))
          -- print entry in default short format
          else
            print(
              string.format("%2d: %-"..maxName.."s %"..maxSize.."d", 
              index, file, attr["size"]))      
          end
      end
      attr = ilua.fsattributes(".")
      local dTotal = (attr["blksize"] * attr["blocks"]) / (10^9) 
      local dFree = (attr["blksize"] * attr["free"]) / (10^9) 
      print(
        string.format("\n%.2f GB of %.2f GB free\n", dFree, dTotal))
      return d
    end
    
    -- cd convenience function changes the current directory
    function cd(pathname)
      if pathname == nil then
        local d = ls()
        io.write("Enter directory number to view:")
        local f=tonumber(io.read())
        if f ~= nil then
          print(f.."\n")
          pathname = d[tonumber(f)]
        else
          print("done\n")
        end
      end
      if pathname ~= nil then
        local sts, err = ilua.chdir(pathname)
        if (sts == nil) then
          print(err)
          io.write("Press Enter to continue...")
          io.read()
        end
        cd()
      end
    end
    
    -- mv convenience function moves a file or directory
    function mv(oldpathname, newpathname)
      if oldpathname == nil or newpathname == nil then
        oldpathname = nil
        newpathname = nil
        local d = ls()
        io.write("Enter file/dir number to move:")
        local f1=tonumber(io.read())
        if f1 ~= nil then
          print(f1.."\n")    
          oldpathname = d[tonumber(f1)]
          io.write("Enter new directory number:")
          local f2=tonumber(io.read())
          if f2 ~= nil then
            print(f2.."\n")
            newpathname = d[tonumber(f2)]
          else
            print("cancel\n")
          end
        else
          print("cancel\n")
        end
      end
      if oldpathname ~= nil and newpathname ~= nil then
        local sts, err = os.rename(oldpathname, 
    	  newpathname.."/"..oldpathname)
        if (sts == nil) then
          print(err)
          io.write("Press Enter to continue...")
          io.read()
        end
        mv()
      end
    end
    
    -- rm convenience function removes a file or directory
    function rm(pathname)
      if pathname == nil then
        local d = ls()
        io.write("Enter file/dir number to remove:")
        local f1=tonumber(io.read())
        if f1 ~= nil then
          print(f1.."\n")
          io.write("Confirm file/dir number to remove:")
          local f2=tonumber(io.read())
          if f2 ~= nil then
            print(f2.."\n")
            if f1 == f2 then
              pathname = d[tonumber(f1)]
            end
          else
            print("cancel\n")
          end
        else
          print("cancel\n")
        end
      end
      if pathname ~= nil then
        local sts, err = os.remove(pathname)
        if (sts == nil) then
          print(err)
          io.write("Press Enter to continue...")
          io.read()
        end
        rm()
      end
    end
    
    -- mk convenience function makes directory
    function mk(pathname)
      if pathname == nil then
        local d = ls()
        io.write("Enter new directory name:")
        pathname = io.read()
        if pathname ~= "" then
          print(pathname.."\n")
        else
          print("cancel\n")
        end
      end
      if pathname ~= "" then
        local sts, err = ilua.mkdir(pathname)
        if (sts == nil) then
          print(err)
          io.write("Press Enter to continue...")
          io.read()
        end
        mk()
      end
    end
    
    -- cat convenience function lists file contents
    function cat(filename, screen)
      local f = assert(io.open(filename, "r"))
      if screen == 1 then
        ilua.cls(1)
      ilua.out2in(f:read("*all"))
      else
        ilua.cls(0)  
        print(f:read("*all")) 
      end
      f:close()
    end
    
    -- ver convenience function prints iLuaBox version
    function ver()
      print(string.format("%s is based on %s", _IVERSION, _VERSION))
    end
    
    -- edit convenience function loads a file to input screen
    function edit(filename)
      if filename == nil then
        local d = ls()
        io.write("Enter file number to edit:")
        local f=tonumber(io.read())
        if f ~= nil then
          print(f.."\n")     
          filename = d[tonumber(f)]
        else
          print("cancel\n")    
        end
      end
      if filename ~= nil then
        cat(filename,1)
      end
    end
    
    -- run convenience function runs a file
    function run(filename)
      if filename == nil then
        local d = ls()
        io.write("Enter file number to run:")
        local f=tonumber(io.read())
        if f ~= nil then
          print(f.."\n")     
          filename = d[tonumber(f)]
        else
          print("cancel\n")    
        end
      end
      if filename ~= nil then
        dofile(filename)
      end
    end
    
    -- Users can add label/script pairs to ilua._CABINET table
    -- that will be used to populate the cabinet action sheet.
    _CABINET = {
      {"View Directory", "cd()"},
      {"Make Directory", "mk()"},
      {"Move", "mv()"},
      {"Remove", "rm()"}, 
      {"Edit File", "edit()"},
      {"Run File", "run()"}}
    
    -- Up to 35 label/text pairs in ilua._SHELF table will be
    -- used to populate the keyboard shelf (iPad only).
    -- The 'tab' label corrsponds to the tab key. Replacement
    -- text can include multiple characters and escape codes.
    _SHELF = {
      {"tab", "  "},
      {"1", "1"},
      {"2", "2"},
      {"3", "3"},
      {"4", "4"},
      {"5", "5"},
      {"6", "6"},
      {"7", "7"},
      {"8", "8"},
      {"9", "9"},
      {"0", "0"},
      {"=", "="},
      {"(", "("},
      {")", ")"},
      {"\"", "\""},
      {"{", "{"},
      {"}", "}"},
      {"[", "["},
      {"]", "]"},
      {"'", "'"},
      {":", ":"},
      {";", ";"},
      {"~", "~"},  
      {"%", "%"},
      {"&", "&"},
      {"#", "#"},  
      {"_", "_"},
      {"\\", "\\"}, 
      {"+", "+"},
      {"-", "-"},
      {"*", "*"},
      {"/", "/"},
      {"^", "^"},
      {"<", "<"},
      {">", ">"}}
    
    -- user initializaion code can be added as-needed
    

  • "bisect.lua":
    a sample math problem.
    -- bisect.lua
    
    -- bisection method for solving non-linear equations
    
    local delta=1e-6  -- tolerance
    
    function bisect(f,a,b,fa,fb)
      local c=(a+b)/2
      io.write(n," c=",c," a=",a," b=",b,"\n")
      if c==a or c==b or math.abs(a-b)<delta then return c,b-a end
      n=n+1
      local fc=f(c)
      if fa*fc<0 then return bisect(f,a,c,fa,fc) else 
        return bisect(f,c,b,fc,fb) end
    end
    
    -- find root of f in the inverval [a,b]. needs f(a)*f(b)<0
    function solve(f,a,b)
      n=0
      local z,e=bisect(f,a,b,f(a),f(b))
    
      io.write(string.format(
        "after %d steps, root is %.17g with error %.1e, f=%.1e\n",
        n,z,e,f(z)))
    
    end
    
    -- our function
    function f(x)
      return x*x*x-x-1
    end
    
    -- find zero in [1,2]
    solve(f,1,2)
    

  • "chat.lua":
    a sample chat session using peer messaging.
    -- chat.lua
    
    -- Enable peer messaging in Settings.
    -- The peer group must be the same for all
    -- participants in the collaboration.
    
    ------------------------------------------------------------------
    --  Import dependencies
    ------------------------------------------------------------------
    local ilua = require("ilua")
    
    -- send input screen text to all peers
    local function updateMyText ()
      local name = ilua.peername
      local text = ilua.inputtext
      if name ~= nil then
        ilua.sendmessage(text)
        groupText[name] = text
      end
    end
    
    -- check incoming messages from peers
    local function updatePeerText ()
      local message, sender = ilua.receivemessage()
      while message ~= nil do
        groupText[sender] = message
        message, sender = ilua.receivemessage()
      end
      -- track all peers that connected
      for i,v in ipairs(ilua.peers) do
        if groupText[v] == nil then
          groupText[v] = ""
        end
      end
    end
    
    -- return text with a specific underline
    local function underlineText (text, char)
      local newText = text.."\n"
      local i
      for i=1,#text,1 do
        newText = newText..char
      end
      newText = newText.."\n"
      return newText
    end
    
    -- create sorted list of peers that chatted
    local function sortPeers ()
      sortedPeers = {}
      for k in pairs(groupText) do
        table.insert(sortedPeers, k)
      end
      table.sort(sortedPeers, function(a,b) return a<b end)
    end
    
    -- build-up header section of chat session
    function makeHeader ()
      local peerGroup = ilua.peergroup or "No Group"
      local header = underlineText(peerGroup.." on "..date, "=")
      sortPeers()
      for i,v in ipairs(sortedPeers) do
        header = header.."* "..v.."\n"
      end
      return header 
    end
    
    -- publish chat session to output screen area
    local function publishTranscript ()
      local transcript = makeHeader().."\n"
      for i,v in ipairs(sortedPeers) do
        if groupText[v] ~= nil then
          transcript = transcript..underlineText(v, "-")
          transcript = transcript..groupText[v].."\n\n"
        end
      end
      if ilua.outputtext ~= transcript then
        ilua.outputtext = transcript
      end
    end
    
    ------------------------------------------------------------------
    --  Start of chat session
    ------------------------------------------------------------------
    date = os.date("%x %I:%M %p")
    ilua.inputtext = ""
    ilua.outputtext = ""
    groupText = {}
    
    -- main loop
    while ilua.peerenabled == true do
      updateMyText()
      updatePeerText()
      publishTranscript()
      ilua.sleep(1.0)
    end
    print("Peer messaging not enabled.")
    

  • "data.lua":
    the ilua._DATA table serialized by ilua.saveData().
    -- data.lua
            
    ilua._DATA = {}
    ilua._DATA["lastVersion"] = "iLuaBox 1.4"
    

  • "ilua.lua":
    adds persistence of user-define variables.
    -- ilua.lua
    
    ------------------------------------------------------------------
    --  Import dependencies
    ------------------------------------------------------------------
    local ilua = require("ilua.core")
    
    ------------------------------------------------------------------
    -- Exported auxiliary functions
    ------------------------------------------------------------------
    -- serialization support function
    function ilua.basicSerialize (o)
      if type(o) == "number" or type(o) == "boolean" then
        return tostring(o)
      else   -- assume it is a string
        return string.format("%q", o) end
    end
    
    -- save a table to current I/O stream
    function ilua.saveTable (name, value, saved)
      saved = saved or {}                 -- initial value
      io.write(name, " = ")
      if type(value) == "number" or type(value) == "string" or
        type(value) == "boolean" then
        io.write(ilua.basicSerialize(value), "\n")
      elseif type(value) == "table" then
        if saved[value] then              -- value already saved?
          io.write(saved[value], "\n")    -- use its previous name
        else
          saved[value] = name             -- save name for next time
          io.write("{}\n")                -- create a new table
          for k,v in pairs(value) do      -- save its fields
            k = ilua.basicSerialize(k)
            local fname = string.format("%s[%s]", name, k)
            ilua.saveTable(fname, v, saved)
          end
        end
      else
        error("cannot save a " .. type(value))
      end
    end
    
    -- Users can add fields to 'ilua._DATA' table
    -- as-needed for perstistent storage between sessions.
    -- Supported types include number, string, boolean, and table.
    -- User must call 'ilua.saveData' function to save data
    -- as a script file named 'data.lua'.  The 'ilua._DATA'
    -- table  is recreated by calling 'ilua.loadData' or by
    -- simply executing 'data.lua'. 
    function ilua.saveData()
      ilua._DATA = ilua._DATA or {}
      local f = io.open("data.lua", "w")
      io.output(f)          -- prepare to write
      io.write("-- data.lua\n\n")
      ilua.saveTable("ilua._DATA", ilua._DATA)
      f:close()
      io.output(io.stdout)  -- restore stdout
    end
    
    -- load the ilua._DATA table from file 'data.lua' 
    function ilua.loadData()
      local f = io.open("data.lua", "r")
      if f == nil then      -- does file exist?
        ilua.saveData()     -- create if necessary
      else
        f:close()           -- close existing file
      end
      io.input(io.stdin)    -- restore stdin
      dofile("data.lua")    -- run the script
    end
    
    ------------------------------------------------------------------
    --  Return module table
    ------------------------------------------------------------------
    return ilua
    

3 – Version History

Here is a chronology of the releases of all versions of iLua Toolbox.

3.1 – iLua Toolbox 1.3

iLua Toolbox 1.3 contains the following improvements:

  • [NEW] Added ilua.inputtext property.
  • [NEW] Added ilua.outputtext property.
  • [NEW] Added ilua.peerenabled property.
  • [NEW] Added ilua.peers property.
  • [NEW] Added ilua.receivemessage function.
  • [NEW] Added ilua.sendmessage function.
  • [NEW] Added boolean data type support to 'ilua._DATA' table.

3.2 – iLua Toolbox 1.2

iLua Toolbox 1.2 contains the following improvements:

  • [NEW] ilua.lua file contains helper functions.
  • [NEW] Added ilua.attributes function.
  • [NEW] Added ilua.chdir function.
  • [NEW] Added ilua.currentdir function.
  • [NEW] Added ilua.fsattributes function.
  • [NEW] Added ilua.mkdir function.
  • [CHANGE] Changed behaviour of ilua.dir function.
  • [CHANGE] Removed ilua.acceleration function.
  • [CHANGE] Removed ilua.setaccelerometerupdate function.

3.3 – iLua Toolbox 1.1

iLua Toolbox 1.1 contains the following improvements:

  • [NEW] Added ilua._DESCRIPTION variable to 'ilua' global table.
  • [NEW] Added ilua._NAME variable to 'ilua' global table.
  • [NEW] Added ilua._VERSION variable to 'ilua' global table.

3.4 – iLua Toolbox 1.0

Initial release.

4 – About iLua Toolbox

iLua Toolbox 1.3

iLuaBox, mLuaBox, eLuaBox, LuaBoxen and the iLuaBox logo are trademarks of MobileApp Systems LLC.
iLuaBox and associated software and hardware products are designed, manufactured and supported by
MobileApp Systems LLC. Visit the MobileApp Systems Web site for additional information:
www.mobileappsystems.com


Copyright © 2010-12 MobileApp Systems LLC

Last update: 21-Mar-2012