2.7 KiB
Lua
Lua is a libre, dynamic scripting programming language created in 1993 by the Brazilian programmer Roberto Ierusalimschy.
Lua is notable for its efficiency (faster than Python), minimal features, extensibility and a small, non bloated implementation, making it a excellent choice for embedding into programs.
Lua has only has 5 datatypes: numbers, tables, functions, strings and nil
. Tables are specially important in Lua,
implementing arrays and hash tables in a single type and enabling metaprogramming though the use of metamethods and metatables.
The main reference implementation is written in ANSI C (about 32000 LOC) and uses a register-based bytecode virtual machine for execution. Another notable implementation is LuaJIT, which speeds up execution speed by JIT compiling the Lua code.
Bytecode
luac
can be used to compile and dump bytecode into a file. However the bytecode is not portable.
luac -o out source.lua
You can get a listing of the compiled bytecode for a Lua source file with luac
:
luac -p -l -l source.lua
See the article Bytecode for an annotated example of Lua bytecode.
Examples
Hello world
print('Hello, world!') -- Can also use double quotes
-- Lua allows you to skip the parentheses if a single argument is supplied:
print 'Hello, world!'
-- Raw string literal:
print [[Hello, world!]]
Factorial
Iterative
function fact(n)
local res = 1
for i = 1, n do
-- Lua has no operator-assignment operators
res = res * i
end
return res
end
-- Functions and variables are global by default, use the `local`
-- specifier to make them local.
local n = 16
-- `..` is the string concatenation operator
print('Factorial of ' .. n .. ':', fact(n))
Tail recursive
function fact(n, acc)
-- Unsupplied arguments default to a `nil` value
-- With the `or` operator we can emulate default arguments:
acc = acc or 1
if n == 0 then
return acc
end
return fact(n - 1, acc * n)
end
Resources
- Documentation and Reference
- Lua Programming Gems
- Online Lua bytecode explorer
- lua-users Unofficial Lua Users group, has a wiki about Lua with useful resources.
- The Implementation of Lua 5.0: paper that describes the register-based virtual machine introduced in version 5.0.
- Lua 5.3 Bytecode Reference (archive: https://archive.is/yLSvT)
See also
- Teal a Lua dialect that adds static typing