Lua programming language
Encyclopedia
Lua is a lightweight multi-paradigm programming language
Programming language
A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely....

 designed as a scripting language
Scripting language
A scripting language, script language, or extension language is a programming language that allows control of one or more applications. "Scripts" are distinct from the core code of the application, as they are usually written in a different language and are often created or at least modified by the...

 with extensible semantics as a primary goal. Lua has a relatively simple C
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....

 API
Application programming interface
An application programming interface is a source code based specification intended to be used as an interface by software components to communicate with each other...

 compared to other scripting languages.

History

Lua was created in 1993 by Roberto Ierusalimschy
Roberto Ierusalimschy
Roberto Ierusalimschy is an associate professor of informatics at PUC-Rio . He is the leading architect of the Lua programming language and the author of Programming in Lua and Programming in Lua, Second Edition...

, Luiz Henrique de Figueiredo, and Waldemar Celes, members of the Computer Graphics Technology Group (Tecgraf) at the Pontifical Catholic University of Rio de Janeiro, in Brazil
Brazil
Brazil , officially the Federative Republic of Brazil , is the largest country in South America. It is the world's fifth largest country, both by geographical area and by population with over 192 million people...

.

From 1977 until 1992, Brazil had a policy of strong trade barriers
Trade barrier
Trade barriers are government-induced restrictions on international trade. The barriers can take many forms, including the following:* Tariffs* Non-tariff barriers to trade** Import licenses** Export licenses** Import quotas** Subsidies...

 (called a 'market reserve') for computer hardware and software. In that atmosphere, Tecgraf's clients could not afford, either politically or financially, to buy customized software from abroad. Those reasons led Tecgraf to implement from scratch the basic tools it needed.

Lua's historical 'father and mother' were data-description/configuration languages SOL (Simple Object Language) and DEL (data-entry language).
They had been independently developed at Tecgraf in 1992–1993 to add some flexibility into two different projects (both were interactive graphical programs for engineering applications at Petrobras
Petrobras
Petróleo Brasileiro or Petrobras is a semi-public Brazilian multinational energy corporation headquartered in Rio de Janeiro, Brazil. It is the largest company in Latin America by market capitalization and revenue, and the largest company headquartered in the Southern Hemisphere by market...

 company). There was a lack of any flow control structures in SOL and DEL, and Petrobras felt a growing need to add full programming power to them.

In 1993, the only real contender was Tcl
Tcl
Tcl is a scripting language created by John Ousterhout. Originally "born out of frustration", according to the author, with programmers devising their own languages intended to be embedded into applications, Tcl gained acceptance on its own...

, which had been explicitly designed to be embedded into applications. However, Tcl had unfamiliar syntax, did not offer good support for data description, and ran only on Unix platforms. We did not consider LISP or Scheme because of their unfriendly syntax. Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...

 was still in its infancy. In the free, do-it-yourself atmosphere that then reigned in Tecgraf, it was quite natural that we should try to develop our own scripting language... Because many potential users of the language were not professional programmers, the language should avoid cryptic syntax and semantics. The implementation of the new language should be highly portable, because Tecgraf's clients had a very diverse collection of computer platforms. Finally, since we expected that other Tecgraf products would also need to embed a scripting language, the new language should follow the example of SOL and be provided as a library with a C API.


