Skip to content

What is Lua

homepage-banner

Lua is a powerful, efficient, lightweight, embeddable scripting language. It supports procedural programming, object-oriented programming, functional programming, data-driven programming, and data description.

Getting Started

A simple example of Lua. lua hello.lua or start an interactive session after running a given chunk lua -i hello.lua.

#!/usr/bin/env lua
-- defines a factorial function
function fact (n)
  if n == 0 then
    return 1
  else
    return n * fact(n - 1)
  end
end
print("enter a number:")
a = io.read("*n")
print(fact(a))

or use lua -e "print(10)" to execute a single line of code. The -l option loads a library before executing the given chunk. e.g. lua -i -llib -e "x = 10".

Data Types

## Numerals
4.57e-3
0.3e12
5E+20
math.type(3)
0xff0x1A3

## Relational Operators
< > <= >= == ~=

## Strings
a = "one string"
b = string.gsub(a, "one", "another")
string.rep("abc", 3)
string.reverse("A Long Line!")
string.lower("A Long Line!")
string.upper("A Long Line!")
tonumber(" -3 ")
tonumber(" 10e4 ")
tonumber("100101", 2)
tonumber("fff", 16)

## Tables
a = {}
k = "x"
a[k] = 10
a[20] = "great"
print(a["x"])
k = 20
print(a[k])
a["x"] = a["x"] + 1
print(a[k])
a.x = 10
print(a.x)

t = {10, print, x = 12, k = "hi"}
for k, v in pairs(t) do
  print(k, v)
end

Functions

-- add the elements of sequence 'a'
function add (a)
  local sum = 0
  for i = 1, #a do
    sum = sum + a[i]
  end
  return sum
end

Functions as First-Class Values

a = {p = print}
a.p("hello world")
print = math.sin
a.p(print(1))
math.sin = a.p
math.sin(10, 20)

Closures

function foo (x)  return 2*x  end
foo = function (x) return 2*x end

network = {
                 {name = "grauna",  IP = "210.26.30.34"},
                 {name = "arraial", IP = "210.26.30.23"},
                 {name = "lua",     IP = "210.26.23.12"},
                 {name = "derain",  IP = "210.26.23.20"},
}
table.sort(network, function (a,b) return (a.name > b.name) end

Precompiled Code

luac -o prog.lc prog.lua
lua prog.lc

Error Handling and Exceptions

local ok, msg = pcall(function ()
  -- some code
    if unexpected_condition then error() end
  -- some code
    print(a[i])    -- potential error: 'a' may not be a table
  -- some code
    end)

if ok then    -- no errors while running protected code
  -- regular code
else   -- protected code raised an error: take appropriate action
  -- error-handling code
end

Reference

  • Lua Programming - The Ultimate Beginner’s Guide to Learn Lua Step by Step (2021)
  • Lua 5.4 Reference Manual (https://www.lua.org/manual/5.4/manual.html)
  • Programming in Lua (2017)
Leave a message