kids encyclopedia robot

Lua facts for kids

Kids Encyclopedia Facts
Quick facts for kids
Lua
Lua-Logo.svg
Excerpt of Coordinates module in Lua.png
Screenshot of Lua code from a Wikipedia Lua module using the MediaWiki Scribunto extension
Paradigm Multi-paradigm: scripting, imperative (procedural, prototype-based, object-oriented), functional, meta, reflective
Designed by Roberto Ierusalimschy
Waldemar Celes
Luiz Henrique de Figueiredo
First appeared 1993; 32 years ago (1993)
Stable release
5.4.8 Edit this on Wikidata / 4 June 2025; 2 months ago (4 June 2025)
Typing discipline Dynamic, strong, duck
Implementation language ANSI C
OS Cross-platform
License MIT
Filename extensions .lua
Major implementations
Lua, LuaJIT, LuaVela, MoonSharp,
Dialects
GSL Shell, Luau
Influenced by
C++, CLU, Modula, Scheme, SNOBOL
Influenced
GameMonkey, Io, JavaScript, Julia, Red, Ring, Ruby, Squirrel, C--, Luau,

Lua (pronounced "LOO-uh") is a special kind of programming language. It's designed to be small, fast, and easy to add into other computer programs. Think of it like a helpful tool that makes other software more flexible and powerful.

Lua is used in many different types of applications, especially in video game development. Because it's written in ANSI C, it can work on many different computer systems. It also has a simple way for C programs to connect with it, making it easy to use.

Lua was first created in 1993. At that time, people needed ways to customize their software more easily. Lua was built to help with this, offering basic programming tools but also ways to add more complex features as needed. Its creators wanted it to be quick, easy to move between different systems, and simple to use for developers.

History

How Lua Started

Lua was created in 1993 by three people: Roberto Ierusalimschy, Luiz Henrique de Figueiredo, and Waldemar Celes. They were part of a computer graphics group called Tecgraf at a university in Brazil.

Back then, Brazil had rules that made it hard to buy computer hardware and software from other countries. This meant that companies in Brazil often had to create their own tools. Tecgraf's clients needed special software, but they couldn't easily buy it from abroad. This situation led Tecgraf to build the basic tools they needed themselves.

Early Ideas for Lua

Before Lua, Tecgraf had two simpler languages called SOL and DEL. These were used to describe data and set up programs. They were made to add flexibility to engineering programs used by a company called Petrobras. However, SOL and DEL didn't have ways to control the flow of a program (like "if this happens, then do that"). Petrobras needed more powerful programming features.

The creators of Lua thought about other programming languages available at the time, like Tcl. But Tcl had a different style and didn't work well on all computer systems. Other languages like LISP and Scheme had complicated rules. Python was also very new.

So, it made sense for them to create their own language. They wanted it to be easy for people who weren't professional programmers to use. It also needed to work on many different computer systems.

Lua's Design and Name

Lua 1.0 was designed to include ideas from SOL. The name "Lua" means "Moon" in Portuguese, just as "Sol" means "Sun." This was a nod to its predecessor.

Lua's rules for how programs work were inspired by other languages. For example, it took ideas from Modula for things like `if` and `while` statements. It also got ideas from CLU for allowing functions to return multiple values. The idea of using associative arrays (like a dictionary where you look up values using names, not just numbers) came from SNOBOL and AWK.

Over time, Lua's meaning and how it works were influenced more by Scheme, especially with the addition of anonymous functions (functions without a name) and lexical scoping (rules about where variables can be used).

Since version 5.0, Lua has been released under the MIT License. This is a very open license that allows people to use and change the language freely.

Features

What Makes Lua Special?

Lua is known as a "multi-paradigm" language. This means it offers a small set of basic features that can be used in many different ways to solve various problems. Lua doesn't have built-in support for things like inheritance (where one object gets features from another). However, programmers can add these features using a special Lua tool called "metatables."

Lua also lets programmers create namespaces (ways to organize code), classes (blueprints for objects), and other features using its main data structure: the table. Functions in Lua can be treated like regular values, which allows for many techniques from functional programming.

Lua aims to provide simple, flexible tools that can be expanded as needed, rather than having many specific features built-in. This keeps the language small and fast. The main Lua program is only about 247 kB in size, making it easy to use in many different applications.