Lua 1.0 was designed in such a way that its object constructors, being then slightly different from the current light and flexible style, incorporated the data-description syntax of SOL. (Hence the name Lua – sol is Portuguese for sun; lua is moon.) Lua syntax for control structures was mostly borrowed from Modula
Modula
The Modula programming language is a descendent of the Pascal programming language. It was developed in Switzerland in the late 1970s by Niklaus Wirth, the same person who designed Pascal...

 (if, while, repeat/until), but also had taken influence from CLU (multiple assignments and multiple returns from function calls, as a simpler alternative to reference parameters or explicit pointers), C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

 ("neat idea of allowing a local variable
Local variable
In computer science, a local variable is a variable that is given local scope. Such a variable is accessible only from the function or block in which it is declared. In programming languages with only two levels of visibility, local variables are contrasted with global variables...

 to be declared only where we need it"), SNOBOL
SNOBOL
SNOBOL is a generic name for the computer programming languages developed between 1962 and 1967 at AT&T Bell Laboratories by David J. Farber, Ralph E. Griswold and Ivan P. Polonsky, culminating in SNOBOL4...

 and AWK (associative array
Associative array
In computer science, an associative array is an abstract data type composed of a collection of pairs, such that each possible key appears at most once in the collection....

s). In an article published in Dr. Dobb's Journal
Dr. Dobb's Journal
Dr. Dobb's Journal was a monthly journal published in the United States by CMP Technology. It covered topics aimed at computer programmers. DDJ was the first regular periodical focused on microcomputer software, rather than hardware. It later became a monthly section within the periodical...

, Lua's creators also state that LISP and Scheme with their single, ubiquitous data structure mechanism (the list) were a major influence on their decision to develop the table as the primary data structure of Lua.

Current Lua semantics
Semantics
Semantics is the study of meaning. It focuses on the relation between signifiers, such as words, phrases, signs and symbols, and what they stand for, their denotata....

 were gained mainly from Scheme:
Semantically, Lua has many similarities with Scheme, even though these similarities are not immediately clear because the two languages are syntactically very different. The influence of Scheme on Lua has gradually increased during Lua's evolution: initially, Scheme was just a language in the background, but later it became increasingly important as a source of inspiration, especially with the introduction of anonymous functions and full lexical scoping.


Versions of Lua prior to version 5.0 were released under a license similar to the BSD license
BSD licenses
BSD licenses are a family of permissive free software licenses. The original license was used for the Berkeley Software Distribution , a Unix-like operating system after which it is named....

. From version 5.0 onwards, Lua has been licensed under the MIT License
MIT License
The MIT License is a free software license originating at the Massachusetts Institute of Technology . It is a permissive license, meaning that it permits reuse within proprietary software provided all copies of the licensed software include a copy of the MIT License terms...

.

Features

Lua is commonly described as a “multi-paradigm” language, providing a small set of general features that can be extended to fit different problem types, rather than providing a more complex and rigid specification to match a single paradigm. Lua, for instance, does not contain explicit support for inheritance
Inheritance (object-oriented programming)
In object-oriented programming , inheritance is a way to reuse code of existing objects, establish a subtype from an existing object, or both, depending upon programming language support...

, but allows it to be implemented relatively easily with metatable
Metatable
A metatable is the section of a database or other data holding structure that is designated to hold data that will act as source code or metadata. In most cases, specific software has been written to read the data from the metatables and perform different actions depending on the data it...

s. Similarly, Lua allows programmers to implement namespaces
Namespace (computer science)
A namespace is an abstract container or environment created to hold a logical grouping of unique identifiers or symbols . An identifier defined in a namespace is associated only with that namespace. The same identifier can be independently defined in multiple namespaces...

, classes
Class (computer science)
In object-oriented programming, a class is a construct that is used as a blueprint to create instances of itself – referred to as class instances, class objects, instance objects or simply objects. A class defines constituent members which enable these class instances to have state and behavior...

, and other related features using its single table implementation; first-class function
First-class function
In computer science, a programming language is said to have first-class functions if it treats functions as first-class objects. Specifically, this means that the language supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning...

s allow the employment of many powerful techniques from functional programming
Functional programming
In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state...

; and full lexical scoping
Scope (programming)
In computer programming, scope is an enclosing context where values and expressions are associated. Various programming languages have various types of scopes. The type of scope determines what kind of entities it can contain and how it affects them—or semantics...

 allows fine-grained information hiding
Information hiding
In computer science, information hiding is the principle of segregation of the design decisions in a computer program that are most likely to change, thus protecting other parts of the program from extensive modification if the design decision is changed...

 to enforce the principle of least privilege
Principle of least privilege
In information security, computer science, and other fields, the principle of least privilege, also known as the principle of minimal privilege or just least privilege, requires that in a particular abstraction layer of a computing environment, every module must be able to access only the...

.

In general, Lua strives to provide flexible meta-features that can be extended as needed, rather than supply a feature-set specific to one programming paradigm. As a result, the base language is light – in fact, the full reference interpreter
Interpreter (computing)
In computer science, an interpreter normally means a computer program that executes, i.e. performs, instructions written in a programming language...

 is only about 150 kB
Kilobyte
The kilobyte is a multiple of the unit byte for digital information. Although the prefix kilo- means 1000, the term kilobyte and symbol KB have historically been used to refer to either 1024 bytes or 1000 bytes, dependent upon context, in the fields of computer science and information...

 compiled – and easily adaptable to a broad range of applications.

Lua is a dynamically typed language intended for use as an extension
Scripting language
A scripting language, script language, or extension language is a programming language that allows control of one or more applications. "Scripts" are distinct from the core code of the application, as they are usually written in a different language and are often created or at least modified by the...

 or scripting language
Scripting language
A scripting language, script language, or extension language is a programming language that allows control of one or more applications. "Scripts" are distinct from the core code of the application, as they are usually written in a different language and are often created or at least modified by the...

, and is compact enough to fit on a variety of host platforms. It supports only a small number of atomic data structures such as boolean values, number
Number
A number is a mathematical object used to count and measure. In mathematics, the definition of number has been extended over the years to include such numbers as zero, negative numbers, rational numbers, irrational numbers, and complex numbers....

s (double-precision floating point
Floating point
In computing, floating point describes a method of representing real numbers in a way that can support a wide range of values. Numbers are, in general, represented approximately to a fixed number of significant digits and scaled using an exponent. The base for the scaling is normally 2, 10 or 16...

 by default), and strings
String (computer science)
In formal languages, which are used in mathematical logic and theoretical computer science, a string is a finite sequence of symbols that are chosen from a set or alphabet....

. Typical data structures such as arrays, sets
Set (computer science)
In computer science, a set is an abstract data structure that can store certain values, without any particular order, and no repeated values. It is a computer implementation of the mathematical concept of a finite set...

, lists, and record
Record (computer science)
In computer science, a record is an instance of a product of primitive data types called a tuple. In C it is the compound data in a struct. Records are among the simplest data structures. A record is a value that contains other values, typically in fixed number and sequence and typically indexed...

s can be represented using Lua’s single native data structure, the table, which is essentially a heterogeneous associative array
Associative array
In computer science, an associative array is an abstract data type composed of a collection of pairs, such that each possible key appears at most once in the collection....

.

Lua implements a small set of advanced features such as first-class function
First-class function
In computer science, a programming language is said to have first-class functions if it treats functions as first-class objects. Specifically, this means that the language supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning...

s, garbage collection
Garbage collection (computer science)
In computer science, garbage collection is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage, or memory occupied by objects that are no longer in use by the program...

, closures
Closure (computer science)
In computer science, a closure is a function together with a referencing environment for the non-local variables of that function. A closure allows a function to access variables outside its typical scope. Such a function is said to be "closed over" its free variables...

, proper tail calls, coercion
Type conversion
In computer science, type conversion, typecasting, and coercion are different ways of, implicitly or explicitly, changing an entity of one data type into another. This is done to take advantage of certain features of type hierarchies or type representations...

 (automatic conversion between string and number values at run time), coroutine
Coroutine
Coroutines are computer program components that generalize subroutines to allow multiple entry points for suspending and resuming execution at certain locations...

s (cooperative multitasking) and dynamic module loading.

By including only a minimum set of data types, Lua attempts to strike a balance between power and size.

Example code

The classic hello world program
Hello world program
A "Hello world" program is a computer program that outputs "Hello world" on a display device. Because it is typically one of the simplest programs possible in most programming languages, it is by tradition often used to illustrate to beginners the most basic syntax of a programming language, or to...

 can be written as follows:

print("Hello World!")


Comments use the following syntax, similar to that of SQL
SQL
SQL is a programming language designed for managing data in relational database management systems ....

 and VHDL:

-- A comment in Lua starts with a double-hyphen and runs to the end of the line.
-- Multi-line strings & comments
are adorned with double square brackets.


The factorial
Factorial
In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n...

 is an example of a recursive
Recursion
Recursion is the process of repeating items in a self-similar way. For instance, when the surfaces of two mirrors are exactly parallel with each other the nested images that occur are a form of infinite recursion. The term has a variety of meanings specific to a variety of disciplines ranging from...

 function:

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


The for loop:

for i = 1,5 do
-- Statements
end


Lua’s treatment of functions as first-class
First-class function
In computer science, a programming language is said to have first-class functions if it treats functions as first-class objects. Specifically, this means that the language supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning...

 values is shown in the following example, where the print function’s behavior is modified:

do
local oldprint = print -- Store current print function as oldprint
function print(s) -- Redefine print function
if s "foo" then
oldprint("bar")
else
oldprint(s)
end
end
end

Any future calls to print will now be routed through the new function, and thanks to Lua’s lexical scoping, the old print function will only be accessible by the new, modified print.

Lua also supports closures
Closure (computer science)
In computer science, a closure is a function together with a referencing environment for the non-local variables of that function. A closure allows a function to access variables outside its typical scope. Such a function is said to be "closed over" its free variables...

, as demonstrated below:

function addto(x)
-- Return a new function that adds x to the argument
return function(y)
-- When we refer to the variable x, which is outside of the current
scope and whose lifetime is longer than that of this anonymous
function, Lua creates a closure.
return x + y
end
end
fourplus = addto(4)
print(fourplus(3)) -- Prints 7

A new closure for the variable x is created every time addto is called, so that the anonymous function returned will always access its own x parameter. The closure is managed by Lua’s garbage collector, just like any other object.

Extensible semantics is a key feature of Lua, and the metatable
Metatable
A metatable is the section of a database or other data holding structure that is designated to hold data that will act as source code or metadata. In most cases, specific software has been written to read the data from the metatables and perform different actions depending on the data it...

 concept allows Lua’s tables to be customized in powerful and unique ways. The following example demonstrates an "infinite" table. For any , fibs[n] will give the th Fibonacci number
Fibonacci number
In mathematics, the Fibonacci numbers are the numbers in the following integer sequence:0,\;1,\;1,\;2,\;3,\;5,\;8,\;13,\;21,\;34,\;55,\;89,\;144,\; \ldots\; ....

 using dynamic programming
Dynamic programming
In mathematics and computer science, dynamic programming is a method for solving complex problems by breaking them down into simpler subproblems. It is applicable to problems exhibiting the properties of overlapping subproblems which are only slightly smaller and optimal substructure...

 and memoization
Memoization
In computing, memoization is an optimization technique used primarily to speed up computer programs by having function calls avoid repeating the calculation of results for previously processed inputs...

.

fibs = { 1, 1 } -- Initial values for fibs[1] and fibs[2].
setmetatable(fibs, {
__index = function(name, n) -- Call this function if fibs[n] does not exist.
name[n] = name[n - 1] + name[n - 2] -- Calculate and memoize fibs[n].
return name[n]
end
})

Tables

Tables are the most important data structure (and, by design, the only built-in composite data type) in Lua, and are the foundation of all user-created types.

A table is a collection of key and data pairs, where the data is referenced by key; in other words, it's a hashed
Hash table
In computer science, a hash table or hash map is a data structure that uses a hash function to map identifying values, known as keys , to their associated values . Thus, a hash table implements an associative array...

 heterogeneous associative array
Associative array
In computer science, an associative array is an abstract data type composed of a collection of pairs, such that each possible key appears at most once in the collection....

. A key (index) can be of any data type except nil. An integer key of 1 is considered distinct from a string key of "1".

Tables are created using the {} constructor syntax:

a_table = {} -- Creates a new, empty table

Tables are always passed by reference:

a_table = {x = 10} -- Creates a new table, with one entry mapping "x" to the number 10.
print(a_table["x"]) -- Prints the value associated with the string key, in this case 10.
b_table = a_table
b_table["x"] = 20 -- The value in the table has been changed to 20.
print(b_table["x"]) -- Prints 20.
print(a_table["x"]) -- Also prints 20, because a_table and b_table both refer to the same table.

As structure

Tables are often used as structure
Object composition
In computer science, object composition is a way to combine simple objects or data types into more complex ones...

s (or objects) by using strings
String (computer science)
In formal languages, which are used in mathematical logic and theoretical computer science, a string is a finite sequence of symbols that are chosen from a set or alphabet....

 as keys. Because such use is very common, Lua features a special syntax for accessing such fields.
Example:

point = { x = 10, y = 20 } -- Create new table
print(point["x"]) -- Prints 10
print(point.x) -- Has exactly the same meaning as line above

As namespace

By using a table to store related functions, it can act as a namespace.

Point = {}
Point.new = function (x, y)
return {x = x, y = y}
end
Point.set_x = function (point, x)
point.x = x
end

As array

By using a numerical key, the table resembles an array data type
Array data type
In computer science, an array type is a data type that is meant to describe a collection of elements , each selected by one or more indices that can be computed at run time by the program. Such a collection is usually called an array variable, array value, or simply array...

. Lua arrays are 1-based: the first index is 1 rather than 0 as it is for many other programming languages (though an explicit index of 0 is allowed).

A simple array of strings:

array = { "a", "b", "c", "d" } -- Indices are assigned automatically.
print(array[2]) -- Prints "b". Automatic indexing in Lua starts at 1.
print(#array) -- Prints 4. # is the length operator for tables and strings.
array[0] = "z" -- Zero is a legal index.
print(#array) -- Still prints 4, as Lua arrays are 1-based.

An array of objects:

function Point(x, y) -- "Point" object constructor
return { x = x, y = y } -- Creates and returns a new object (table)
end
array = { Point(10, 20), Point(30, 40), Point(50, 60) } -- Creates array of points
print(array[2].y) -- Prints 40

Using a hash map to emulate an array normally is slower than using an actual array; however, Lua tables are optimized for use as arrays to help avoid this issue.

Object-oriented programming

Although Lua does not have a built-in concept of classes
Class (computer science)
In object-oriented programming, a class is a construct that is used as a blueprint to create instances of itself – referred to as class instances, class objects, instance objects or simply objects. A class defines constituent members which enable these class instances to have state and behavior...

, they can be implemented using two language features: first-class function
First-class function
In computer science, a programming language is said to have first-class functions if it treats functions as first-class objects. Specifically, this means that the language supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning...

s and tables. By placing functions and related data into a table, an object is formed. Inheritance
Inheritance (object-oriented programming)
In object-oriented programming , inheritance is a way to reuse code of existing objects, establish a subtype from an existing object, or both, depending upon programming language support...

 (both single and multiple) can be implemented via the metatable
Metatable
A metatable is the section of a database or other data holding structure that is designated to hold data that will act as source code or metadata. In most cases, specific software has been written to read the data from the metatables and perform different actions depending on the data it...

 mechanism, telling the object to lookup nonexistent methods and fields in parent object(s).

There is no such concept as "class" with these techniques, rather prototypes
Prototype-based programming
Prototype-based programming is a style of object-oriented programming in which classes are not present, and behavior reuse is performed via a process of cloning existing objects that serve as prototypes. This model can also be known as classless, prototype-oriented or instance-based programming...

 are used as in the programming languages Self or JavaScript
JavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....

. New objects are created either with a factory method
Factory method pattern
The factory method pattern is an object-oriented design pattern to implement the concept of factories. Like other creational patterns, it deals with the problem of creating objects without specifying the exact class of object that will be created.The creation of an object often requires complex...

 (that constructs new objects from scratch) or by cloning an existing object.

Lua provides some syntactic sugar
Syntactic sugar
Syntactic sugar is a computer science term that refers to syntax within a programming language that is designed to make things easier to read or to express....

 to facilitate object orientation. To declare member functions
Method (computer science)
In object-oriented programming, a method is a subroutine associated with a class. Methods define the behavior to be exhibited by instances of the associated class at program run time...

 inside a prototype table, one can use function table:func(args), which is equivalent to function table.func(self, args). Calling class methods also makes use of the colon: object:func(args) is equivalent to object.func(object, args).

Creating a basic vector object:

Vector = {} -- Create a table to hold the class methods
function Vector:new(x, y, z) -- The constructor
local object = { x = x, y = y, z = z }
setmetatable(object, { __index = Vector }) -- Inheritance
return object
end
function Vector:magnitude -- Another member function
-- Reference the implicit object using self
return math.sqrt(self.x^2 + self.y^2 + self.z^2)
end

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

Internals

Lua programs are not interpreted
Interpreted language
Interpreted language is a programming language in which programs are 'indirectly' executed by an interpreter program. This can be contrasted with a compiled language which is converted into machine code and then 'directly' executed by the host CPU...

 directly from the textual Lua file, but are compiled
Compiler
A compiler is a computer program that transforms source code written in a programming language into another computer language...

 into bytecode
Bytecode
Bytecode, also known as p-code , is a term which has been used to denote various forms of instruction sets designed for efficient execution by a software interpreter as well as being suitable for further compilation into machine code...

 which is then run on the Lua virtual machine
Virtual machine
A virtual machine is a "completely isolated guest operating system installation within a normal host operating system". Modern virtual machines are implemented with either software emulation or hardware virtualization or both together.-VM Definitions:A virtual machine is a software...

. The compilation process is typically transparent to the user and is performed during run-time, but it can be done offline in order to increase loading performance or reduce the memory footprint of the host environment by leaving out the compiler.

Like most CPUs, and unlike most virtual machines (which are stack-based
Stack machine
A stack machine may be* A real or emulated computer that evaluates each sub-expression of a program statement via a pushdown data stack and uses a reverse Polish notation instruction set....

), the Lua VM is register-based
Register machine
In mathematical logic and theoretical computer science a register machine is a generic class of abstract machines used in a manner similar to a Turing machine...

, and therefore more closely resembles an actual hardware design. The register architecture both avoids excessive copying of values and reduces the total number of instructions per function. The virtual machine of Lua 5 is one of the first register-based pure VM to have a wide use. Perl
Perl 6
Perl 6 is a major revision to the Perl programming language. It is still in development, as a specification from which several interpreter and compiler implementations are being written. It is introducing elements of many modern and historical languages. Perl 6 is intended to have many...

's
Parrot
Parrot virtual machine
Parrot is a register-based process virtual machine designed to run dynamic languages efficiently. It uses just-in-time compilation for speed to reduce the interpretation overhead. It is currently possible to compile Parrot assembly language and PIR to Parrot bytecode and execute it...

 and Android's Dalvik
Dalvik virtual machine
Dalvik is the process virtual machine in Google's Android operating system. It is the software that runs the apps on Android phones. Dalvik is thus an integral part of Android, which is typically used on mobile devices such as mobile phones, tablet computers and netbooks. Programs are commonly...

 are two other well-known register-based VMs.

This example is the bytecode listing of the factorial function defined above (as shown by luac 5.1 compiler):

function (10 instructions, 40 bytes at 003D5818)
1 param, 3 slots, 0 upvalues, 1 local, 3 constants, 0 functions
1 [2] EQ 0 0 -1 ; - 0
2 [2] JMP 2 ; to 5
3 [3] LOADK 1 -2 ; 1
4 [3] RETURN 1 2
5 [5] GETGLOBAL 1 -3 ; factorial
6 [5] SUB 2 0 -2 ; - 1
7 [5] CALL 1 2 2
8 [5] MUL 1 0 1
9 [5] RETURN 1 2
10 [6] RETURN 0 1

C API

Lua is intended to be embedded into other applications, and accordingly it provides a robust, easy to use C
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....

 API
Application programming interface
An application programming interface is a source code based specification intended to be used as an interface by software components to communicate with each other...

. The API is divided into two parts: the Lua core and the Lua auxiliary library.

The Lua API is fairly straightforward because its design eliminates the need for manual reference management
Reference counting
In computer science, reference counting is a technique of storing the number of references, pointers, or handles to a resource such as an object, block of memory, disk space or other resource...

 in C code, unlike Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...

’s API. The API, like the language, is minimalistic. Advanced functionality is provided by the auxiliary library, which consists largely of preprocessor
Preprocessor
In computer science, a preprocessor is a program that processes its input data to produce output that is used as input to another program. The output is said to be a preprocessed form of the input data, which is often used by some subsequent programs like compilers...

 macros which make complex table operations more palatable.

Stack

The Lua C API is stack
Stack (data structure)
In computer science, a stack is a last in, first out abstract data type and linear data structure. A stack can have any abstract data type as an element, but is characterized by only three fundamental operations: push, pop and stack top. The push operation adds a new item to the top of the stack,...

 based. Lua provides functions to push and pop most simple C data types (integers, floats, etc.) to and from the stack, as well as functions for manipulating tables through the stack. The Lua stack is somewhat different from a traditional stack; the stack can be indexed directly, for example. Negative indices indicate offsets from the top of the stack (for example, −1 is the last element), while positive indices indicate offsets from the bottom.

Marshalling data between C and Lua functions is also done using the stack. To call a Lua function, arguments are pushed onto the stack, and then the lua_call is used to call the actual function. When writing a C function to be directly called from Lua, the arguments are popped from the stack.

Special tables

The C API also provides several special tables, located at various “pseudo-indices” in the Lua stack. At LUA_GLOBALSINDEX is the globals table, _G from within Lua, which is the main namespace
Namespace (computer science)
A namespace is an abstract container or environment created to hold a logical grouping of unique identifiers or symbols . An identifier defined in a namespace is associated only with that namespace. The same identifier can be independently defined in multiple namespaces...

. There is also a registry located at LUA_REGISTRYINDEX where C programs can store Lua values for later retrieval.

Extension and binding

It is possible to write extension modules using the Lua API. Extension modules are shared objects which can be used to extend the functionality of the interpreter by providing native facilities to Lua scripts. From the Lua side, such a module appears as a namespace table holding its functions and variables. Lua scripts may load extension modules using require.

A growing collection of modules known as rocks are available through a package management system
Package management system
In software, a package management system, also called package manager, is a collection of software tools to automate the process of installing, upgrading, configuring, and removing software packages for a computer's operating system in a consistent manner...

 called LuaRocks, in the spirit of CPAN
CPAN
CPAN, the Comprehensive Perl Archive Network, is an archive of nearly 100,000 modules of software written in Perl, as well as documentation for it. It has a presence on the World Wide Web at and is mirrored worldwide at more than 200 locations...

, RubyGems
RubyGems
RubyGems is a package manager for the Ruby programming language that provides a standard format for distributing Ruby programs and libraries , a tool designed to easily manage the installation of gems, and a server for distributing them. It is analogous to EasyInstall for the Python programming...

 and Python Eggs.
Other sources include LuaForge
LuaForge
LuaForge is an open source code repository and collaborative software development management system for programmers and projects related to the Lua programming language., there are more than five hundred projects in a software catalog of LuaForge....

 and the Lua Addons directory of lua-users.org wiki.

Prewritten Lua bindings
Language binding
In computing, a binding from a programming language to a library or OS service is an API providing that service in the language.Many software libraries are written in systems programming languages such as C or C++...

 exist for most popular programming languages, including other scripting languages. For C++, there are a number of template-based approaches and some automatic binding generators.

Video games

In video game development
Game development
Game development is the software development process by which a video game is developed. Development is undertaken by a game developer, which may range from a single person to a large business. Mainstream games are normally funded by a publisher and take several years to develop. Indie games can...

, Lua is widely used as a scripting language
Scripting language
A scripting language, script language, or extension language is a programming language that allows control of one or more applications. "Scripts" are distinct from the core code of the application, as they are usually written in a different language and are often created or at least modified by the...

 by game programmers, perhaps owing to how easy it is to embed, its fast execution, and its small learning curve.
In June 2010, Apple Computer
Apple Computer
Apple Inc. is an American multinational corporation that designs and markets consumer electronics, computer software, and personal computers. The company's best-known hardware products include the Macintosh line of computers, the iPod, the iPhone and the iPad...

 altered the terms of use for its iOS SDK, the software development kit
Software development kit
A software development kit is typically a set of software development tools that allows for the creation of applications for a certain software package, software framework, hardware platform, computer system, video game console, operating system, or similar platform.It may be something as simple...

 for its iOS operating system, allowing the use of Lua. The company's terms of use had formerly specified that "no interpreted code may be downloaded or used in an Application except for code that is interpreted and run by Apple’s Documented APIs and built-in interpreter(s).", which at the time were limited to Objective-C
Objective-C
Objective-C is a reflective, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.Today, it is used primarily on Apple's Mac OS X and iOS: two environments derived from the OpenStep standard, though not compliant with it...

, C
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....

, C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

 and JavaScript
JavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....

.

Other

Other applications using Lua include:

  • 3DMLW plugin
    3DMLW
    3DMLW is an XML-based Markup Language for representing interactive 3D and 2D content on the World Wide Web. It serves as a cornerstone for a broader platform also referred to as 3DMLW.3DMLW platform=...

     uses Lua scripting for animating 3D
    3D computer graphics
    3D computer graphics are graphics that use a three-dimensional representation of geometric data that is stored in the computer for the purposes of performing calculations and rendering 2D images...

     and handling different events.
  • Adobe Photoshop Lightroom uses Lua for its user interface.
  • Apache HTTP Server
    Apache HTTP Server
    The Apache HTTP Server, commonly referred to as Apache , is web server software notable for playing a key role in the initial growth of the World Wide Web. In 2009 it became the first web server software to surpass the 100 million website milestone...

     can use Lua anywhere in the request process (since version 2.3, via the core mod_lua module).
  • Awesome
    Awesome (window manager)
    awesome is a dynamic window manager for the X Window System developed in the C and Lua programming languages. The latter is also used for configuring and extending the window manager. Its development began as a fork of dwm...

    , a window manager
    Window manager
    A window manager is system software that controls the placement and appearance of windows within a windowing system in a graphical user interface. Most window managers are designed to help provide a desktop environment...

    , is written partly in Lua, also using it as its configuration file format
  • The Canon Hack Development (CHDK), an open source firmware for Canon cameras, uses Lua as one of two scripting languages.
  • Celestia
    Celestia
    Celestia is a 3D astronomy program created by Chris Laurel. The program is based on the Hipparcos Catalogue and allows users to travel through an extensive universe, modeled after reality, at any speed, in any direction and at any time in history...

    , the astronomy educational program, uses Lua as its scripting language.
  • Cisco
    Cisco Systems
    Cisco Systems, Inc. is an American multinational corporation headquartered in San Jose, California, United States, that designs and sells consumer electronics, networking, voice, and communications technology and services. Cisco has more than 70,000 employees and annual revenue of US$...

     uses Lua to implement Dynamic Access Policies within the Adaptive Security Appliance
    Cisco ASA
    In computer networking, Cisco ASA 5500 Series Adaptive Security Appliances, or simply Cisco ASA 5500 Series, is Cisco's line of network security devices introduced in 2005, that succeeded three existing lines of popular Cisco products:...

    .
  • Custom applications for the Creative Technology
    Creative Technology
    Creative Technology Ltd. is a Singapore-based global company headquartered in Jurong East, Singapore. The principal activities of the company and its subsidiaries consist of the design, manufacture and distribution of digitized sound and video boards, computers and related multimedia, and personal...

     Zen X-Fi2 portable media player can be created in Lua.
  • Damn Small Linux
    Damn Small Linux
    Damn Small Linux or DSL is a computer operating system for the x86 family of personal computers. It is free and open source software under the terms of GNU GPL and other free and open source licenses. It was designed to run graphical applications on older PC hardware—for example, machines with...

     uses Lua to provide desktop-friendly interfaces for command-line utilities without sacrificing lots of disk space.
  • Dolphin Computer Access
    Dolphin Computer Access
    Dolphin Computer Access is a British company that designs, creates and sells software for people who are blind or have vision and print impairments, Dyslexia and other specific learning difficulties. The company was set up in 1986 and now has offices in the UK, US and Sweden...

     uses Lua scripting to make inaccessible applications accessible
    Accessibility
    Accessibility is a general term used to describe the degree to which a product, device, service, or environment is available to as many people as possible. Accessibility can be viewed as the "ability to access" and benefit from some system or entity...

     for visually impaired
    Visual impairment
    Visual impairment is vision loss to such a degree as to qualify as an additional support need through a significant limitation of visual capability resulting from either disease, trauma, or congenital or degenerative conditions that cannot be corrected by conventional means, such as refractive...

     computer users with their screen reader
    Screen reader
    A screen reader is a software application that attempts to identify and interpret what is being displayed on the screen . This interpretation is then re-presented to the user with text-to-speech, sound icons, or a Braille output device...

     – SuperNova.
  • Eyeon's Fusion
    Eyeon Fusion
    Fusion is an image compositing software program created by eyeon Software Inc. It is typically used to create visual effects and digital compositing for film, HD and commercials...

     compositor uses embedded Lua for internal and external scripts and also plugin prototyping.
  • A fork of the NES
    Nintendo Entertainment System
    The Nintendo Entertainment System is an 8-bit video game console that was released by Nintendo in North America during 1985, in Europe during 1986 and Australia in 1987...

     emulator
    Emulator
    In computing, an emulator is hardware or software or both that duplicates the functions of a first computer system in a different second computer system, so that the behavior of the second system closely resembles the behavior of the first system...

     FCE Ultra
    FCE Ultra
    FCEUX is an open source Nintendo Entertainment System and Family Computer Disk System emulator. It is a merger of various forks of FCE Ultra.-Multiplayer support:...

     called FCEUX allows for extensions or modifications to games via Lua scripts.
  • FreePOPs
    FreePOPs
    FreePOPs is an extensible mail proxy. Its primary use is to allow checking and downloading of e-mail from webmails from any conventional POP3 client program, avoiding the need to use a Web browser. It can also be used as an aggregator for RSS feeds and more....

    , an extensible mail proxy, uses Lua to power its web front-end.
  • Ginga
    Ginga (SBTVD Middleware)
    Ginga is the middleware specification for the Brazilian Digital TV System . Ginga was developed based on a set of standardized technologies, such as ITU-T J.200, and also adding innovations developed by Brazilian researchers...

    , the middleware for Brazilian Digital Television System ( SBTVD or ISDB-T ), uses Lua as a script language to its declarative environment, Ginga-NCL. In Ginga-NCL, Lua is integrated as media objects (called NCLua) inside NCL ( Nested Context Language
    Nested Context Language
    Nested Context Language is a declarative authoring language for hypermedia documents.NCL is an XML application language, which provides several facilities for authoring a complete hypermedia document with synchronization relationships among its components...

     ) documents.
  • The drawing editor Ipe
    Ipe (program)
    Ipe extensible drawing editor is a free vector graphics editor for creating figures in PDF or EPS format. It can be used for making small figures for inclusion into LaTeX documents as well as making multi-page PDF presentations....

     (mainly used for producing figures with LaTeX
    LaTeX
    LaTeX is a document markup language and document preparation system for the TeX typesetting program. Within the typesetting system, its name is styled as . The term LaTeX refers only to the language in which documents are written, not to the editor used to write those documents. In order to...

     labeling) uses Lua for its functionality and script extensions.
  • Lego Mindstorms NXT
    Lego Mindstorms NXT
    Lego Mindstorms NXT is a programmable robotics kit released by Lego in late July 2006.It replaced the first-generation Lego Mindstorms kit, which was called the Robotics Invention System. The base kit ships in two versions: the Retail Version and the Education Base Set . It comes with the NXT-G...

     and NXT 2.0
    Lego Mindstorms NXT 2.0
    Lego Mindstorms NXT 2.0 is the newest set from LEGO's Lego Mindstorms series, launched on August 5, 2009 at the Lego Shop in the U.S. The set contains 619 pieces, including a new sensor that can detect colors. It is priced at approximately 280 US $ or 230 £....

     can be scripted with Lua using third-party software.
  • lighttpd
    Lighttpd
    lighttpd is an open-source web server more optimized for speed-critical environments than common products while remaining standards-compliant, secure and flexible...

     web server uses Lua for hook scripts as well as a modern replacement for the Cache Meta Language
    Cache Meta Language
    Cache Meta Language is a computer programming language used to configure high-speed caching functionality in web server software such as lighttpd, which couples the functionality with that of memcache, a memory-based caching system....

    .
  • Version 2.01 of the profile management software for Logitech
    Logitech
    Logitech International S.A. is a global provider of personal peripherals for computers and other digital platforms headquartered in Romanel-sur-Morges, Switzerland. The company develops and markets products like peripheral devices for PCs, including keyboards, mice, microphones, game controllers...

    ’s G15
    Logitech G15
    The Logitech G15 is a keyboard produced by Logitech designed specifically for gamers. The original version of this keyboard included 18 macro keys each with 3 different states making a total of 54 macros available, a button to record quick macros, and a blue backlit monochrome LCD .- Game and...

     gaming keyboard uses Lua as its scripting language.
  • LuaTeX
    LuaTeX
    LuaTeX is a TeX based computer typesetting system which started as a version of pdfTeX with a Lua scripting engine embedded. After some experiments it was adopted by the pdfTeX team as a successor to pdfTeX . Later in the project some functionality of Aleph was included...

    , the designated successor of pdfTeX
    PdfTeX
    The computer program pdfTeX is an extension of Knuth's typesetting program TeX, and was originally written and developed into a publicly usable product by Hàn Thế Thành as a part of the work for his PhD thesis at the Faculty of Informatics, Masaryk University, Brno...

    , allows extensions to be written in Lua.
  • MikroTik RouterOS has beta support of Lua in 4.x, and planned support in 5.x.
  • Multimedia Fusion Developer 2
    Clickteam
    Clickteam is a software company, founded in 1993 by François Lionet, Yves Lamoureux and Francis Poulain, headquartered in Paris, France. Clickteam is perhaps best known for the creation of a script-free programming tool that allows users to create video games or other interactive software using a...

     has a Lua extension that allows games and applications created with it to run Lua scripts.
  • MySQL Workbench
    MySQL Workbench
    MySQL Workbench is a visual database design tool that integrates SQL development, administration, database design, creation and maintenance into a single integrated development environment for the MySQL database system...

     uses Lua for its extensions & add-ons.
  • nmap
    Nmap
    Nmap is a security scanner originally written by Gordon Lyon used to discover hosts and services on a computer network, thus creating a "map" ofthe network...

     network security scanner uses Lua as the basis for its scripting language, called nse.
  • Wavecom's GSM firmware Open AT OS allows user applications to be written in Lua.
  • Project Dogwaffle Professional
    Project Dogwaffle
    Project Dogwaffle is a raster graphics editor with animation capabilities.The program, written by Dan Ritchie, runs on the Windows platform and has both freeware and commercial versions. The commercial version, PD Pro Digital Painter, is updated frequently while the most recent freeware version is...

     offers Lua scripting to make filters through the DogLua filter. Lua filters can be shared between Project Dogwaffle, GIMP
    GIMP
    GIMP is a free software raster graphics editor. It is primarily employed as an image retouching and editing tool and is freely available in versions tailored for most popular operating systems including Microsoft Windows, Apple Mac OS X, and Linux.In addition to detailed image retouching and...

    , Pixarra Twistedbrush and ArtWeaver.
  • Prosody
    Prosody (software)
    Prosody is a cross-platform XMPP server written in Lua. Its development goals include low resource usage, ease-of-use, and extensibility.- History :...

     is a cross-platform
    Cross-platform
    In computing, cross-platform, or multi-platform, is an attribute conferred to computer software or computing methods and concepts that are implemented and inter-operate on multiple computer platforms...

     Jabber/XMPP
    Extensible Messaging and Presence Protocol
    Extensible Messaging and Presence Protocol is an open-standard communications protocol for message-oriented middleware based on XML . The protocol was originally named Jabber, and was developed by the Jabber open-source community in 1999 for near-real-time, extensible instant messaging , presence...

     server
    Server (computing)
    In the context of client-server architecture, a server is a computer program running to serve the requests of other programs, the "clients". Thus, the "server" performs some computational task on behalf of "clients"...

     written in Lua.
  • Reason Digital Audio Workstation, Lua is used to describe Remote codecs.
  • Renoise
    Renoise
    Renoise is a contemporary digital audio workstation based upon the heritage and development of tracker software. Its primary use is the composition of music using sound samples, soft synths, and effects plug-ins. It is also able to interface with MIDI and OSC equipment...

     audio tracker, in which Lua scripting is used to extend functionality.

  • Rockbox
    Rockbox
    Rockbox is a replacement for the standard firmware in various forms of digital audio players . It offers an alternative to the player's operating system, in many cases without removing the original firmware, which provides a plug-in architecture for adding various enhancements and functions...

    , the open-source digital audio player firmware, supports plugins written in Lua.
  • New versions of SciTE
    SciTE
    SciTE or SCIntilla based Text Editor is a cross-platform text editor written by Neil Hodgson using the Scintilla editing component. It is licensed under a minimal version of the Historical Permission Notice and Disclaimer...

     editor can be extended using Lua.
  • Snort
    Snort (software)
    Snort is a free and open source network intrusion prevention system and network intrusion detection system , created by Martin Roesch in 1998...

     intrusion detection system includes a Lua interpreter since 3.0 beta release.
  • The Squeezebox music players from Logitech support plugins written in Lua on recent models (Controller, Radio and Touch).
  • Vim
    Vim (text editor)
    Vim is a text editor written by Bram Moolenaar and first released publicly in 1991. Based on the vi editor common to Unix-like systems, Vim is designed for use both from a command line interface and as a standalone application in a graphical user interface...

     has Lua scripting support starting with version 7.3.
  • VLC media player
    VLC media player
    VLC media player is a free and open source media player and multimedia framework written by the VideoLAN project.VLC is a portable multimedia player, encoder, and streamer supporting many audio and video codecs and file formats as well as DVDs, VCDs, and various streaming protocols. It is able to...

     uses Lua to provide scripting support.
  • Wireshark
    Wireshark
    Wireshark is a free and open-source packet analyzer. It is used for network troubleshooting, analysis, software and communications protocol development, and education...

     network packet analyzer allows protocol dissectors and post-dissector taps to be written in Lua.
  • GrafX2
    GrafX2
    GrafX2 is a bitmap graphics editor inspired by the Amiga programs Deluxe Paint and Brilliance . It is free software and distributed under GNU General Public License.- History :...

    , a pixel-art editor, can run Lua scripts for simple picture processing or generative illustration.


Further reading

(1st ed. is available online) – Interview with Roberto Ierusalimschy – How the embeddability of Lua impacted its design

External links

The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK