wiki/articles/lua.md
tocariimaa cb69c5d301 rewrite articles urls, once again
change the html extension to md
2025-02-08 21:29:57 -03:00

2 KiB

Lua

Lua is a libre, 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.

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