As a dynamically typed language, Lua is compact enough to work on various devices. It supports only a few basic types of data, such as true/false values (Booleans), numbers (usually decimals or 64-bit whole numbers), and strings (text). Common data structures like arrays (lists of items), sets, and records (collections of related data) can all be made using Lua's unique "table" feature.

Lua also includes advanced features like first-class functions (functions that can be stored in variables), garbage collection (automatic memory cleanup), closures (functions that remember their surroundings), and coroutines (a way to pause and resume functions).

Basic Lua Code Examples

Here's how you can write the classic "Hello, World!" program in Lua:

print("Hello, World!")

You can also write it without parentheses:

print "Hello, World!"

To create a variable without giving it a value:

local variable

To create a variable and give it a value, like the number 10:

local students = 10

Comments in Lua start with two hyphens (`--`) and go to the end of the line. You can also write comments that span multiple lines using `--` and `--`.

-- This is a single line comment
--[[
This is a
multi-line comment
--]]

Here's an example of a function that calculates the factorial of a number:

function factorial(n)
  local x = 1
  for i = 2, n do
    x = x * i
  end
  return x
end

How Lua Controls Program Flow

Lua uses `if then end` statements for making decisions. You can also add `else` or `elseif then` for more options.

A simple `if` statement looks like this:

if condition then
        -- do something if the condition is true
end

For example, if `x` is not equal to 10:

if x ~= 10 then
        print(x)
end

You can add an `else` part to do something different if the `if` condition is false:

if condition then
        -- do this if true
else
        -- do this if false
end

Here's an example:

if x == 10 then
        print(10)
else
        print(x)
end

For multiple conditions, use `elseif then`:

if condition1 then
        -- do this
elseif condition2 then
        -- do that
else -- optional
        -- do something else
end

Example:

if x == y then
        print("x = y")
elseif x == z then
        print("x = z")
else -- optional
        print("x does not equal any other variable")
end

Lua has different types of loops to repeat actions: `while` loops, `repeat` loops, and `for` loops.

-- A while loop
while condition do
  -- statements to repeat
end

-- A repeat loop (runs at least once)
repeat
  -- statements to repeat
until condition

-- A numeric for loop (counts from first to last)
for i = first, last, delta do
  -- statements, 'i' changes each time
end

You can also put loops inside other loops, which is called nesting.

local grid = {
  { 11, 12, 13 },
  { 21, 22, 23 },
  { 31, 32, 33 }
}

for y, row in pairs(grid) do
  for x, value in pairs(row) do
    print(x, y, value)
  end
end

Functions in Lua

In Lua, functions are treated like any other value. You can store them in variables or pass them around. This example shows how you could change what the `print` function does:

do
  local oldprint = print
  -- Save the original print function
  function print(s)
    -- Make a new print function that changes "foo" to "bar"
    oldprint(s == "foo" and "bar" or s)
  end
end

Now, if you call `print("foo")`, it will actually print "bar"!

Lua also supports closures. This means a function can "remember" the variables from where it was created, even after that part of the code has finished.

function addto(x)
  -- This function returns another function
  return function(y)
    -- The inner function remembers 'x' from 'addto'
    return x + y
  end
end
fourplus = addto(4)
print(fourplus(3)) -- This will print 7 (4 + 3)

Understanding Tables in Lua

Tables are the most important data structure in Lua. They are like flexible containers that can hold different types of information. They are similar to hash tables or dictionaries in other languages.

You create a table using curly brackets `{}`:

a_table = {} -- Creates an empty table

Tables are always passed by reference. This means if you give a table to a function or assign it to another variable, they both point to the *same* table. If you change it through one variable, the change shows up in the other.

a_table = {x = 10}  -- Table with "x" set to 10
print(a_table["x"]) -- Prints 10
b_table = a_table
b_table["x"] = 20   -- Change the value through b_table
print(b_table["x"]) -- Prints 20
print(a_table["x"]) -- Also prints 20, because they are the same table!

You can use text (strings) as keys to store information, like creating a "record" or "structure":

point = { x = 10, y = 20 }   -- Create a table for a point
print(point["x"])            -- Prints 10
print(point.x)               -- This is a shortcut for the line above

