In association with heise online

A quick look at Lua code

To get started with Lua, you can use its standalone interpreter which comes already packaged for many platforms or can be installed from source. For example, on Ubuntu, "sudo apt-get install lua5.1" at the command line will be enough to install it.

Familiar commands in Lua include print, if, then, else, elseif, for, while, repeat, do and end; here's an example to give a feel;

    for n=1,5 do
if n==1 then
print "Would you like a cup of tea?"
elseif n==5 then
print "One cup of tea coming up"
print "Go on"

Lua has first-class functions and tables, an all-purpose key-value data structure. First class functions are functions which, rather than just being code in the program, can be treated as variables and passed between functions. The table stands in for the range of data structures other languages may offer; an array is just a table where all the keys are numeric (though unlike many other languages, array indexes start at 1):

> arr={ "one","two","three" }
> print(arr[2].." cups of tea")
two cups of tea

The ".." operator concatenates strings. The table takes strings as a key, not just integers, and can act as an associative array too, which can in turn be used as part of creating object-like data storage. Lua supports a "." operator to access them so you can do...

> holder={ tea="cup", coffee="mug" }
> print(holder.tea)
> holder.tea="mug"
> print(holder.tea)

Here's a more substantial snippet of Lua code, with comments, to count occurrences of words in a text file. The lines starting with "--" are Lua comments. Things to notice are the use of generators, to read and return words from the file, and using a table as an associative array.

-- words.lua
-- This is a generator - given a file, it returns a function that
-- will return words from the file until the file is finished

function wordget( file )
local f=file
return function ()
local c=f:read(1)
local s=""
while c~=nil do
if (c>="a" and c<="z") or (c>="A" and c<="Z") then
if string.len(s)>0 then
return s

-- Here we open a text text file"test.text","r")

-- We initialise the array for the counting of words

-- Now we use the generator to read words from the file
for i in wordget(f) do
-- If there's no existing entry, create one and set to 1
if not wordcount[i] then
-- Otherwise, just add one to the existing entry

-- Using the pairs function, step through the key/value pairs
-- in the wordcount table and print them out

for j,k in pairs(wordcount) do

Hopefully, these short examples have given you a taste of the clean, expressive style of Lua. But, how does it work in production? For that we talk with a Lua user.

Next: Talking with a Lua user

Print Version | Permalink:
  • Twitter
  • Facebook
  • submit to slashdot
  • StumbleUpon
  • submit to reddit

  • July's Community Calendar

The H Open

The H Security

The H Developer

The H Internet Toolkit