-- Complex Lua Script

-- Function to generate a Fibonacci sequence up to a given limit
function generateFibonacci(limit)
    local fib = {0, 1}
    while fib[#fib] + fib[#fib - 1] <= limit do
        table.insert(fib, fib[#fib] + fib[#fib - 1])
    end
    return fib
end

-- Function to print a table with labels
function printTableWithLabels(label, tbl)
    print(label .. ":")
    for k, v in pairs(tbl) do
        print("\t" .. tostring(k) .. ": " .. tostring(v))
    end
end

-- Main program
local limit = 1000
local fibonacciSequence = generateFibonacci(limit)

print("Welcome to Marc Costanzo's !")
print("This script demonstrates various Lua features.")

-- Display the Fibonacci sequence
printTableWithLabels("Fibonacci Sequence", fibonacciSequence)

-- Anonymous function using closure
local multiplyByFactor = function(factor)
    return function(x)
        return x * factor
    end
end

local triple = multiplyByFactor(3)
print("Triple of 7:", triple(7))

-- Metatables and custom operators
local Vector = {}
Vector.__index = Vector

function Vector.new(x, y)
    local self = setmetatable({}, Vector)
    self.x = x
    self.y = y
    return self
end

function Vector.__add(v1, v2)
    return Vector.new(v1.x + v2.x, v1.y + v2.y)
end

local v1 = Vector.new(1, 2)
local v2 = Vector.new(3, 4)
local v3 = v1 + v2

printTableWithLabels("Vector v1", v1)
printTableWithLabels("Vector v2", v2)
printTableWithLabels("Vector v3 (v1 + v2)", v3)

-- Coroutine example
local coroutineExample = coroutine.create(function()
    print("Coroutine started")
    coroutine.yield()
    print("Coroutine resumed")
end)

coroutine.resume(coroutineExample)
print("Main program continues")
coroutine.resume(coroutineExample)

-- Custom iterator
local function countdown(n)
    return function()
        if n > 0 then
            n = n - 1
            return n + 1
        end
    end
end

print("Countdown:")
for i in countdown(5) do
    print(i)
end

print("Complex Lua Script executed successfully!")
 

Lua online compiler

Write, Run & Share Lua code online using OneCompiler's Lua online compiler for free. It's one of the robust, feature-rich online compilers for Lua language, running the latest Lua version 5.4. Getting started with the OneCompiler's Lua editor is easy and fast. The editor shows sample boilerplate code when you choose language as Lua and start coding.

Taking inputs (stdin)

OneCompiler's Lua online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample Lua program which takes name as input and prints hello message with your name.

name = io.read("*a")
print ("Hello ", name)

About Lua

Lua is a light weight embeddable scripting language which is built on top of C. It is used in almost all kind of applications like games, web applications, mobile applications, image processing etc. It's a very powerful, fast, easy to learn, open-source scripting language.

Syntax help

Variables

  • By default all the variables declared are global variables
  • If the variables are explicitly mentioned as local then they are local variables.
  • Lua is a dynamically typed language and hence only the values will have types not the variables.

Examples

-- global variables
a = 10

-- local variables

local x = 30
Value TypeDescription
numberRepresents numbers
stringRepresents text
nilDifferentiates values whether it has data or not
booleanValue can be either true or false
functionRepresents a sub-routine
userdataRepresents arbitary C data
threadRepresents independent threads of execution.
tableCan hold any value except nil

Loops

1. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while(condition)
do
--code
end

2. Repeat-Until:

Repeat-Until is also used to iterate a set of statements based on a condition. It is very similar to Do-While, it is mostly used when you need to execute the statements atleast once.

repeat
   --code
until( condition )

3. For:

For loop is used to iterate a set of statements based on a condition.

for init,max/min value, increment
do
   --code
end

Functions

Function is a sub-routine which contains set of statements. Usually functions are written when multiple calls are required to same set of statements which increase re-usuability and modularity.

optional_function_scope function function_name( argument1, argument2, argument3........, argumentn)
--code
return params with comma seperated
end