Lua: Difference between revisions

Content deleted Content added
m Disambiguate 3D to 3D computer graphics using popups
m Added an oxford comma when listing the creators
 
Line 1:
{{Short description|Lightweight programming language}}
{{nofootnotes|article}}
{{tooshortother}}
{{Use dmy dates|date=February 2021}}{{Infobox programming language
| name = Lua
| logo = Lua-Logo.svg
| logo size = 140px
| paradigm = [[Multi-paradigm programming language|Multi-paradigm]]: [[scripting language|scripting]], [[imperative programming|imperative]], [[functional programming|functional]]
| screenshot = Excerpt of Coordinates module in Lua.png
| year = [[1993]]
| screenshot_size = 250px
| designer = [[Roberto Ierusalimschy]] </br> Waldemar Celes </br> Luiz Henrique de Figueiredo
| screenshot caption = Screenshot of Lua code from a [[WP:Lua|Wikipedia Lua module]] using the [[MediaWiki]] [[mw:Extension:Scribunto|Scribunto]] extension
| developer =
| paradigm = [[Multi-paradigm]]: [[Scripting language|scripting]], [[Imperative programming|imperative]] ([[Procedural programming|procedural]], [[Prototype-based programming|prototype-based]], [[Object-oriented programming|object-oriented]]), [[Functional programming|functional]], [[Metaprogramming|meta]], [[Reflective programming|reflective]]
| latest_release_version = 5.1.4
| year = {{Start date and age|1993|df=yes}}
| latest_release_date = [[August 22]] [[2008]]
| designer = [[Roberto Ierusalimschy]]<br/>Waldemar Celes<br/>Luiz Henrique de Figueiredo
| typing = [[Type_system#Dynamic_typing|Dynamic]], [[Type_system#Strong_and_weak_typing|weak]] ("[[Duck Typing|duck]]")
| developer =
| implementations =
| latest release version = {{wikidata|property|reference|edit |Q207316 |P348}}
| dialects =
| latest release date = {{start date and age|{{wikidata|qualifier|Q207316|P348|P577}}}}
| influenced_by = [[Scheme (programming language)|Scheme]], [[Icon programming language|Icon]]
| latest preview version =
| influenced = [[Io (programming language)|Io]], [[Squirrel programming language|Squirrel]], [[Dao (programming language)|Dao]]
| latest preview date =
| operating_system = [[Cross-platform]]
| typing = [[Dynamic typing|Dynamic]], [[Strong and weak typing|strong]], [[Duck typing|duck]]
| license = [[MIT License]]
| implementations = [//www.lua.org/download.html Lua], [[LuaJIT]], [//github.com/luavela/luavela LuaVela],
| website = [http://www.lua.org www.lua.org]
[https://www.moonsharp.org/ MoonSharp],
| programming language = [[ANSI C]]
| dialects = [https://www.nongnu.org/gsl-shell/ GSL Shell], [https://luau.org Lua''u'']
| influenced by = [[C++]], [[CLU (programming language)|CLU]], [[Modula]], [[Scheme (programming language)|Scheme]], [[SNOBOL]]
| influenced = [[GameMonkey Script|GameMonkey]],<!--2003--> [[Io (programming language)|Io]],<!--2002--> [[JavaScript]]{{Citation needed|date=November 2022}}, [[Julia (programming language)|Julia]],<!--2006--> [[Red (programming language)|Red]], [[Ring (programming language)|Ring]],<ref name="The Ring programming language and other languages">{{cite web |url=https://ring-lang.sourceforge.net/doc1.6/introduction.html#ring-and-other-languages |title=The Ring programming language and other languages |author=Ring Team |date=5 December 2017 |work=ring-lang.net |access-date=5 December 2017 |archive-date=25 December 2018 |archive-url=https://web.archive.org/web/20181225175312/http://ring-lang.sourceforge.net/doc1.6/introduction.html#ring-and-other-languages |url-status=dead}}</ref> [[Ruby (programming language)|Ruby]],{{Citation needed|date=November 2022}} [[Squirrel (programming language)|Squirrel]],<!--2011--> [[C--]], [[Roblox Studio|Luau]],
| operating system = [[Cross-platform software|Cross-platform]]
| license = [[MIT License|MIT]]
| website = {{url|https://lua.org/}}
| file ext = <code>.lua</code>
| wikibooks =
}}
 
'''Lua''' {{Noexcerpt|({{IPAc-en|ˈ|l|uː|ə}} {{Respell|LOO|ə}}; from {{Langx|pt|[[wikt:lua#Portuguese|lua]]}} {{IPA|pt|ˈlu(w)ɐ|}} meaning ''[[moon]]'')}} is a [[Lightweight programming language|lightweight]], [[High-level programming language|high-level]], [[multi-paradigm programming language|multi-paradigm]] [[programming language]] designed mainly for [[Scripting language|embedded use]] in applications.<ref name="luaspe">{{cite journal|last1=Ierusalimschy|first1=Roberto|last2=de Figueiredo|first2=Luiz Henrique|last3=Filho|first3=Waldemar Celes|title=Lua—An Extensible Extension Language|journal=Software: Practice and Experience|date=June 1996|volume=26|issue=6|pages=635–652|doi=10.1002/(SICI)1097-024X(199606)26:6<635::AID-SPE26>3.0.CO;2-P|s2cid=61066194 |url=https://www.lua.org/spe.html|access-date=24 October 2015|url-access=subscription}}</ref> Lua is [[cross-platform software]], since the [[Interpreter (computing)|interpreter]] of [[Compiler|compiled]] [[bytecode]] is written in [[ANSI C]],<ref name=luaabout>{{cite web |url=https://www.lua.org/about.html#why |title=About Lua |publisher=Lua.org |access-date=2011-08-11}}</ref> and Lua has a relatively simple C application programming interface ([[API]]) to embed it into applications.<ref>{{cite magazine |last1=Takhteyev |first1=Yuri |date=21 April 2013 |url=https://www.foreignaffairs.com/articles/139332/yuri-takhteyev/from-brazil-to-wikipedia?page=2 |title=From Brazil to Wikipedia |magazine=[[Foreign Affairs]] |access-date=25 April 2013}}</ref>
In [[computing]], '''Lua''' ({{pronEng|ˈluː.a}} LOO-ah) is a [[lightweight languages|lightweight]], [[Reflection (computer science)|reflective]], [[imperative programming|imperative]] and [[procedural programming|procedural]] [[programming language]], designed as a [[scripting language]] with [[extension language|extensible]] [[semantics]] as a primary goal. The name means ‘moon’ in [[Portuguese language|Portuguese]]. It has enjoyed great popularity in the videogames industry and is known for having a simple yet powerful [[C (programming language)|C]] [[Application programming interface|API]].
 
Lua originated in 1993 as a language for extending [[application software|software applications]] to meet the increasing demand for customization at the time. It provided the basic facilities of most [[procedural programming]] languages, but more complicated or [[___domain-specific language|___domain-specific]] features were not included; rather, it included mechanisms for extending the language, allowing programmers to implement such features. As Lua was intended to be a general embeddable extension language, the designers of Lua focused on improving its [[Profiling (computer programming)|speed]], [[Porting|portability]], extensibility and ease-of-use in development.
 
== History ==
Lua was created in 1993 by [[Roberto Ierusalimschy]], 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]].
 
From 1977 until 1992, Brazil had a policy of strong [[trade barrier]]s (called a market reserve) for [[computer hardware]] and [[software]], believing that Brazil could and should produce its own hardware and software. In that climate, Tecgraf's clients could not afford, either politically or financially, to buy customized software from abroad; under the market reserve, clients would have to go through a complex bureaucratic process to prove their needs couldn't be met by Brazilian companies. Those reasons led Tecgraf to implement the basic tools it needed from scratch.<ref name=hopl2007>{{cite book |last1=Ierusalimschy |first1=R. |author1-link=Roberto Ierusalimschy |last2=Figueiredo |first2=L. H. |last3=Celes |first3=W. |year=2007 |title=Proceedings of the third ACM SIGPLAN conference on History of programming languages |contribution=The evolution of Lua |contribution-url=https://www.lua.org/doc/hopl.pdf |doi=10.1145/1238844.1238846 |url=https://www.acm.org/sigs/sigplan/hopl |pages=2–1–2–26 |isbn=978-1-59593-766-7 |s2cid=475143}}</ref><!-- More sources about the Brazilian market reserve are needed, as it helps further prove how it affected the development of the Lua language.-->
 
Lua's predecessors were the data-description and configuration languages Simple Object Language (SOL) and Data-Entry Language (DEL).<ref name="luahist2001">{{cite web|url=https://www.lua.org/history.html|title=The evolution of an extension language: a history of Lua|year=2001|access-date=2008-12-18}}
<!-- {{cite journal |last1=Ierusalimschy |first1=R. |author1-link=Roberto Ierusalimschy |last2=Figueiredo |first2=L. H. |last3=Celes |first3=W. |year=2001 |contribution=The evolution of an extension language: a history of Lua |contribution-url=https://www.lua.org/history.html |title=Proceedings of V Brazilian Symposium on Programming Languages |pages=B–14–B–28}} --></ref> 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]] 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 ''The Evolution of Lua'', the language's authors wrote:<ref name=hopl2007/>
 
{{Blockquote|In 1993, the only real contender was [[Tcl]], 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 (programming language)|LISP]] or [[Scheme (programming language)|Scheme]] because of their unfriendly syntax. [[Python (programming language)|Python]] 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&nbsp;... 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'' meaning "Sun" in Portuguese, and ''Lua'' meaning "Moon"). Lua [[Syntax (programming languages)|syntax]] for control structures was mostly borrowed from [[Modula]] (<code>if</code>, <code>while</code>, <code>repeat</code>/<code>until</code>), but also had taken influence from [[CLU (programming language)|CLU]] (multiple assignments and multiple returns from function calls, as a simpler alternative to [[Call by reference|reference parameters]] or explicit [[pointer (computer programming)|pointers]]), [[C++]] ("neat idea of allowing a [[local variable]] to be declared only where we need it"<ref name=hopl2007/>), [[SNOBOL]] and [[AWK]] ([[associative array]]s). In an article published in ''[[Dr. Dobb's Journal]]'', Lua's creators also state that LISP and Scheme with their single, ubiquitous data-structure mechanism (the [[List (abstract data type)|list]]) were a major influence on their decision to develop the table as the primary data structure of Lua.<ref name=ddj96>{{cite news |last1=Figueiredo |first1=L. H. |last2=Ierusalimschy |first2=R. |last3=Celes |first3=W. |date=December 1996 |title=Lua: an Extensible Embedded Language. A few metamechanisms replace a host of features |magazine=Dr. Dobb's Journal |volume=21 |issue=12 |pages=26–33 |url=https://www.lua.org/ddj.html}}</ref>
Lua was created in 1993 by [[Roberto Ierusalimschy]], [[Luiz Henrique de Figueiredo]], and [[Waldemar Celes]], members of the Computer Graphics Technology Group at [[PUC-Rio]], the [[Pontifical University]] of [[Rio de Janeiro]], in [[Brazil]]. Versions of Lua prior to version 5.0 were released under a license similar to the [[BSD licenses|BSD license]]. From version 5.0 onwards, Lua has been licensed under the [[MIT License]].
 
Lua [[semantics]] have been increasingly influenced by Scheme over time,<ref name=hopl2007/> especially with the introduction of [[anonymous function]]s and full [[Scope (computer science)#Lexical scope vs. dynamic scope|lexical scoping]]. Several features were added in new Lua versions.
Some of its closest relatives include [[Icon (programming language)|Icon]] for its design and [[Python (programming language)|Python]] for its ease of use by non-programmers. In an article published in ''[[Dr. Dobb's Journal]]'', Lua’s creators also state that [[Lisp (programming language)|Lisp]] and [[Scheme (programming language)|Scheme]] with their single, ubiquitous data structure mechanism (the [[Scheme (programming language)#Lists|list]]) were a major influence on their decision to develop the table as the primary data structure of Lua.[http://www.lua.org/ddj.html]
 
Versions of Lua prior to version 5.0 were released under a license similar to the [[BSD licenses|BSD license]]. From version 5.0 onwards, Lua has been licensed under the [[MIT License]]. Both are [[permissive free software licences]] and are almost identical.
Lua has been used in many applications, both commercial and non-commercial. See the [[#Applications|Applications]] section for a detailed list.
 
== Features ==
Lua is commonly described as a "[[Multimulti-paradigm programming language|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 [[inheritanceInheritance (computerobject-oriented scienceprogramming)|inheritance]], but allows it to be implemented relatively easily with [[#Metatables|metatables]]. Similarly, Lua allows programmers to implement [[namespace (programming)|namespaces]]s, [[classesClass (computer scienceprogramming)|classes]], and other related features using its single table implementation; [[first-class function]]s allow the employment of many powerful techniques from [[functional programming]]; and full lexical [[Scopelexical (programming)|scoping]] allows fine-grained [[information hiding]] to enforce the [[principle of least privilege]].
 
In general, Lua strives to provide simple, flexible [[metaprogramming|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 [[lightweightLightweight languagesprogramming language|light]] —in fact,; the full reference [[interpreter (computing)|interpreter]] is only about 150247&nbsp;[[Kilobyte|kB]] compiled—compiled<ref name=luaabout/> and easily adaptable to a broad range of applications.<!-- The full reference interpreter? Is this talking about the interpreter and the reference manual together? If so, this should be made more clear. -->
 
Lua isAs a [[dynamically typed]] language intended for use as an [[extension language|extension]] or [[scripting language]], andLua is compact enough to fit on a variety of host platforms. It supports only a small number of atomic data structures such as [[booleanBoolean data type|Boolean]] values, [[number]]snumbers (double-precision [[floating point]] and [[64-bit computing|64-bit]] [[integer]]s by default), and [[string (computer science)|strings]]. Typical data structures such as [[arrayArray data structure|arrays]]s, [[set (computer science)|sets]], [[hash table]]s, [[List (computing)|lists]], and [[record (computer science)|recordrecords]]s can be represented using Lua’sLua's single native data structure, the table, which is essentially a heterogeneous [[mapassociative (computer science)|maparray]].
 
Lua implements a small set of advanced features such as [[first-class function]]s, [[Garbage collection (computer science)|garbage collection]], [[Closure (computer science)|closures]], proper [[Tail recursion|tail calls]], [[Type conversion|coercion]] (automatic conversion between string and number values at run time), [[coroutine]]s (cooperative multitasking) and [[Dynamic loading|dynamic module loading]].
Lua has no built-in support for namespaces and [[object-oriented]] programming. Instead, metatable and metamethods are used to extend the language to support both programming paradigms in an elegant and straight-forward manner.
 
=== Syntax ===
Lua implements a small set of advanced features such as [[first-class function]]s, [[garbage collection (computer science)|garbage collection]], [[Closure (computer science)|closures]], proper [[Tail recursion|tail call]]s, [[Type conversion|coercion]] (automatic conversion between string and number values at run time), [[coroutine]]s (cooperative multitasking) and dynamic module loading.
The classic [["Hello, World!" program]] can be written as follows, with or without parentheses:<ref>{{cite web |url=https://www.lua.org/pil/1.html |title=Programming in Lua : 1}}</ref>{{efn|[[Syntactic sugar]], a table construct or literal string following an identifier is a valid function call.<ref>{{cite web |url=https://www.lua.org/manual/5.0/manual.html#2.5.7 |title=Lua 5.0 Reference Manual, 2.5.7, Function Calls}}</ref>}}
<syntaxhighlight lang="lua">
print("Hello, World!")
</syntaxhighlight>
<syntaxhighlight lang="lua">
print "Hello, World!"
</syntaxhighlight>
 
The declaration of a variable, without a value.
By including only a minimum set of data types, Lua attempts to strike a balance between power and size.
<syntaxhighlight lang="lua">
local variable
</syntaxhighlight>
 
The declaration of a variable with a value of 10.
=== Example code ===
<syntaxhighlight lang="lua">
local students = 10
</syntaxhighlight>
 
A [[Comment (computer programming)|comment]] in Lua starts with a double-hyphen and runs to the end of the line, similar to [[Ada (programming language)|Ada]], [[Eiffel (programming language)|Eiffel]], [[Haskell]], [[SQL]] and [[VHDL]]. Multi-line strings and comments are marked with double square brackets.
The classic [[hello world program]] can be written as follows:
<sourcesyntaxhighlight lang="lua">
-- Single line comment
print("Hello World!")
--[[
</source>
Multi-line comment
The [[factorial]] is an example of a [[recursion|recursive]] function:
--]]
<source lang="lua">
</syntaxhighlight>
 
{{anchor|Factorial example}}The [[factorial]] function is implemented in this example:<!-- referred to elsewhere in this article -->
<syntaxhighlight lang="lua">
function factorial(n)
iflocal nx == 0 then1
for i = 2, n do
return 1 -- A comment in Lua starts with a double-hyphen
x = x * i
else
return n * factorial(n - 1) -- and runs to the end of the line
end
return x
end
end
</syntaxhighlight>
 
=== Control flow ===
function factorial2(n) -- Shorter equivalent of the above
Lua has one type of [[Conditional (computer programming)|conditional]] test: <code>[[Conditional_(computer_programming)#If–then(–else)|if then end]]</code> with optional <code>else</code> and <code>elseif then</code> execution control constructs.
return n==0 and 1 or n*factorial2(n - 1)
 
The generic <code>if then end</code> statement requires all three keywords:
<syntaxhighlight lang="lua">
if condition then
--statement body
end
</syntaxhighlight>
 
An example of an <code>if</code> statement
<syntaxhighlight lang="lua">
if x ~= 10 then
print(x)
end
</syntaxhighlight>
 
The <code>else</code> keyword may be added with an accompanying statement block to control execution when the <code>if</code> condition evaluates to <code>false</code>:
<syntaxhighlight lang="lua">
if condition then
--statement body
else
--statement body
end
</syntaxhighlight>
 
An example of an <code>if else</code> statement
<syntaxhighlight lang="lua">
if x == 10 then
print(10)
else
print(x)
end
</syntaxhighlight>
 
Execution may also be controlled according to multiple conditions using the <code>elseif then</code> keywords:
<syntaxhighlight lang="lua">
if condition then
--statement body
elseif condition then
--statement body
else -- optional
--optional default statement body
end
</syntaxhighlight>
An example of an <code>if elseif else</code> statement
<syntaxhighlight lang="lua">
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
</syntaxhighlight>
 
Lua has four types of conditional loops: the [[while loop|<code>while</code> loop]], the <code>repeat</code> loop (similar to a [[do while loop|<code>do while</code> loop]]), the numeric [[for loop|<code>for</code> loop]] and the generic <code>for</code> loop.
<syntaxhighlight lang="lua">
--condition = true
 
while condition do
--statements
end
 
repeat
--statements
until condition
 
for i = first, last, delta do --delta may be negative, allowing the for loop to count down or up
--statements
--example: print(i)
end
</syntaxhighlight>
 
This generic <code>for</code> loop would iterate over the table <code>_G</code> using the standard iterator function <code>pairs</code>, until it returns <code>nil</code>:
<syntaxhighlight lang="lua">
for key, value in pairs(_G) do
print(key, value)
end
</syntaxhighlight>
 
Loops can also be [[Nesting (programming)|nested]] (put inside of another loop).
<syntaxhighlight lang="lua">
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
</syntaxhighlight>
print([[multiple
lines]]) --[[ Multi-line strings & comments are
adorned with double square brackets ]]
</source>
The second form of factorial function originates from Lua's [[short-circuit evaluation]] of boolean operators.
 
=== Functions ===
Lua’s treatment of functions as [[first-class function|first-class]] variables is shown in the following example, where the print function’s behavior is modified:
Lua's treatment of functions as [[first-class function|first-class]] values is shown in the following example, where the print function's behavior is modified:
<source lang="lua">
<syntaxhighlight lang="lua">
do
local oldprint = print
-- Store current print function as oldprint
function print(s)
print = function(s) -- Redefine print function
--[[ Redefine print function. The usual print function can still be used
if s == "foo" then
through oldprint("bar"). The new one has only one argument.]]
oldprint(s == "foo" and "bar" or s)
else
oldprint(s)
end
end
end
</syntaxhighlight>
</source>
Any future calls to <code>print</code> will now be routed through the new function, and thanksbecause toof Lua’sLua's [[scopeScope (programming)#Lexical scoping|lexical scoping]], the old print function will only be accessible by the new, modified print.
 
Lua also supports [[Closure (computer scienceprogramming)|closures]], as demonstrated below:
<sourcesyntaxhighlight lang="lua">
function makeaddfuncaddto(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 iswould be shorter than that of this anonymous
-- function, Lua creates a closure.]]
return x + y
end
end
fourplus = addto(4)
plustwo = makeaddfunc(2)
print(plustwofourplus(53)) -- Prints 7
</source>
A new closure for the variable <tt>x</tt> is created every time <tt>makeaddfunc</tt> is called, so that the anonymous function returned will always access its own <tt>x</tt> parameter. The closure is managed by Lua’s garbage collector, just like any other object.
 
--This can also be achieved by calling the function in the following way:
Extensible semantics is a key feature of Lua, and the “metatable” concept allows Lua’s tables to be customized in powerful and unique ways. The following example demonstrates an “infinite” table. For any <math>n</math>, <code>fibs[n]</code> will give the <math>n</math>th [[Fibonacci number]] using [[dynamic programming]] and [[memoization]].
print(addto(4)(3))
<source lang="lua">
--[[ This is because we are calling the returned function from 'addto(4)' with the argument '3' directly.
fibs = { 1, 1 } -- Initial values for fibs[1] and fibs[2].
This also helps to reduce data cost and up performance if being called iteratively.]]
setmetatable(fibs, { -- Give fibs some magic behavior.
</syntaxhighlight>
__index = function(name, n) -- Call this function if fibs[n] does not exist.
A new closure for the variable <code>x</code> is created every time <code>addto</code> is called, so that each new anonymous function returned will always access its own <code>x</code> parameter. The closure is managed by Lua's garbage collector, just like any other object.
name[n] = name[n - 1] + name[n - 2] -- Calculate and memoize fibs[n].
return name[n]
end
})
</source>
 
=== Tables ===
Tables are the most important data structurestructures (and, by design, the only complexbuilt-in [[composite data structuretype]]) in Lua, and are the foundation of all user-created types. They are associative arrays with addition of automatic numeric key and special syntax.
 
A table is a set of key and data pairs, where the data is referenced by key; in other words, it is a [[hash table|hashed]] heterogeneous associative array.
 
Tables are created using the <code>{}</code> constructor syntax.
 
<syntaxhighlight lang="lua">
a_table = {} -- Creates a new, empty table
</syntaxhighlight>
 
Tables are always passed by reference (see [[Call by sharing]]).
 
A key (index) can be any value except <code>nil</code> and [[NaN]], including functions.
The table is a collection of key and data pairs (known also as [[hash table|hashed]] [[heterogeneous]] [[associative array]]), where the data is referenced by key. The key (index) can be of any data type except nil. An integer key of <code>1</code> is considered distinct from a string key of <code>"1"</code>.
 
<syntaxhighlight lang="lua">
Tables are created using the {} constructor syntax:
a_table = {x = 10} -- Creates a new table, with one entry mapping "x" to the number 10.
<source lang="lua">
print(a_table["x"]) =-- {}Prints the value associated with --the Createsstring a newkey, emptyin this case table10.
</source>
Tables are always passed by reference:
<source lang="lua">
-- Creates a new table, with one associated entry. The string x mapping to
-- the number 10.
a_table = {x = 10}
-- Prints the value associated with the string key,
-- in this case 10.
print(a_table["x"])
b_table = a_table
a_tableb_table["x"] = 20 -- The value in the table has been changed to 20.
print(a_tableb_table["x"]) -- Prints 20.
print(a_table["x"]) -- PrintsAlso prints 20, because a_table and b_table both refer to the same table.
</syntaxhighlight>
print(b_table["x"])
 
</source>
A table is often used as [[object composition|structure]] (or [[Record (computer science)|record]]) by using [[string (computer science)|strings]] as keys. Because such use is very common, Lua features a special syntax for accessing such fields.<ref>{{cite web|url=https://www.lua.org/manual/5.1/manual.html#2.3|title=Lua 5.1 Reference Manual|access-date=2014-02-27|year=2014}}</ref>
==== Table as structure ====
 
Tables are often used as [[object composition|structure]]s (or objects) by using [[string (computer science)|strings]] as keys. Because such use is very common, Lua features a special syntax for accessing such fields.
<syntaxhighlight lang="lua">
Example:
<source lang="lua">
point = { x = 10, y = 20 } -- Create new table
print(point["x"]) -- Prints 10
print(point.x) -- Has exactly the same meaning as line above. The easier-to-read dot notation is just syntactic sugar.
</syntaxhighlight>
</source>
 
==== Table as namespace ====
 
By using a table to store related functions, it can act as a namespace.
 
<source lang="lua">
<syntaxhighlight lang="lua">
Point = {}
 
Point.new = function (x, y)
return {xPoint.new = function(x, y = y})
return {x = x, y = y} -- return {["x"] = x, ["y"] = y}
end
 
Point.set_x = function (point, x)
point.x = x -- point["x"] = x;
end
</syntaxhighlight>
</source>
 
==== Table as array ====
ByTables usingare automatically assigned a numerical key, theenabling tablethem resemblesto be used as an [[array]] data type]]. LuaThe arrays arefirst 1-based: the firstautomatic index is 1 rather than 0 as it is for many other programming languages (though an explicit index of 0 is allowed).
 
A numeric key <code>1</code> is distinct from a string key <code>"1"</code>.
 
<syntaxhighlight lang="lua">
A simple array of strings:
<source lang="lua">
array = { "a", "b", "c", "d" } -- Indices are assigned automatically.
print(array[2]) -- Prints "b". Automatic indexing in Lua starts at 1.
Line 166 ⟶ 287:
array[0] = "z" -- Zero is a legal index.
print(#array) -- Still prints 4, as Lua arrays are 1-based.
</syntaxhighlight>
</source>
 
An array of objects:
The length of a table <code>t</code> is defined to be any integer index <code>n</code> such that <code>t[n]</code> is not <code>nil</code> and <code>t[n+1]</code> is <code>nil</code>; moreover, if <code>t[1]</code> is <code>nil</code>, <code>n</code> can be zero. For a regular array, with non-nil values from 1 to a given <code>n</code>, its length is exactly that <code>n</code>, the index of its last value. If the array has "holes" (that is, nil values between other non-nil values), then <code>#t</code> can be any of the indices that directly precedes a <code>nil</code> value (that is, it may consider any such nil value as the end of the array).<ref>{{cite web|url=https://www.lua.org/manual/5.1/manual.html#2.5.5|title=Lua 5.1 Reference Manual|access-date=2012-10-16|year=2012}}</ref>
<source lang="lua">
 
<syntaxhighlight lang="lua">
ExampleTable =
{
{1, 2, 3, 4},
{5, 6, 7, 8}
}
print(ExampleTable[1][3]) -- Prints "3"
print(ExampleTable[2][4]) -- Prints "8"
</syntaxhighlight>
 
A table can be an array of objects.
 
<syntaxhighlight lang="lua">
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
-- array = { { x = 10, y = 20 }, { x = 30, y = 40 }, { x = 50, y = 60 } };
print(array[2].y) -- Prints 40
</syntaxhighlight>
</source>
 
Using a hash map to emulate an array is normally slower than using an actual array; however, Lua tables are optimized for use as arrays to help avoid this issue.<ref name=lobject_h_array>{{cite web|url=https://www.lua.org/source/5.1/lobject.h.html#array|title=Lua 5.1 Source Code|access-date=2011-03-24|year=2006}}</ref><!-- I'd like to find a message on the mailing list from one of the developers, but I can't. However, source code is a reasonably trustworthy reference. -->
 
=== Metatables ===
Extensible semantics is a key feature of Lua, and the metatable allows powerful customization of tables. The following example demonstrates an "infinite" table. For any <code>n</code>, <code>fibs[n]</code> will give the <code>n</code>-th [[Fibonacci number]] using [[dynamic programming]] and [[memoization]].
<syntaxhighlight lang="lua">
fibs = { 1, 1 } -- Initial values for fibs[1] and fibs[2].
setmetatable(fibs, {
__index = function(values, n) --[[__index is a function predefined by Lua,
it is called if key "n" does not exist.]]
values[n] = values[n - 1] + values[n - 2] -- Calculate and memoize fibs[n].
return values[n]
end
})
</syntaxhighlight>
 
=== Object-oriented programming ===
Although Lua does not have a built-in concept of [[class (computer science)|classes]], they[[object-oriented programming]] can be implementedemulated using twofunctions languageand features:tables. [[first-classAn function]]sobject andis tables.formed Byby placingputting functionsmethods and relatedfields data intoin a table, an object is formed. [[Inheritance (computerobject-oriented scienceprogramming)|Inheritance]] (both single and multiple) can be implemented viawith the “metatable” mechanism[[#Metatables|metatables]], telling the object to lookupdelegating nonexistent methods and fields into a parent object(s).
 
There is no such concept as “class”"class" with these techniques,; rather, [[prototype-based programming|“prototypes”prototypes]] are used, assimilar into [[Self (programming language)|Self]] or [[JavascriptJavaScript]]. New objects are created either with a [[factory method pattern|factory method]] (that constructs new objects from scratch) or by cloning an existing object.
 
Creating a basic [[Vector (geometry)|vector]] object:
Lua provides some [[syntactic sugar]] to facilitate object orientation. To declare [[Method (computer science)|member functions]] inside a prototype table, you can use <tt>function table:func(args)</tt>, which is equivalent to <tt>function table.func(self, args)</tt>. Calling class methods also makes use of the colon: <tt>object:func(args)</tt> is equivalent to <tt>object.func(object, args)</tt>.
<syntaxhighlight lang="lua">
local Vector = {}
local VectorMeta = { __index = Vector}
 
function Vector.new(x, y, z) -- The constructor
Creating a basic [[vector (geometry)|vector]] object:
return setmetatable({x = x, y = y, z = z}, VectorMeta)
<source lang="lua">
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, {
-- Overload the index event so that fields not present within the object are
-- looked up in the prototype Vector table
__index = Vector
})
return object
end
 
-- Declare another member function, to determine the
--function Vector.magnitude(self) of the vector -- Another method
return math.sqrt(self.x^2 + self.y^2 + self.z^2)
function Vector:mag()
end
 
local vec = Vector.new(0, 1, 0) -- Create a vector
print(vec.magnitude(vec)) -- Call a method (output: 1)
print(vec.x) -- Access a member variable (output: 0)
</syntaxhighlight>
 
Here, {{code |lang=lua|setmetatable}} tells Lua to look for an element in the {{code |lang=lua|Vector}} table if it is not present in the {{code |lang=lua|vec}} table. {{code |lang=lua|vec.magnitude}}, which is equivalent to {{code |lang=lua|vec["magnitude"]}}, first looks in the {{code |lang=lua|vec}} table for the {{code |lang=lua|magnitude}} element. The {{code |lang=lua|vec}} table does not have a {{code |lang=lua|magnitude}} element, but its metatable delegates to the {{code |lang=lua|Vector}} table for the {{code |lang=lua|magnitude}} element when it's not found in the {{code |lang=lua|vec}} table.
 
Lua provides some [[syntactic sugar]] to facilitate object orientation. To declare [[Method (computer science)|member functions]] inside a prototype table, one can use {{code |lang=lua |function table:func(args)}}, which is equivalent to {{code |lang=lua |function table.func(self, args)}}. Calling class methods also makes use of the colon: {{code |lang=lua |object:func(args)}} is equivalent to {{code |lang=lua |object.func(object, args)}}.
 
That in mind, here is a corresponding class with {{code|lang=lua|:}} syntactic sugar:
 
<syntaxhighlight lang="lua">
local Vector = {}
Vector.__index = Vector
 
function Vector:new(x, y, z) -- The constructor
-- Since the function definition uses a colon,
-- its first argument is "self" which refers
-- to "Vector"
return setmetatable({x = x, y = y, z = z}, self)
end
 
function Vector:magnitude() -- Another method
-- Reference the implicit object using self
return math.sqrt(self.x * self.x^2 + self.y * self.y^2 + self.z * self.z^2)
end
vec = Vector:new(0, 1, 0) -- Create a vector
print(vec:mag()) -- Call a member function using ":"
print(vec.x) -- Access a member variable using "."
</source>
 
local vec = Vector:new(0, 1, 0) -- Create a vector
== Internals ==
print(vec:magnitude()) -- Call a method (output: 1)
print(vec.x) -- Access a member variable (output: 0)
</syntaxhighlight>
 
==== Inheritance ====
Lua programs are not [[interpreted language|interpreted]] directly from the textual Lua file, but are [[compiler|compiled]] into [[bytecode]] which is then run on the Lua [[virtual machine]]. 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.
Lua supports using metatables to give Lua class inheritance.<ref>{{cite book|title=Programming in Lua, 4th Edition|page=165|author=Roberto Ierusalimschy}}</ref> In this example, we allow vectors to have their values multiplied by a constant in a derived class.
 
<syntaxhighlight lang="lua">
This example is the bytecode listing of the factorial function described above (in Lua 5.1.1):
local Vector = {}
Vector.__index = Vector
 
function <factorial.luaVector:1new(x,6> (10 instructionsy, 40z) bytes at 003D5818) -- The constructor
-- Here, self refers to whatever class's "new"
1 param, 3 slots, 0 upvalues, 1 local, 3 constants, 0 functions
-- method we call. In a derived class, self will
1 [2] EQ 0 0 -1 ; - 0
-- be the derived class; in the Vector class, self
2 [2] JMP 2 ; to 5
-- will be Vector
3 [3] LOADK 1 -2 ; 1
return setmetatable({x = x, y = y, z = z}, self)
4 [3] RETURN 1 2
end
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
 
function Vector:magnitude() -- Another method
There is also a free, third-party [[just-in-time compiler]] for the latest version (5.1) of Lua, called [http://luajit.org/luajit.html LuaJIT]. It’s very small (under 32kB of additional code) and can often improve the performance of a Lua program significantly. [http://luajit.org/luajit_performance.html]
-- Reference the implicit object using self
return math.sqrt(self.x^2 + self.y^2 + self.z^2)
end
 
-- Example of class inheritance
== C API ==
local VectorMult = {}
VectorMult.__index = VectorMult
setmetatable(VectorMult, Vector) -- Make VectorMult a child of Vector
 
function VectorMult:multiply(value)
Lua is intended to be embedded into other applications, and accordingly it provides a robust, easy to use [[C (programming language)|C]] [[Application Programming Interface|API]]. The API is divided into two parts: the Lua core [http://www.lua.org/manual/5.1/manual.html#3], and the Lua auxiliary library [http://www.lua.org/manual/5.1/manual.html#4].
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 vector
The Lua API is fairly straightforward because its unique design eliminates the need for manual [[Reference counting|reference management]] in C code, unlike [[Python (programming language)|Python]]’s API. The API, like the language, is minimalistic. Advanced functionality is provided by the auxiliary library, which consists largely of [[Preprocessor#Macros|preprocessor macros]] which make complex table operations more palatable.
print(vec:magnitude()) -- Call a method (output: 1)
print(vec.y) -- Access a member variable (output: 1)
vec:multiply(2) -- Multiply all components of vector by 2
print(vec.y) -- Access member again (output: 2)
</syntaxhighlight>
 
Lua also supports [[multiple inheritance]]; {{code|language=lua|__index}} can either be a function or a table.<ref>{{Cite web|title=Programming in Lua : 16.3|url=https://www.lua.org/pil/16.3.html|access-date=2021-09-16|website=Lua}}</ref> [[Operator overloading]] can also be done; Lua metatables can have elements such as {{code|language=lua|__add}}, {{code|language=lua|__sub}} and so on.<ref>{{Cite web|title= Metamethods Tutorial|url=http://lua-users.org/wiki/MetamethodsTutorial|access-date=2021-09-16|website=lua-users wiki |url-status=dead |archive-url=https://web.archive.org/web/20210916182214/http://lua-users.org/wiki/MetamethodsTutorial |archive-date=September 16, 2021}}</ref>
=== Stack ===
 
== Implementation ==
The Lua API makes extensive use of a global [[Stack (data structure)|stack]] which is used to pass parameters to and from Lua and C functions. 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, &minus;1 is the last element), while positive indices indicate offsets from the bottom.
Lua programs are not [[Interpreter (computing)|interpreted]] directly from the textual Lua file, but are [[Compiler|compiled]] into bytecode, which is then run on the Lua [[virtual machine]] (VM). The compiling process is typically invisible to the user and is performed during [[Run time (program lifecycle phase)|run-time]], especially when a [[just-in-time compilation]] (JIT) compiler is used, but it can be done offline to increase loading performance or reduce the memory footprint of the host environment by leaving out the compiler. Lua bytecode can also be produced and executed from within Lua, using the <code>dump</code> function from the string library and the <code>load/loadstring/loadfile</code> functions. Lua version 5.3.4 is implemented in approximately 24,000 lines of C code.<ref name="luaspe"/><ref name="luaabout"/>
 
Like most CPUs, and unlike most virtual machines (which are [[Stack machine|stack-based]]), the Lua VM is [[Register machine|register-based]], and therefore more closely resembles most 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 VMs to have a wide use.<ref name=lua5impl>{{cite journal |last1=Ierusalimschy |first1=R. |last2=Figueiredo |first2=L. H. |last3=Celes |first3=W. |year=2005 |title=The implementation of Lua 5.0 |journal=J. Of Universal Comp. Sci. |volume=11 |issue=7 |pages=1159–1176 |url=http://www.jucs.org/jucs_11_7/the_implementation_of_lua/jucs_11_7_1159_1176_defigueiredo.html |doi=10.3217/jucs-011-07-1159 |doi-access=free}}</ref> [[Parrot virtual machine|Parrot]] and [[Android (operating system)|Android]]'s [[Dalvik (software)|Dalvik]] are two other well-known register-based VMs. PCScheme's VM was also register-based.<ref>{{cite book |last1=Texas Instruments |year=1990 |title=PC Scheme: Users Guide and Language Reference Manual, Trade Edition |publisher=MIP Press |isbn=0-262-70040-9}}</ref>
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 <tt>lua_call</tt> 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.
 
This example is the bytecode listing of the factorial function defined [[#Factorial example|above]] (as shown by the <code>luac</code> 5.1 compiler):<ref name=luavm51instr>{{cite web |last1=Man |first1=Kein-Hong |year=2006 |title=A No-Frills Introduction to Lua 5.1 VM Instructions |url=https://talk.pokitto.com/uploads/default/original/2X/7/716c67a0b5b1636cbc4dc1fec232ca2536cb74d1.pdf}}</ref><!-- See earlier revisions for now-dead original and archive.org snapshots of this link, in case it moves again. It is CC-BY-NC-SA so it can be rehosted if needed. -->
=== Special tables ===
 
function <factorial.lua:1,7> (9 instructions, 36 bytes at 0x8063c60)
The C API also provides several special tables, located at various “pseudo-indices” in the Lua stack. At <tt>LUA_GLOBALSINDEX</tt> is the globals table, <tt>_G</tt> from within Lua, which is the main [[Namespace (computer science)|namespace]]. There is also a registry located at <tt>LUA_REGISTRYINDEX</tt> where C programs can store Lua values for later retrieval.
1 param, 6 slots, 0 upvalues, 6 locals, 2 constants, 0 functions
1 [2] LOADK 1 -1 ; 1
2 [3] LOADK 2 -2 ; 2
3 [3] MOVE 3 0
4 [3] LOADK 4 -1 ; 1
5 [3] FORPREP 2 1 ; to 7
6 [4] MUL 1 1 5
7 [3] FORLOOP 2 -2 ; to 6
8 [6] RETURN 1 2
9 [7] RETURN 0 1
 
=== ExtensionC modulesAPI ===
Lua is intended to be embedded into other applications, and provides a [[C (programming language)|C]] [[Application Programming Interface|API]] for this purpose. The API is divided into two parts: the Lua core and the Lua auxiliary library.<ref name="luarefman">{{cite web |url=https://www.lua.org/manual/5.2/ |title=Lua 5.2 Reference Manual |publisher=Lua.org |access-date=2012-10-23}}</ref> The Lua API's design eliminates the need for manual [[reference counting]] (management) in C code, unlike [[Python (programming language)|Python]]'s API. The API, like the language, is minimalist. Advanced functions are provided by the auxiliary library, which consists largely of [[preprocessor]] [[Macro (computer science)|macros]] which assist with complex table operations.
 
The Lua C API is [[Stack (data structure)|stack]] based. Lua provides functions to push and pop most simple C data types (integers, floats, etc.) to and from the stack, and functions to manipulate 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<!-- not a hyphen --> is the top (most recently pushed value), while positive indices indicate offsets from the bottom (oldest value). [[Marshalling (computer science)|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 <code>lua_call</code> is used to call the actual function. When writing a C function to be directly called from Lua, the arguments are read from the stack.
 
Here is an example of calling a Lua function from C:
 
<syntaxhighlight lang="c">
#include <stdio.h>
#include <lua.h> // Lua main library (lua_*)
#include <lauxlib.h> // Lua auxiliary library (luaL_*)
 
int main(void)
{
// create a Lua state
lua_State *L = luaL_newstate();
 
// load and execute a string
if (luaL_dostring(L, "function foo (x,y) return x+y end")) {
lua_close(L);
return -1;
}
 
// push value of global "foo" (the function defined above)
// to the stack, followed by integers 5 and 3
lua_getglobal(L, "foo");
lua_pushinteger(L, 5);
lua_pushinteger(L, 3);
lua_call(L, 2, 1); // call a function with two arguments and one return value
printf("Result: %d\n", lua_tointeger(L, -1)); // print integer value of item at stack top
lua_pop(L, 1); // return stack to original state
lua_close(L); // close Lua state
return 0;
}
</syntaxhighlight>
 
Running this example gives:
It is possible to write extension modules using the Lua API. Extension modules are [[Library (computing)#Dynamic linking|shared objects]] which can be used to extend the functionality of the interpreter by providing native facilities to Lua scripts. Lua scripts may load extension modules using <tt>require</tt> [http://www.lua.org/manual/5.1/manual.html#pdf-require]. A growing collection of modules known as ''rocks'' are available through a [[package management system]] called [http://www.luarocks.org LuaRocks], in the spirit of [[RubyGems]].
<syntaxhighlight lang="console">
$ cc -o example example.c -llua
$ ./example
Result: 8
</syntaxhighlight>
 
The C API also provides some special tables, located at various "pseudo-indices" in the Lua stack. At <code>LUA_GLOBALSINDEX</code> prior to Lua 5.2<ref name="Changes in the API, Lua 5.2 manual">{{cite book |first1=Roberto |last1=Ierusalimschy |first2=Luiz Henrique |last2=de Figueiredo |first3=Waldemar |last3=Celes |date=2011–2013 |url=https://www.lua.org/manual/5.2/manual.html#8.3 |title=Changes in the API |work=Lua 5.2 Reference Manual |publisher=Lua.org |access-date=2014-05-09}}</ref> is the globals table, <code>_G</code> from within Lua, which is the main [[namespace]]. There is also a registry located at <code>LUA_REGISTRYINDEX</code> where C programs can store Lua values for later retrieval.
=== Bindings to other languages ===
 
=== Modules ===
* LuaInterface [http://luaforge.net/projects/luainterface/] for [[Common Language Runtime|CLR]] based languages.
Besides standard library (core) modules it is possible to write extensions using the Lua API. Extension modules are [[Library (computing)#Dynamic linking|shared objects]] which can be used to extend the functions of the interpreter by providing native facilities to Lua scripts. Lua scripts may load extension modules using <code>require</code>,<ref name="luarefman"/> just like modules written in Lua itself, or with <code>package.loadlib</code>.<ref>{{Cite web |title=Lua 5.4 Reference Manual |url=https://www.lua.org/manual/5.4/manual.html#pdf-package.loadlib |first1=Roberto |last1=Ierusalimschy |first2=Luiz Henrique |last2=de Figueiredo |first3=Waldemar |last3=Celes |access-date=2022-06-01 |website=Lua}}</ref> When a C library is loaded via {{ml-lua|foo}} Lua will look for the function <code>luaopen_foo</code> and call it, which acts as any C function callable from Lua and generally returns a table filled with methods. A growing set of modules termed ''rocks'' are available through a [[package management system]] named [[LuaRocks]],<ref>{{cite web |url=https://luarocks.org/ |title=LuaRocks |publisher=luarocks.org |access-date=2009-05-24}}</ref> in the spirit of [[CPAN]], [[RubyGems]] and [[Python eggs]]. Prewritten Lua [[Language binding|bindings]] exist for most popular programming languages, including other scripting languages.<ref>{{cite web |url=http://lua-users.org/wiki/BindingCodeToLua |title=Binding Code To Lua |publisher=Lua-users wiki |access-date=2009-05-24 |url-status=dead |archive-url=https://web.archive.org/web/20090727080345/http://lua-users.org/wiki/BindingCodeToLua |archive-date= Jul 27, 2009}}</ref> For C++, there are a number of template-based approaches and some automatic binding generators.
* Tao.Lua [http://www.taoframework.com/project/lua] for [[Microsoft .NET|.Net]] and [[Mono (software)|Mono]]
* LuaJava [http://luaforge.net/projects/luajava] for Java.
* RubyLuaBridge [http://rubyluabridge.rubyforge.org] for [[Ruby (programming language)|Ruby]].
* Kahlua [http://code.google.com/p/kahlua/] for J2ME (CLDC 1.1). This is not a binding, but a reimplementation of the Lua virtual machine.
* Lunatic Python [http://labix.org/lunatic-python] binds Python and Lua
 
== Applications ==
{{main|List of applications using Lua}}
{{examplefarm}}
Lua, as a compiled binary, is small. Coupled with it being relatively fast and having the liberal [[MIT license]], it has gained a following among game developers for providing a viable scripting interface.{{Fact|date=August 2008}}
 
In [[video game development]], Lua is widely used as a [[scripting language]], mainly due to its perceived ease of embedding, fast execution, and short [[learning curve]].<ref>{{cite web|url=https://stackoverflow.com/questions/38338/why-is-lua-considered-a-game-language |title=Why is Lua considered a game language? |website=Stack Overflow |access-date=2017-04-22 |url-status=dead |archive-url=https://web.archive.org/web/20130820131611/http://stackoverflow.com/questions/38338/why-is-lua-considered-a-game-language |archive-date=20 August 2013}}</ref> Notable games which use Lua include ''[[Roblox]]'',<ref>{{Cite web|title=Why Lua''u''?|url=https://luau-lang.org/why.html|access-date=2022-03-23|website=Luau|language=en-US}}</ref> ''[[Garry's Mod]]'', '' [[World of Warcraft]]'', ''[[Payday 2]]'', ''[[Phantasy Star Online 2]]'', ''[[Dota 2]]'', ''[[Crysis (video game)|Crysis]]'',<ref>{{cite web |url=https://crymp.net/thread?id=347 |title=Introduction to Crysis server-side modding |access-date=23 March 2022}}</ref> and many others. Some games that do not natively support Lua programming or scripting have this function added by mods, as ComputerCraft does for ''[[Minecraft]]''. Similarly, Lua API libraries, like Discordia, are used for platforms that do not natively support Lua.<ref>{{Cite web|title=Discordia API|url=https://github.com/SinisterRectus/Discordia|access-date=2025-07-02|language=en-US}}</ref> Lua is used in an open-source 2-dimensional game engine called LOVE2D.<ref>{{Cite web|title=LOVE2D Game Engine|url=https://love2d.org/|access-date=2025-07-02|language=en-US|archive-date=5 March 2025|archive-url=https://web.archive.org/web/20250305202646/https://love2d.org/|url-status=dead}}</ref> Also, Lua is used in non-video game software, such as [[Adobe Lightroom]], [[Moho (software)|Moho]], [[iClone]], [[Aerospike (database)|Aerospike]], and some system software in [[FreeBSD]] and [[NetBSD]], and used as a template scripting language on [[MediaWiki]] using the Scribunto extension.<ref>{{Cite web|title=Lua Functions|url=https://wow.gamepedia.com/Lua_functions|access-date=2021-03-01|website=wow.gamepedia.com|language=en-US}}</ref>
<!--More can be found here at this site http://www.lua.org/uses.html. If it needs to be added. Add here http://www.lua.org/uses-form.html. Please only add truly noteworthy applications to this list.-->
===Games===
 
In 2003, a poll conducted by GameDev.net showed that Lua was the most popular scripting language for game programming.<ref>{{cite web|url=https://gamedev.net/gdpolls/viewpoll.asp?ID=163 |title=Poll Results |access-date=2017-04-22 |url-status=bot: unknown |archive-url=https://web.archive.org/web/20031207171619/http://gamedev.net/gdpolls/viewpoll.asp?ID=163 |archive-date=7 December 2003}}</ref> On 12 January 2012, Lua was announced as a winner of the Front Line Award 2011 from the magazine ''[[Game Developer (magazine)|Game Developer]]'' in the category Programming Tools.<ref>{{cite web|url=http://www.gdmag.com/blog/2012/01/front-line-award-winners.php |title=Front Line Award Winners Announced |access-date=2017-04-22 |url-status=dead |archive-url=https://web.archive.org/web/20130615013638/http://www.gdmag.com/blog/2012/01/front-line-award-winners.php |archive-date=15 June 2013}}</ref>
A list of notable games using Lua:
 
Many non-game applications also use Lua for extensibility, such as [[LuaTeX]], an implementation of the [[TeX]] type-setting language; [[Redis]], a [[key-value database]]; [[ScyllaDB]], a [[wide-column store]], [[Neovim]], a text editor; [[Nginx]], a [[web server]]; [[Wireshark]], a network packet analyzer; Disordia, a [[Discord]] API library; and [[Pure Data]], a visual audio programming language (through the pdlua extension).
*[[Aleph One (computer game)|Aleph One]] (an open-source enhancement of ''[[Marathon 2: Durandal]]'') supports Lua, and it’s been used in a number of [[Marathon total conversions|scenarios]] (including ''Excalibur'' and ''Eternal'').
*''[[Company of Heroes]]'', a WW2 RTS. Lua is used for the console, AI, single player scripting, win condition scripting and for storing unit attributes and configuration information.
*''[[Crysis]]'', a [[first-person shooter]] & spiritual successor to [[Far Cry]]. FarCry itself used Lua extensively.
*''[[Garry's Mod]]'' and ''[[Fortress Forever]]'', [[Mod (computer gaming)|mods]] for [[Half-Life 2]], use Lua scripting for tools and other sorts of things for full customization.
*''[[Grim Fandango]]'' and ''[[Escape from Monkey Island]]'', both based on the [[GrimE|GrimE engine]]. The historic “SCUMM Bar” is renovated and renamed to the "Lua Bar" as a reference.
*''[[Heroes of Might and Magic V]]'', a turn-based strategy computer game.
*''[[PlayStation Home]]'' is programmed using Lua.
*''[[Ragnarok Online]]'' uses Lua to allow players to fully customize the artificial intelligence of their homunculus to their liking, provided that they have an Alchemist to summon one.
*"[[Roblox]]" An Online game for kids Ages 7-14
*''[[S.T.A.L.K.E.R.: Shadow of Chernobyl]]'', has all game scripts written in Lua
*''[[Star Wars: Empire at War]]'' and ''[[Universe at War: Earth Assault]]''
*''[[The Guild 2]]'' Most of the game is programmed in Lua.
*''[[World of Warcraft]]'', a fantasy MMORPG. Lua is used to allow users to customize its user interface.
*''[[The Witcher]]'' Uses Lua for game scripts
*''[[Vendetta Online]]'' Uses Lua for game scripts and missions.
 
== Derived languages ==
===Other applications===
 
===Languages that compile to Lua===
*[[Celestia]] uses Lua to expand its capabilities without recompiling its source code
* MoonScript is a [[Dynamic programming language|dynamic]], [[Whitespace character|whitespace]]-sensitive [[scripting language]] inspired by [[CoffeeScript]], which is compiled into Lua. This means that instead of using <code>do</code> and <code>end</code> (or <code>{</code> and <code>}</code>) to delimit sections of code it uses [[Line break (computing)|line breaks]] and [[indentation style]].<ref>{{Cite web|title=Language Guide - MoonScript 0.5.0|url=https://moonscript.org/reference/|access-date=2020-09-25|website=moonscript.org}}</ref><ref>{{Cite web|last=leaf|title=leafo/moonscript|website=[[GitHub]] |date=2020-09-23|url=https://github.com/leafo/moonscript|access-date=2020-09-25}}</ref><ref name=":1">{{cite web |url=https://andregarzia.com/2020/06/languages-that-compile-to-lua.html |title=Languages that compile to Lua |website=AndreGarzia.com |last1=Garzia |first1=Andre Alves |access-date= 25 September 2020}}</ref> A notable use of MoonScript is the video game distribution website [[Itch.io]].
*[[Multimedia Fusion 2|Multimedia Fusion Developer 2]] has a Lua extension that allows games and applications created with it to run Lua scripts.
* [[Haxe]] supports compiling to some Lua targets, including Lua 5.1-5.3 and [[LuaJIT]] 2.0 and 2.1.
*[[Adobe Photoshop Lightroom]] uses Lua for its user interface
* Fennel, a Lisp dialect that targets Lua.<ref name=":1"/>
*The [[window manager]] [[Ion (window manager)|Ion]] uses Lua for customization and extensibility.
* Urn, a [[Lisp (programming language)|Lisp]] dialect built on Lua.<ref>{{Cite web|title=Urn: A Lisp implementation for Lua {{!}} Urn|url=https://urn-lang.com/|access-date=2021-01-12|website=urn-lang.com}}</ref>
*The packet sniffer [[Wireshark]] uses Lua for scripting and prototyping.
* Amulet, an [[ML (programming language)|ML]]-like [[functional programming]] language, which compiler emits Lua files.<ref>{{Cite web|title=Amulet ML|url=https://amulet.works/|access-date=2021-01-12|website=amulet.works|language=en-US}}</ref>
*[[Intellipool Network Monitor]] uses Lua for customization and extensibility.
* LunarML, Standard ML compiler that produces Lua/JavaScript<ref>{{Cite web|title=LunarML, Standard ML compiler that produces Lua/JavaScript|website=[[GitHub]] |url=https://github.com/minoki/LunarML}}</ref>
*[[Lua Player]] is a port designed to run on [[Sony Computer Entertainment]]’s [[PlayStation Portable]] to allow entry-level programming.
 
*[[CMUcam]] uses Lua for customization and extensibility as part of the CMUcam 3 scripter
=== Dialects ===
*[[lighttpd]] uses Lua for its [[Cache Meta Language]], a sophisticated way to describe caching behavior.
* [[LuaJIT]], a just-in-time compiler of Lua 5.1.<ref>{{cite web |title=LuaJIT |url=https://luajit.org/luajit.html |website=LuaJIT}}</ref><ref>{{cite web |title=Extensions |url=https://luajit.org/extensions.html |website=LuaJIT}}</ref>
*The popular network mapping program [[nmap]] uses Lua as the basis for its scripting language, called [[nse]].
* [[Roblox#Roblox Studio and game design|Luau]] developed by [[Roblox Corporation]], a derivative of and backwards-compatible with Lua 5.1 with [[gradual typing]], additional features, and a focus on performance.<ref>{{Cite web |title=Why Luau? |url=https://luau-lang.org/why |access-date=2024-08-03 |website=Luau |language=en |quote=All of these motivated us to start reshaping Lua 5.1 that we started from into a new, derivative language that we call Luau. Our focus is on making the language more performant and feature-rich, and make it easier to write robust code through a combination of linting and type checking using a gradual type system.}}</ref> Luau has improved sandboxing to allow for running untrusted code in embedded applications.<ref>{{Cite web |title=Sandboxing |url=https://luau.org/sandbox |access-date=2025-03-27 |website=Luau |language=en}}</ref>
*The version control system [[Monotone (software)|Monotone]] uses Lua for scripting hooks.
* Ravi, a JIT-enabled Lua 5.3 language with optional static typing. JIT is guided by type information.<ref>{{cite web |title=Ravi Programming Language |url=http://ravilang.github.io/ |website=GitHub}}</ref>
*The [[Freeswitch]] open source PBX project embeds Lua in it's API
* Shine, a fork of [[LuaJIT]] with many extensions, including a module system and a macro system.<ref>{{cite web |last1=Hundt |first1=Richard |title=richardhundt/shine |website=[[GitHub]] |url=https://github.com/richardhundt/shine |date=2021-04-22}}</ref>
*eyeon's [[Eyeon Fusion|Fusion]] compositor uses embedded Lua for internal and external [[scripting programming language|scripts]] and also [[plugin]] prototyping.
* Glua, a modified version embedded into the game [[Garry's Mod]] as its scripting language.<ref>{{cite web |title=Garry's Mod Wiki |url=https://wiki.facepunch.com/gmod/ |website=wiki.facepunch.com}}</ref>
*The [[Snort (software)|Snort]] Intrusion Detection/Prevention System version 3.0 uses Lua for its command line interpreter.
* Teal, a [[Type system#Static type checking|statically typed]] Lua dialect written in Lua.<ref>{{cite web |title=teal-language/tl |date=2024-12-23 |url=https://github.com/teal-language/tl |access-date=2024-12-23 |website=Teal language}}</ref>
*New versions of [[SciTE]] allow Lua to be used to provide additional features.
* [[PICO-8]], a "fantasy video game console", uses a subset of Lua known as PICO-8 Lua.
*Version 2.01 of the profile management software for [[Logitech]]’s G15 gaming keyboard uses Lua as its scripting language.
* Pluto, a superset of Lua 5.4 offering enhanced syntax, libraries, and better developer experience, all while staying compatible with regular Lua.<ref>{{cite web|title=What is Pluto?|url=https://pluto-lang.org/docs/Introduction|access-date=2025-06-27|website=Pluto}}</ref>
* [[Cisco]] uses Lua to implement Dynamic Access Policies within the [[Adaptive Security Appliance]].
 
* [[Project Dogwaffle]] uses Lua to let the end-user create new imaging filters. DogLua is based on a 'gluas' plugin spec developed initially for the [[GIMP]]. Lua scripting is also available in other digital painting programs, such as ArtWeaver and Twistedbrush. Some implementations have their respective extensions. When the core GIMP-original gluas syntax is used without proprietary extensions, these imaging filters can be shared and used across these applications for the benefit of other users. Some extensions from Project Dogwaffle have found their way also into others such as ArtWeaver.
In addition, the Lua users community provides some ''power patches'' on top of the reference C implementation.<ref>{{cite web |title=Lua Power Patches |url=http://lua-users.org/wiki/LuaPowerPatches |website=lua-users.org |access-date=18 May 2021 |archive-date=18 May 2021 |archive-url=https://web.archive.org/web/20210518114041/http://lua-users.org/wiki/LuaPowerPatches |url-status=dead}}</ref>
* [[3DMLW|3DMLW plugin]] uses Lua scripting for animating [[3D computer graphics|3D]] and handling different events.
 
* [[FreePOPs]] is an extensible mail proxy. It enables checking and downloading of [[e-mail]] from [[webmail]]s from any conventional [[Post Office Protocol|POP3]] [[Client (computing)|client]] program, avoiding the need to use a [[Web browser]].
== See also ==
* [[Damn Small Linux]] uses Lua to provide desktop-friendly interfaces for command-line utilities without sacrificing lots of disk space.
* [[Comparison of programming languages]]
* [[LuaTeX]], the designated successor of [[pdfTeX]], allows extensions to be written in Lua.
 
* [[Awesome (window manager)|awesome 3.0 and up]] use lua for customization and config
== Notes ==
* [[Dolphin Computer Access]] uses Lua scripting to make inaccessible applications [[accessible]] for [[visually impaired]] computer users with their [[screen reader]] - SuperNova.
{{Notelist}}
* [http://elua.berlios.de/ eLua] is a small Lua [[runtime]] for [[microcontroller]]s with special consideration for limited performance and low level [[hardware]] access.
 
== References ==
{{Reflist}}
{{Portal|Free software|Free Software Portal Logo.svg}}
 
== Further reading ==
{{refbegin}}
* {{cite book |last1=Ierusalimschy |first1=R. |title=Programming in Lua |edition=3rd |year=2013 |publisher=Lua.org |isbn=978-85-903798-5-0 |url=https://www.lua.org/pil/}} (The 1st ed. is available [https://www.lua.org/pil/contents.html online].)
* [http://www.lua.org/manual/5.1/ ''Lua 5.1 Reference Manual''] (online version of paper book) (ISBN 85-903798-3-3)
<!--UPDATEME to 5.2: * {{cite book |last1=Ierusalimschy |first1= R. |last2=Figueiredo |first2=L. H. |last3=Celes |first3=W. |year=2006 |title=Lua 5.1 Reference Manual |publisher=Lua.org |isbn= 85-903798-3-3 |url=https://www.lua.org/manual/5.1/}}-->
* [http://www.inf.puc-rio.br/~roberto/pil2/ ''Programming in Lua, Second Edition''] ([http://www.lua.org/pil/ online first edition]) (ISBN 85-903798-2-5)
* {{cite book |last1=Gutschmidt |first1=T. |year=2003 |title=Game Programming with Python, Lua, and Ruby |publisher=Course Technology PTR |isbn=978-1-59200-077-7}}
* ''Game Development with Lua'' (ISBN 1-58450-404-8)
* {{cite book |last1=Schuytema |first1=P. |last2=Manyen |first2=M. |year=2005 |title=Game Development with Lua |publisher=Charles River Media |isbn=978-1-58450-404-7}}
* [http://www.wrox.com/WileyCDA/WroxTitle/productCd-0470069171.html ''Beginning Lua Programming''] (ISBN 978-0-470-06917-2)
* {{cite book |last1=Jung |first1=K. |last2=Brown |first2=A. |year=2007 |title=Beginning Lua Programming |publisher=[[Wrox Press]] |isbn=978-0-470-06917-2 |url=https://www.wrox.com/WileyCDA/WroxTitle/productCd-0470069171.html |access-date=7 July 2018 |archive-url=https://web.archive.org/web/20180708015602/https://www.wrox.com/WileyCDA/WroxTitle/productCd-0470069171.html |archive-date=8 July 2018 |url-status=dead}}
{{refend}}
* {{cite book |editor-last=Figueiredo |editor-first=L. H. |editor2-last=Celes |editor2-first=W. |editor3-last=Ierusalimschy |editor3-first=R. |title=Lua Programming Gems |publisher=Lua.org |year=2008 |isbn=978-85-903798-4-3 |url=https://www.lua.org/gems/}}
* {{cite book |last1=Takhteyev |first1=Yuri |year=2012 |title=Coding Places: Software Practice in a South American City |publisher=[[The MIT Press]] |isbn=978-0-262-01807-4 |url=https://codingplaces.net/ |archive-url=https://web.archive.org/web/20121102000628/http://codingplaces.net/ |url-status=dead |archive-date=2012-11-02}} Chapters 6 and 7 are dedicated to Lua, while others look at software in Brazil more broadly.
* {{cite book |last=Varma |first=Jayant |title=Learn Lua for iOS Game Development |publisher=[[Apress]] |year=2012 |isbn=978-1-4302-4662-6 |url=https://www.amazon.com/exec/obidos/ASIN/1430246626/lua-docs-20}}
* {{cite web |url=https://www.gamedev.net/page/resources/_/technical/game-programming/an-introduction-to-lua-r1932 |title=An Introduction to Lua |website=GameDev.net |date=29 April 2003 |access-date=3 January 2013 |author=Matheson, Ash |archive-url=https://web.archive.org/web/20121218104442/http://www.gamedev.net/page/resources/_/technical/game-programming/an-introduction-to-lua-r1932 |archive-date=18 December 2012 |url-status=dead}}
* {{cite web|url=http://www.onlamp.com/pub/a/onlamp/2006/02/16/introducing-lua.html|title=Introducing Lua|last=Fieldhouse|first=Keith|date=16 February 2006|work=ONLamp.com|publisher=[[O'Reilly Media]]|access-date=28 February 2006|archive-url=https://web.archive.org/web/20060312124121/http://www.onlamp.com/pub/a/onlamp/2006/02/16/introducing-lua.html|archive-date=12 March 2006|url-status=dead}}
* {{cite web|url=https://www.ibm.com/developerworks/linux/library/l-lua.html|title=Embeddable scripting with Lua|last=Streicher|first=Martin|date=28 April 2006|work=developerWorks|publisher=[[IBM]]|access-date=7 July 2018|archive-date=2 July 2009|archive-url=https://web.archive.org/web/20090702111603/http://www.ibm.com/developerworks/linux/library/l-lua.html|url-status=dead}}
* {{cite journal |last=Quigley|first=Joseph|date=1 June 2007|title=A Look at Lua|journal=[[Linux Journal]]|url=https://www.linuxjournal.com/article/9605}}
* {{cite news|url=https://www.computerworld.com.au/article/260022/a-z_programming_languages_lua/|title=The A-Z of Programming Languages: Lua|last=Hamilton|first=Naomi|date=11 September 2008|work=[[Computerworld]]|publisher=[[International Data Group|IDG]]|access-date=7 July 2018|archive-url=https://web.archive.org/web/20180708020030/https://www.computerworld.com.au/article/260022/a-z_programming_languages_lua/|archive-date=8 July 2018|url-status=dead}} Interview with Roberto Ierusalimschy.
* {{cite journal|title=Passing a Language through the Eye of a Needle|last1=Ierusalimschy|first1=Roberto|last2=de Figueiredo|first2=Luiz Henrique|last3=Celes|first3=Waldemar|date=12 May 2011|journal=[[ACM Queue]]|volume=9|issue=5|pages=20–29|doi=10.1145/1978862.1983083|s2cid=19484689|doi-access=free}} How the embeddability of Lua impacted its design.
* {{cite journal|url=https://cacm.acm.org/magazines/2018/11/232214-a-look-at-the-design-of-lua|title=A Look at the Design of Lua|last1=Ierusalimschy|first1=Roberto|last2=de Figueiredo|first2=Luiz Henrique|last3=Celes|first3=Waldemar|journal=[[Communications of the ACM]]|volume=61|issue=11|pages=114–123|date=November 2018|doi=10.1145/3186277|s2cid=53114923|url-access=subscription}}{{Dead link|date=June 2020 |bot=InternetArchiveBot |fix-attempted=yes}}
* [https://www.lua.org/papers.html Lua papers and theses]
 
== External links ==
{{Wikibooks|Lua Programming}}
* [http://www.lua.org Lua official site]
{{Sister project links|display=Lua|b=Lua Programming|v=Lua|wikt=no|q=no|s=no|commons=no}}
* [http://www.lua.org/uses.html User projects] — list of applications using Lua, compiled by the authors
* [http://lua-users.org/ lua-users.org] — community website for and by users (and authors) of Lua
* [http://lua-users.org lua-users wiki] — supplementary information and resources
* [http://lua-users.org/lists/lua-l/ lua-l archive] — the official list
* [http://pgl.yoyo.org/luai Luai] — an alternative interface to the reference manual
* [http://www.onlamp.com/pub/a/onlamp/2006/02/16/introducing-lua.html Introducing Lua] — ONLamp.com
* [http://www.gamedev.net/reference/articles/article1932.asp An Introduction to Lua] — GameDev.net
* [http://www.computerworld.com.au/index.php/id;1028768484;fp;4194304;fpid;1 Computerworld Interview with Roberto Ierusalimschy on Lua]
[[Category:Lua programming language| ]]
[[Category:Embedded systems]]
[[Category:Virtual machines]]
[[Category:Free compilers and interpreters]]
[[Category:Free development toolkits and libraries]]
 
* {{Official website}}
[[cs:Lua]]
* [http://lua-users.org/ Lua Users] {{Webarchive|url=https://web.archive.org/web/20101216084624/http://lua-users.org/ |date=16 December 2010}}, Community
[[da:Lua (programmeringssprog)]]
* [https://luaforum.com Lua Forum] {{Webarchive|url=https://web.archive.org/web/20210928172635/https://www.luaforum.com/ |date=28 September 2021}}
[[de:Lua]]
* [https://luadist.org LuaDist]
[[es:Lua]]
* [https://luarocks.org/ Lua Rocks - Package manager]
[[eo:Lua]]
* [https://web.archive.org/web/20070202005230/http://luaforge.net/ Projects in Lua]
[[eu:Lua]]
 
[[fr:Lua]]
{{Lua programming language}}
[[gl:Lua (linguaxe de programación)]]
{{FOSS}}
[[ko:루아 (프로그래밍 언어)]]
{{Programming languages}}
[[it:Lua]]
{{Authority control}}
[[ms:Lua]]
{{Portal bar|Free and open-source software|Computer programming}}
[[nl:Lua (programmeertaal)]]
 
[[ja:Lua]]
[[Category:Lua (programming language)| ]]
[[pl:Lua]]
[[Category:Articles with example C code]]
[[pt:Lua (linguagem de programação)]]
[[Category:Brazilian inventions]]
[[ru:Lua]]
[[Category:Cross-platform free software]]
[[fi:Lua]]
[[Category:Cross-platform software]]
[[sv:Lua]]
[[Category:Dynamic programming languages]]
[[zh:Lua]]
[[Category:Dynamically typed programming languages]]
[[Category:Embedded systems]]
[[Category:Free and open source interpreters]]
[[Category:Free computer libraries]]
[[Category:Free software programmed in C]]
[[Category:Object-oriented programming languages]]
[[Category:Pontifical Catholic University of Rio de Janeiro]]
[[Category:Programming languages]]
[[Category:Programming languages created in 1993]]
[[Category:Prototype-based programming languages]]
[[Category:Register-based virtual machines]]
[[Category:Scripting languages]]
[[Category:Software using the MIT license]]