Lua

Implementation of programming language Lua

Reference implementation from language creators, written in ANSI C. Runs by interpreting bytecode for a register-based virtual machine, and has automatic memory management with incremental garbage collection.

Examples:

Hello, World!:

Example for versions Lua 5.0.3
print("Hello, World!")

Factorial:

Example for versions Lua 5.0.3

This example uses recursive factorial definition.

function factorial(n)
    if (n == 0) then
        return 1
    else
        return n * factorial(n - 1)
    end
end

for n = 0, 16 do
    io.write(n, "! = ", factorial(n), "\n")
end

Fibonacci numbers:

Example for versions Lua 5.0.3

This example uses recursive definition of Fibonacci numbers.

function fibonacci(n)
    if n<3 then
        return 1
    else
        return fibonacci(n-1) + fibonacci(n-2)
    end
end

for n = 1, 16 do
    io.write(fibonacci(n), ", ")
end
io.write("...\n")

Fibonacci numbers:

Example for versions Lua 5.0.3

Numbers which have already been calculated are stored in associative array fib and are retrieved from it to calculate the next ones. By default Lua associative arrays use 1-based integer keys, so fib = {1, 1} creates an array with indices 1 and 2.

fib = {1, 1}
for n = 3, 16 do
    fib[n] = fib[n-1] + fib[n-2]
end
for n = 1, 16 do
    io.write(fib[n], ", ")
end
io.write("...\n")

Quadratic equation:

Example for versions Lua 5.0.3, Lua 5.1.4

*n specifies that a number has to be read. Everything else is quite evident.

local A = io.read('*n')
if A==0 then 
    io.write('Not a quadratic equation.')
    return
end
local B = io.read('*n')
local C = io.read('*n')
D = B*B-4*A*C
if D==0 then
    io.write('x = ', -B/2/A)
else if D>0 then
        io.write('x1 = ', (-B+math.sqrt(D))/2/A, '\nx2 = ', (-B-math.sqrt(D))/2/A)
     else
        io.write('x1 = (', -B/2/A, ',', math.sqrt(-D)/2/A, ')\nx2 = (', -B/2/A, ',', -math.sqrt(-D)/2/A, ')\n')
     end
end