Lua for Python Programmers

Getting Started

To try for yourself the code examples in this paper, or any other curiosities you will want to test, get the Lua 5.1.4 and Python 3.1.2 interpreters.

Getting Lua 5.1.4

Lua binaries for several platforms are available here. Alternatively, luaforwindows is great for getting started quickly in Windows.

Getting Python 3.1.2

Python can be downloaded here.

A First Example

The following examples are complete programs in each language, Lua and Python. The programs prompt for a number on one line then print a message on another line:

PythonLua
from sys import *

def fact(n) :
    if n < 1 :
        return 1
    else :
        return n * fact(n-1)

stdout.write("Enter a number: ")
n = int(input())

print("Factorial is " + str(fact(n)))
function fact(n)
    if n < 1 then
        return 1
    else
        return n * fact(n-1)
    end    
end

io.write("Enter a number: ")
n = tonumber(io.read())

print("Factorial is " .. fact(n))

As shown in the example, Lua functions can be defined with the function keyword followed by the common pattern on an identifier, parentheses, and parameter names. Continuing through the example, the conditional part of an if-statement is ended by a then keyword. Code statements can be separated by any whitespace (not just newline) and an optional semicolon. This means that multiple statements can be written on the same line separated only by spaces. Tolerable programmers use semicolons. C-style syntax is used for returning, function call, and arithmetic. Blocks of statements, including functions, are closed by the end keyword. The io object by default points to standard input and output. io.write will write characters without an added newline and io.read will read a line of text. The tonumber function coverts a string to Lua’s one numeric type, double-precision floating point. The print function outputs a string and a newline. The string concatenation operator is .. (two periods). String concatenation coerces its operands into strings.