Lua

From LQWiki
Jump to navigation Jump to search

Lua (pronounce LOO-ah) is a small, powerful, dynamically-typed scripting language. It can be embedded into applications through its C API (though other bindings are available) or scripts can be run with the standalone interpreter, much like Python or Perl. Lua is free software distributed under the MIT license.

Lua's syntax resembles that of several languages. At first sight it can look like JavaScript, and a little reminiscent of BASIC. When compiled, the Lua interpreter is as little as 150K, which is pretty small for such a powerful language.

Examples

Here is a classic "Hello world" in Lua:

print "Hello World!"

and a more practical, Rot13 function:

-- A function that returns the Rot13 encoded version of a string passed to it
function rot13 (s)
  local byte_a, byte_A = string.byte('a'), string.byte('A')
  s = string.gsub(s, "(%a)", function (c)   -- change each letter ...
        c = string.byte(c)
        local offset = (c >= 97) and byte_a or byte_A
        c = math.mod(c+13-offset, 26)
        return string.char(c + offset)
      end)
  return s
end


Lua doesn't strive to have a large, fully-featured API. It aims to be flexible, implementing all the things required in a normal application. Due to the flexibility of Lua, although the language is not object oriented as such, it is possible to use Lua 'tables' (an array-like data type) as objects, complete with properties and methods. With the addition of metatables it is also possible to add inheritance in several simple lines of code.

Because Lua itself is written in clean C, it is portable to any platform for which there is a C compiler.

Features

  • Small interpreter
  • Portable
  • Powerful syntax
  • Ability to compile scripts to bytecode
  • Open-source license


  • Lexical scoping
  • Dynamically typed (Types: number, string, table, boolean, function, userdata, thread, nil)
  • Functions are first-class values
  • Proper tail-calls (allowing theoretically infinite function recursion depth)
  • Anonymous functions
  • Closures
  • Tables (an implementations of associative arrays)


See also