The Lua scripting language

Moonstruck

First Class: Functions

To structure programs, Lua provides functions that represent distinct types that also can be stored in variables. Functions are defined with the function keyword followed by brackets containing parameters. The function body follows and is terminated by the end keyword. To define a variable number of parameters, Lua uses the construct ..., which can be confusing in examples because it looks like code has been omitted. For example, select (x, ...) lets you access the x th element in the function body. select('#', ...) returns the number of parameters actually passed in. Alternatively, the statement args = {...} grabs all the arguments in the args table. The Lua interpreter does not complain when a function expects three parameters, but only two are provided with a call. The missing parameter is set to nil. An idiom for emulating default values for parameters that do not exist looks like:

function f(a, b, c)
   local a = a or 0
   ...

The local variable a is thus given the value of the parameter variable a if present, and otherwise a value of 0. Because you can store functions in variables and pass them into other functions, you can also construct higher order functions. Lua is also used to program in a functional style, which is back in fashion thanks to languages like Scala, Clojure, and even JavaScript (in the form of Node.js). To parallelize programs, Lua does not use threads but co-routines, which are less prone to error.

Loops

The control structures in Lua are essentially the same as in other popular programming languages. The if queries can contain multiple elseifs and an else block. A while statement always checks a condition at the beginning and executes the block as long as the condition is satisfied. A repeat block does this in reverse and runs until the condition stated at the end of the block is no longer fulfilled.

A for loop can extend over ranges of numbers or use an iterator function that you create (e.g., from an array). Special functions include pairs and ipairs. The following code iterates against an array using a for loop:

tbl = {"a", "b", "c"}
for key, value in ipairs(tbl) do
   print(key, value)
end

A numeric for loop extends over a range of numbers, either with or without an increment: for i = 1, 5 iterates over any number between 1 and 5, whereas for i = 1, 10, 2 uses steps of 2.

A break statement terminates the loop and then continues with program flow. Strangely, Lua is missing a continue statement that other programming languages have, which jumps to the end of a loop and then continues. It has to be simulated in a fairly complicated way using a goto:

for i = 1, 10 do
   if i % 2 == 0 then goto continue end
   print(i)
   ::continue::
end

A goto label is, as seen here, enclosed by two double colons. To simulate the continue statement, the marker occurs directly before the loop end.

Rocks

Basically, I've covered the main language features in Lua, which can already achieve quite a lot. For further reading and a quick reference for syntax and functions, check out the language reference [5].

A programming language is of little value without a healthy ecosystem, and the Luarocks [6] module repository fulfills this purpose. It is installed from source in a jiffy and is included in most Linux distributions. A call to:

luarocks <search term>

searches in the repositories, and

luarocks install    <package>

installs it locally. Root privileges are needed if the location for the packages is only writable for the superuser.

Table 2 shows a selection of useful extensions available from the Luarocks repository. Unfortunately, not all Lua libraries are available on Luarocks, such as modules for LDAP and modern features like libguestfs and the Augeas configuration API. Thanks to the widespread use of Lua, you will have no shortage of programming tools. If you want to use something other than vi or Emacs for your development work, you can turn to a number of graphical development environments (e.g., ZeroBrane; Figure 2) that are available for Linux, Windows, and OS X, and which cost as much as you are willing to pay [7]. Lua plugins are also available for the major Java IDEs, such as Eclipse, Netbeans, and IntelliJ. The ZeroBrane offers many tutorials, such as the one for debugging Wireshark scripts [8].

Figure 2: Users can pay as much as they like for the ZeroBrane IDE.

Table 2

Luarocks

Module Function
AesFileEncrypt AES encryption
Flu Module for the filesystem in userspace (FUSE)
Inotify API for inotify
JSON4Lua JSON module
lapis Web framework for MoonScript and Lua
lbase64 Base64 module
lposix POSIX library (including curses)
lsocket Unix sockets
lsqlite3 Connector for SQLite database
lua-csnappy Support for Google's Snappy compression
lua-ev Module for Linux libev
lua-gnuplot Graphs with gnuplot
lua-inih Parser for .ini files
lua-websockets WebSockets for Lua
LuaCrypto Lua front end for OpenSSL
luadaemon Make Unix daemons out of Lua programs
luadbi-mysql Database abstraction for MySQL
luadbi-postgresql Database abstraction for PostgreSQL
luadns DNS
LuaFileSystem Modules for filesystem access
lualogging Logging API
lzlib Zlib compression (gzip)
MD5 MD5 hashes

The Codea IDE [9] is interesting in that it implements a Lua development environment on the iPad (Figure 3). The movie on the Codea page is worth seeing; it shows what a development environment could look like in support of the developer with colors, sounds, file selection, and so forth, according to data type.

Figure 3: Codea is a Lua development environment on the iPad. (twolivesleft.com)

Infos

  1. Lua website: http://lua.org
  2. "NSE: Nmap Scripting Engine" by Ron McCarty, ADMIN , 2011, issue 06, pg. 72
  3. "Lua for Apache" by Tim Schürmann, ADMIN , issue 09, pg. 42: http://www.admin-magazine.com/Articles/Lua-for-Apache/
  4. Lua programming: http://www.lua.org/pil/contents.html
  5. Lua Reference Manual: http://www.lua.org/manual/5.2/manual.html
  6. Luarocks: http://luarocks.org/
  7. ZeroBrane: http://studio.zerobrane.com/
  8. Debugging Wireshark Lua scripts: http://notebook.kulchenko.com/zerobrane/debugging-wireshark-lua-scripts-with-zerobrane-studio
  9. Codea: http://twolivesleft.com/Codea/

Buy ADMIN Magazine

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content

  • The Lua Scripting Language

    Is this powerful but simple scripting language big enough for Big Data?

  • Lua for Apache

    Lua is a small, lean, and fast scripting language – ideal for working with web servers. Version 2.4 of the Apache web server is the first to offer a matching module that has a few quirks – and pitfalls, if you dig more deeply.

  • Optimization and standardization of PowerShell scripts
    When PowerShell one-liners become full-blown scripts that have an effect throughout the enterprise, IT managers need to review their software development strategies. We look at PowerShell best practices for script design, notation, error handling, and documentation.
  • New features in PHP 8
    After about two years of development, version 8 of the popular PHP scripting language has been released. It comes with a number of innovations and ditches some obsolete features
  • CoffeeScript: A Replacement for JavaScript?

    Through the years, many languages have tried to improve or even replace JavaScript, including CoffeeScript, which runs in all JavaScript Runtime Environments and compiles into JavaScript.

comments powered by Disqus