Tables can also act like arrays (numbered lists). Lua automatically gives numbers to items in a table, starting from 1 (not 0, like many other languages).

array = { "a", "b", "c", "d" }   -- Items are automatically numbered 1, 2, 3, 4
print(array[2])                  -- Prints "b"
print(#array)                    -- Prints 4 (the length of the array)

You can even have tables inside tables:

ExampleTable =
{
  {1, 2, 3, 4},
  {5, 6, 7, 8}
}
print(ExampleTable[1][3]) -- Prints "3" (the 3rd item in the 1st inner table)
print(ExampleTable[2][4]) -- Prints "8" (the 4th item in the 2nd inner table)

Metatables: Making Tables Smarter

Metatables are a powerful feature in Lua that let you change how tables behave. They allow you to customize operations like what happens when you try to access a key that doesn't exist in a table.

For example, you can use metatables to create an "infinite" table that calculates Fibonacci numbers as you need them:

fibs = { 1, 1 }                                -- Start with the first two Fibonacci numbers
setmetatable(fibs, {
  __index = function(values, n)                -- This function runs if you try to get fibs[n] and it's not there
    values[n] = values[n - 1] + values[n - 2]  -- Calculate the number and save it
    return values[n]
  end
})

Object-Oriented Programming in Lua

Lua doesn't have a built-in idea of "classes" like some other languages. However, you can use functions and tables to create objects and use object-oriented programming (OOP) ideas. An object is basically a table that holds both data (fields) and functions (methods) that work with that data.

You can also make objects inherit features from other objects using metatables. This is similar to how prototypes work in languages like JavaScript.

Here's how you might create a basic "Vector" object:

local Vector = {}
local VectorMeta = { __index = Vector}

function Vector.new(x, y, z)    -- This is like a "constructor" to make new vectors
  return setmetatable({x = x, y = y, z = z}, VectorMeta)
end

function Vector.magnitude(self)     -- A method to calculate the vector's length
  return math.sqrt(self.x^2 + self.y^2 + self.z^2)
end

local vec = Vector.new(0, 1, 0) -- Create a new vector
print(vec.magnitude(vec))       -- Call the method (output: 1)
print(vec.x)                    -- Access a value (output: 0)

Lua also has a special shortcut using a colon (`:`) to make writing object-oriented code easier:

local Vector = {}
Vector.__index = Vector

function Vector:new(x, y, z)    -- The colon means 'self' is automatically passed
  return setmetatable({x = x, y = y, z = z}, self)
end

function Vector:magnitude()     -- Another method
  return math.sqrt(self.x^2 + self.y^2 + self.z^2)
end

local vec = Vector:new(0, 1, 0) -- Create a vector
print(vec:magnitude())          -- Call a method (output: 1)
print(vec.x)                    -- Access a member variable (output: 0)

Inheritance in Lua

You can also make one Lua "class" inherit from another using metatables. This means a new class can get all the features of an existing one and then add its own.

local Vector = {}
Vector.__index = Vector

function Vector:new(x, y, z)
  return setmetatable({x = x, y = y, z = z}, self)
end

function Vector:magnitude()
  return math.sqrt(self.x^2 + self.y^2 + self.z^2)
end

-- Create a new class that inherits from Vector
local VectorMult = {}
VectorMult.__index = VectorMult
setmetatable(VectorMult, Vector) -- VectorMult is now a child of Vector

function VectorMult:multiply(value)
  self.x = self.x * value
  self.y = self.y * value
  self.z = self.z * value
  return self
end

local vec = VectorMult:new(0, 1, 0) -- Create a VectorMult object
print(vec:magnitude())          -- Can still use Vector's methods (output: 1)
print(vec.y)                    -- Access value (output: 1)
vec:multiply(2)                 -- Use VectorMult's new method
print(vec.y)                    -- Value changed (output: 2)

Lua even supports multiple inheritance, where a class can inherit from more than one parent. You can also change how operators like `+` or `-` work for your objects using metatables.

How Lua Works Internally

Lua programs aren't run directly from the text file you write. Instead, they are first turned into something called "bytecode" by a compiler. This bytecode is then run by the Lua virtual machine (VM). This process usually happens automatically when you run your program.

The Lua VM is designed to be very efficient, similar to how a computer's main processor works. This helps Lua programs run quickly.

Connecting Lua with C Programs

Lua is often used to add scripting abilities to other applications. It has a special C API that makes it easy for C programs to talk to Lua. This API is simple and helps C programmers manage data without a lot of extra work.

The Lua C API uses a "stack" to pass information between C and Lua. Think of the stack like a pile of plates: you can put values on top (push) and take them off (pop). You can also look at values anywhere in the stack.

Here's a simple example of how a C program can call a Lua function:

#include <stdio.h>
#include <lua.h> // Lua main library
#include <lauxlib.h> // Lua auxiliary library

int main(void)
{
    // Create a Lua environment
    lua_State *L = luaL_newstate();

    // Load and run a Lua code string (defines a function 'foo')
    if (luaL_dostring(L, "function foo (x,y) return x+y end")) {
        lua_close(L);
        return -1;
    }

    // Tell Lua to get the function 'foo' and put it on the stack
    lua_getglobal(L, "foo");
    // Push the numbers 5 and 3 onto the stack as arguments
    lua_pushinteger(L, 5);
    lua_pushinteger(L, 3);
    // Call the Lua function: 2 arguments, 1 return value
    lua_call(L, 2, 1);
    // Get the result from the stack and print it
    printf("Result: %d\n", lua_tointeger(L, -1));
    // Remove the result from the stack
    lua_pop(L, 1);
    // Close the Lua environment
    lua_close(L);
    return 0;
}

When you run this C program, it will output:

Result: 8

Lua Modules

Besides the basic Lua features, you can also add more functions by using "extension modules." These are like plugins that add new abilities to Lua scripts. Lua scripts can load these modules using `require`, just like they load other Lua files.

There's a system called LuaRocks that helps you find and install these modules, similar to how other programming languages have their own package managers.

Where Lua is Used

Lua in Video Games

Lua is very popular in video game development as a scripting language. Game developers like it because it's easy to add into games, runs fast, and is relatively simple to learn.

Many famous games use Lua, including:

Some games that don't originally support Lua can have this feature added by mods (modifications made by players), like ComputerCraft for Minecraft. Lua is also used in the open-source 2D game engine called LOVE2D.

In 2003, a survey showed that Lua was the most popular scripting language for game programming. In 2012, Lua even won an award for programming tools from Game Developer magazine.

Lua in Other Software

Lua isn't just for games! Many other types of software use Lua to add flexibility:

  • Adobe Lightroom (for photo editing)
  • Moho (for animation)
  • iClone (for 3D animation)
  • Aerospike (a database)
  • Some system software in FreeBSD and NetBSD (operating systems)
  • MediaWiki (the software Wikipedia uses) uses Lua with an extension called Scribunto for templates.
  • LuaTeX (a type-setting language)
  • Redis (a database)
  • ScyllaDB (another database)
  • Neovim (a text editor)
  • Nginx (a web server)
  • Wireshark (a network analysis tool)
  • Pure Data (a visual audio programming language)

Languages Based on Lua

Some programming languages are built on top of Lua or compile into Lua code:

Languages That Compile to Lua

  • MoonScript is a scripting language that looks different from Lua but turns into Lua code. It's used on the video game distribution website Itch.io.
  • Haxe can create Lua code for different Lua versions.
  • Fennel and Urn are Lisp-like languages that also target Lua.
  • Amulet and LunarML are functional programming languages that produce Lua files.

Lua Dialects

Some versions of Lua have been changed or extended:

  • LuaJIT is a special version of Lua that runs much faster using a "just-in-time" compiler.
  • Luau was developed by Roblox Corporation. It's based on Lua 5.1 but has extra features, better performance, and improved safety for running code.
  • Ravi is another fast version of Lua 5.3 with optional static typing.
  • Shine is a version of LuaJIT with many additions.
  • Glua is a modified version of Lua used in the game Garry's Mod.
  • Teal is a Lua version that checks for types before running, helping to catch errors early.
  • PICO-8 uses a smaller version of Lua called PICO-8 Lua.
  • Pluto is a newer version of Lua 5.4 with improved syntax and libraries.

See also

Kids robot.svg In Spanish: Lua para niños

kids search engine
Lua Facts for Kids. Kiddle Encyclopedia.