Lua: Difference between revisions

From Wikipedia, the free encyclopedia
Jump to navigation Jump to search
imported>Annh07
m Reverted 1 edit by 49.237.9.109 (talk) to last revision by The Hurdy Gurdy Man
imported>Kamenûk
Spacing, and pronunciation
 
(2 intermediate revisions by 2 users not shown)
Line 1: Line 1:
{{Short description|Lightweight programming language}}
{{Short description|Lightweight programming language}}
{{other}}
{{other}}
{{Use dmy dates|date=February 2021}}{{Infobox programming language
{{Use dmy dates|date=February 2021}}
 
{{Infobox programming language
| name = Lua
| name = Lua
| logo = Lua-Logo.svg
| logo = Lua-Logo.svg
| logo size = 140px
| logo size =  
| screenshot = Excerpt of Coordinates module in Lua.png
| screenshot = Excerpt of Coordinates module in Lua.png
| screenshot_size = 250px
| screenshot_size = 250px
Line 20: Line 22:
[https://www.moonsharp.org/ MoonSharp],
[https://www.moonsharp.org/ MoonSharp],
| programming language = [[ANSI C]]
| programming language = [[ANSI C]]
| dialects = [https://www.nongnu.org/gsl-shell/ GSL Shell], [https://luau.org Lua''u'']
| dialects = [https://www.nongnu.org/gsl-shell/ GSL Shell], [https://luau.org Luau]
| influenced by = [[C++]], [[CLU (programming language)|CLU]], [[Modula]], [[Scheme (programming language)|Scheme]], [[SNOBOL]]
| influenced by = [[C++]], [[CLU (programming language)|CLU]], [[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=http://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]],
| influenced = [[GameMonkey Script|GameMonkey]], [[Io (programming language)|Io]], [[Julia (programming language)|Julia]], [[Red (programming language)|Red]], [[Ruby (programming language)|Ruby]], [[Squirrel (programming language)|Squirrel]], [[Luau (programming language)|Luau]]
| operating system = [[Cross-platform software|Cross-platform]]
| operating system = [[Cross-platform software|Cross-platform]]
| license = [[MIT License|MIT]]
| license = [[MIT License|MIT]]
| website = {{url|https://lua.org/}}
| website = {{url|https://lua.org}}
| file ext = <code>.lua</code>
| file ext = <code>.lua</code>
| wikibooks =  
| 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>
'''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=26 May 2026}}</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>


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.
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 ==
== 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]].
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.-->
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.-->
Line 44: Line 46:
In ''The Evolution of Lua'', the language's authors wrote:<ref name=hopl2007/>
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.}}
{{Blockquote|In 1993, the only real contender was [[Tcl (programming language)|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 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>
Line 53: Line 55:


== Features ==
== Features ==
Lua is commonly described as a "[[multi-paradigm programming language|multi-paradigm]]" language, providing a small set of general features that can be extended to fit different problem types. Lua does not contain explicit support for [[Inheritance (object-oriented programming)|inheritance]], but allows it to be implemented with [[#Metatables|metatables]]. Similarly, Lua allows programmers to implement [[namespace]]s, [[Class (computer programming)|classes]] and other related features using its single table implementation; [[first-class function]]s allow the employment of many techniques from [[functional programming]] and full [[lexical scoping]] allows fine-grained [[information hiding]] to enforce the [[principle of least privilege]].
Lua is commonly described as a "[[multi-paradigm programming language|multi-paradigm]]" language, providing a small set of general features that can be extended to fit different problem types. Lua does not contain explicit support for [[Inheritance (object-oriented programming)|inheritance]], but allows it to be implemented with [[#Metatables|metatables]]. Similarly, Lua allows programmers to implement [[namespace]]s, [[Class (programming)|classes]] and other related features using its single table implementation; [[first-class function]]s allow the employment of many techniques from [[functional programming]] and full [[lexical 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 [[Lightweight programming language|light]]; the full reference [[interpreter (computing)|interpreter]] is only about 247&nbsp;[[Kilobyte|kB]] 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. -->
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 [[Lightweight programming language|light]]; the full reference [[interpreter (computing)|interpreter]] is only about 293&nbsp;[[Kilobyte|kB]] 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. -->


As a [[dynamically typed]] language intended for use as an extension language or [[scripting language]], Lua is compact enough to fit on a variety of host platforms. It supports only a small number of atomic data structures such as [[Boolean data type|Boolean]] values, numbers (double-precision [[floating point]] and [[64-bit computing|64-bit]] [[integer]]s by default) and [[string (computer science)|strings]]. Typical data structures such as [[Array data structure|arrays]], [[set (computer science)|sets]], [[List (computing)|lists]] and [[record (computer science)|records]] can be represented using Lua's single native data structure, the table, which is essentially a heterogeneous [[associative array]].
As a [[dynamically typed]] language intended for use as an extension language or [[scripting language]], Lua is compact enough to fit on a variety of host platforms. It supports only a small number of atomic data structures such as [[Boolean data type|Boolean]] values, numbers (double-precision [[floating point]] and [[64-bit computing|64-bit]] [[integer]]s by default) and [[string (computer science)|strings]]. Typical data structures such as [[Array data structure|arrays]], [[set (computer science)|sets]], [[List (computing)|lists]] and [[record (computer science)|records]] can be represented using Lua's single native data structure, the table, which is essentially a heterogeneous [[associative array]].
Line 75: Line 77:
</syntaxhighlight>
</syntaxhighlight>


The declaration of a variable with a value of 10.
The declaration of a variable with a value of 1000 (one thousand)
<syntaxhighlight lang="lua">
<syntaxhighlight lang="lua">
local students = 10
local students = 1000
</syntaxhighlight>
</syntaxhighlight>


Line 312: Line 314:
</syntaxhighlight>
</syntaxhighlight>


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. -->
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 ===
=== Metatables ===
Extensible semantics is a key feature of Lua, and the [[#Metatables|metatable]] concept 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]].
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">
<syntaxhighlight lang="lua">
fibs = { 1, 1 }                                -- Initial values for fibs[1] and fibs[2].
fibs = { 1, 1 }                                -- Initial values for fibs[1] and fibs[2].
Line 378: Line 380:


==== Inheritance ====
==== Inheritance ====
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.
It is possible to use metatables to mimic the behavior of class inheritance in Lua.<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">
<syntaxhighlight lang="lua">
Line 397: Line 399:
end
end


-- Example of class inheritance
-- Example of pseudo class inheritance
local VectorMult = {}
local VectorMult = {}
VectorMult.__index = VectorMult
VectorMult.__index = VectorMult
Line 416: Line 418:
</syntaxhighlight>
</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>
It is also possible to implement [[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>


== Implementation ==
== Implementation ==
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"/>
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.5.0 is implemented in approximately 32,000 lines of C code.<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>
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>


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. -->
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. -->


  function <factorial.lua:1,7> (9 instructions, 36 bytes at 0x8063c60)
  function <factorial.lua:1,7> (9 instructions, 36 bytes at 0x8063c60)
Line 488: Line 490:
{{main|List of applications using Lua}}
{{main|List of applications using Lua}}


In [[video game development]], Lua is widely used as a [[scripting language]], mainly due to its perceived easiness to embed, 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]]''. 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>
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.org/why/|access-date=2026-04-06|website=Luau|language=en-US}}</ref> ''[[Garry's Mod]]'', '' [[World of Warcraft]]'', ''[[Payday 2]]'', ''[[Project Zomboid]]'', ''[[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. 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>


In 2003, a poll conducted by GameDev.net showed 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>
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>


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 and [[Pure Data]], a visual audio programming language (through the pdlua extension).
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; Discordia, a [[Discord]] API library; and [[Pure Data]], a visual audio programming language (through the pdlua extension).


== Derived languages ==
== Derived languages ==
Line 498: Line 500:
===Languages that compile to Lua===
===Languages that compile to Lua===
* 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]].
* 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]].
* [[Haxe]] supports compiling to some Lua targets, including Lua 5.1-5.3 and [[LuaJIT]] 2.0 and 2.1.
* [[Haxe]] supports compiling to some Lua targets, including Lua 5.1–5.3 and [[LuaJIT]] 2.0 and 2.1.
* Fennel, a Lisp dialect that targets Lua.<ref name=":1"/>
* Fennel, a Lisp dialect that targets Lua.<ref name=":1"/>
* 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>
* 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>
Line 506: Line 508:
=== Dialects ===
=== Dialects ===
* [[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>
* [[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>
* [[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>
* [[Luau_(programming_language)|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>
* 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>
* 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>
* 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>
* 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>
Line 518: Line 520:
== See also ==
== See also ==
* [[Comparison of programming languages]]
* [[Comparison of programming languages]]
* [[Löve (game framework)]]


== Notes ==
== Notes ==
Line 540: Line 543:
* {{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 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|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}}
* {{cite journal |last1=Ierusalimschy |first1=Roberto |last2=de Figueiredo |first2=Luiz Henrique |last3=Celes |first3=Waldemar |title=A look at the design of Lua |journal=[[Communications of the ACM]] |date=26 October 2018 |volume=61 |issue=11 |pages=114–123 |doi=10.1145/3186277 |s2cid=53114923 | doi-access=free}}
* [https://www.lua.org/papers.html Lua papers and theses]
* [https://www.lua.org/papers.html Lua papers and theses]



Latest revision as of 18:36, 20 June 2026

Template:Short description Script error: No such module "other uses". Script error: No such module "Unsubst".

Script error: No such module "Infobox".Script error: No such module "Check for unknown parameters".

Lua Template:Noexcerpt is a lightweight, high-level, multi-paradigm programming language designed mainly for embedded use in applications.[1] Lua is cross-platform software, since the interpreter of compiled bytecode is written in ANSI C,[2] and Lua has a relatively simple C application programming interface (API) to embed it into applications.[3]

Lua originated in 1993 as a language for extending 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 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 speed, 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 barriers (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.[4]

Lua's predecessors were the data-description and configuration languages Simple Object Language (SOL) and Data-Entry Language (DEL).[5] 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:[4]

<templatestyles src="Template:Blockquote/styles.css" />

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 or Scheme because of their unfriendly syntax. 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 ... 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.

Script error: No such module "Check for unknown parameters".

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 for control structures was mostly borrowed from Modula (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++ ("neat idea of allowing a local variable to be declared only where we need it"[4]), SNOBOL and AWK (associative arrays). 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) were a major influence on their decision to develop the table as the primary data structure of Lua.[6]

Lua semantics have been increasingly influenced by Scheme over time,[4] especially with the introduction of anonymous functions and full lexical scoping. Several features were added in new Lua versions.

Versions of Lua prior to version 5.0 were released under a license similar to the 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.

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. Lua does not contain explicit support for inheritance, but allows it to be implemented with metatables. Similarly, Lua allows programmers to implement namespaces, classes and other related features using its single table implementation; first-class functions allow the employment of many techniques from functional programming and full lexical scoping allows fine-grained information hiding to enforce the principle of least privilege.

In general, Lua strives to provide simple, 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; the full reference interpreter is only about 293 kB compiled[2] and easily adaptable to a broad range of applications.

As a dynamically typed language intended for use as an extension language or scripting language, Lua 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, numbers (double-precision floating point and 64-bit integers by default) and strings. Typical data structures such as arrays, sets, lists and records can be represented using Lua's single native data structure, the table, which is essentially a heterogeneous associative array.

Lua implements a small set of advanced features such as first-class functions, garbage collection, closures, proper tail calls, coercion (automatic conversion between string and number values at run time), coroutines (cooperative multitasking) and dynamic module loading.

Syntax

The classic "Hello, World!" program can be written as follows, with or without parentheses:[7]Template:Efn

print("Hello, World!")
print "Hello, World!"

The declaration of a variable, without a value.

local variable

The declaration of a variable with a value of 1000 (one thousand)

local students = 1000

A comment in Lua starts with a double-hyphen and runs to the end of the line, similar to Ada, Eiffel, Haskell, SQL and VHDL. Multi-line strings and comments are marked with double square brackets.

-- Single line comment
--[[
Multi-line comment
--]]

Script error: No such module "anchor".The factorial function is implemented in this example:

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

Control flow

Lua has one type of conditional test: if then end with optional else and elseif then execution control constructs.

The generic if then end statement requires all three keywords:

if condition then
	--statement body
end

An example of an if statement

if x ~= 10 then
	print(x)
end

The else keyword may be added with an accompanying statement block to control execution when the if condition evaluates to false:

if condition then
	--statement body
else
	--statement body
end

An example of an if else statement

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

Execution may also be controlled according to multiple conditions using the elseif then keywords:

if condition then
	--statement body
elseif condition then
	--statement body
else -- optional
	--optional default statement body
end

An example of an if elseif else statement

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

Lua has four types of conditional loops: the while loop, the repeat loop (similar to a do while loop), the numeric for loop and the generic for loop.

--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

This generic for loop would iterate over the table _G using the standard iterator function pairs, until it returns nil:

for key, value in pairs(_G) do
  print(key, value)
end

Loops can also be nested (put inside of another loop).

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

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

Functions

Lua's treatment of functions as first-class 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. The usual print function can still be used
      through oldprint. The new one has only one argument.]]
    oldprint(s == "foo" and "bar" or s)
  end
end

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

Lua also supports closures, 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 the current
      scope and whose lifetime would be shorter than that of this anonymous
      function, Lua creates a closure.]]
    return x + y
  end
end
fourplus = addto(4)
print(fourplus(3)) -- Prints 7

--This can also be achieved by calling the function in the following way:
print(addto(4)(3))
--[[ This is because we are calling the returned function from 'addto(4)' with the argument '3' directly.
  This also helps to reduce data cost and up performance if being called iteratively.]]

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

Tables

Tables are the most important data structures (and, by design, the only built-in composite data type) 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 hashed heterogeneous associative array.

Tables are created using the {} constructor syntax.

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

Tables are always passed by reference (see Call by sharing).

A key (index) can be any value except nil and NaN, including functions.

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.

A table is often used as structure (or record) by using strings as keys. Because such use is very common, Lua features a special syntax for accessing such fields.[8]

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.

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}  --  return {["x"] = x, ["y"] = y}
end

Point.set_x = function(point, x)
  point.x = x  --  point["x"] = x;
end

Tables are automatically assigned a numerical key, enabling them to be used as an array data type. The first automatic 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 1 is distinct from a string key "1".

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.

The length of a table t is defined to be any integer index n such that t[n] is not nil and t[n+1] is nil; moreover, if t[1] is nil, n can be zero. For a regular array, with non-nil values from 1 to a given n, its length is exactly that n, the index of its last value. If the array has "holes" (that is, nil values between other non-nil values), then #t can be any of the indices that directly precedes a nil value (that is, it may consider any such nil value as the end of the array).[9]

ExampleTable =
{
  {1, 2, 3, 4},
  {5, 6, 7, 8}
}
print(ExampleTable[1][3]) -- Prints "3"
print(ExampleTable[2][4]) -- Prints "8"

A table can be 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
                        -- array = { { x = 10, y = 20 }, { x = 30, y = 40 }, { x = 50, y = 60 } };
print(array[2].y)                                         -- Prints 40

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.[10]

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 n, fibs[n] will give the n-th Fibonacci number using dynamic programming and memoization.

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
})

Object-oriented programming

Although Lua does not have a built-in concept of classes, object-oriented programming can be emulated using functions and tables. An object is formed by putting methods and fields in a table. Inheritance (both single and multiple) can be implemented with metatables, delegating nonexistent methods and fields to a parent object.

There is no such concept as "class" with these techniques; rather, prototypes are used, similar to Self or JavaScript. New objects are created either with a factory method (that constructs new objects from scratch) or by cloning an existing object.

Creating a basic vector object:

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

function Vector.new(x, y, z)    -- The constructor
  return setmetatable({x = x, y = y, z = z}, VectorMeta)
end

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

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

Here, setmetatable tells Lua to look for an element in the Vector table if it is not present in the vec table. vec.magnitude, which is equivalent to vec["magnitude"], first looks in the vec table for the magnitude element. The vec table does not have a magnitude element, but its metatable delegates to the Vector table for the magnitude element when it's not found in the vec table.

Lua provides some syntactic sugar to facilitate object orientation. To declare member functions 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).

That in mind, here is a corresponding class with : syntactic sugar:

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^2 + self.y^2 + self.z^2)
end

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

Inheritance

It is possible to use metatables to mimic the behavior of class inheritance in Lua.[11] In this example, we allow vectors to have their values multiplied by a constant in a derived class.

local Vector = {}
Vector.__index = Vector

function Vector:new(x, y, z)    -- The constructor
  -- Here, self refers to whatever class's "new"
  -- method we call.  In a derived class, self will
  -- be the derived class; in the Vector class, self
  -- will be 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^2 + self.y^2 + self.z^2)
end

-- Example of pseudo class inheritance
local VectorMult = {}
VectorMult.__index = VectorMult
setmetatable(VectorMult, Vector) -- Make VectorMult a child of Vector

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

local vec = VectorMult:new(0, 1, 0) -- Create a vector
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)

It is also possible to implement multiple inheritance; __index can either be a function or a table.[12] Operator overloading can also be done; Lua metatables can have elements such as __add, __sub and so on.[13]

Implementation

Lua programs are not interpreted directly from the textual Lua file, but are 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, 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 dump function from the string library and the load/loadstring/loadfile functions. Lua version 5.5.0 is implemented in approximately 32,000 lines of C code.[2]

Like most CPUs, and unlike most virtual machines (which are stack-based), the Lua VM is 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.[14] Parrot and Android's Dalvik are two other well-known register-based VMs. PCScheme's VM was also register-based.[15]

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

function <factorial.lua:1,7> (9 instructions, 36 bytes at 0x8063c60)
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

C API

Lua is intended to be embedded into other applications, and provides a C API for this purpose. The API is divided into two parts: the Lua core and the Lua auxiliary library.[17] The Lua API's design eliminates the need for manual reference counting (management) in C code, unlike Python's API. The API, like the language, is minimalist. Advanced functions are provided by the auxiliary library, which consists largely of preprocessor macros which assist with complex table operations.

The Lua C API is 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 is the top (most recently pushed value), while positive indices indicate offsets from the bottom (oldest value). 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 read from the stack.

Here is an example of calling a Lua function from 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;
}

Running this example gives:

$ cc -o example example.c -llua
$ ./example
Result: 8

The C API also provides some special tables, located at various "pseudo-indices" in the Lua stack. At LUA_GLOBALSINDEX prior to Lua 5.2[18] is the globals table, _G from within Lua, which is the main namespace. There is also a registry located at LUA_REGISTRYINDEX where C programs can store Lua values for later retrieval.

Modules

Besides standard library (core) modules it is possible to write extensions using the Lua API. Extension modules are 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 require,[17] just like modules written in Lua itself, or with package.loadlib.[19] When a C library is loaded via Template:Ml-lua Lua will look for the function luaopen_foo 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,[20] in the spirit of CPAN, RubyGems and Python eggs. Prewritten Lua bindings exist for most popular programming languages, including other scripting languages.[21] For C++, there are a number of template-based approaches and some automatic binding generators.

Applications

Script error: No such module "Labelled list hatnote".

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.[22] Notable games which use Lua include Roblox,[23] Garry's Mod, World of Warcraft, Payday 2, Project Zomboid, Phantasy Star Online 2, Dota 2, Crysis,[24] and many others. Also, Lua is used in non-video game software, such as Adobe Lightroom, Moho, iClone, Aerospike, and some system software in FreeBSD and NetBSD, and used as a template scripting language on MediaWiki using the Scribunto extension.[25]

In 2003, a poll conducted by GameDev.net showed that Lua was the most popular scripting language for game programming.[26] On 12 January 2012, Lua was announced as a winner of the Front Line Award 2011 from the magazine Game Developer in the category Programming Tools.[27]

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; Discordia, a Discord API library; and Pure Data, a visual audio programming language (through the pdlua extension).

Derived languages

Languages that compile to Lua

Dialects

  • LuaJIT, a just-in-time compiler of Lua 5.1.[34][35]
  • 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.[36] Luau has improved sandboxing to allow for running untrusted code in embedded applications.[37]
  • Ravi, a JIT-enabled Lua 5.3 language with optional static typing. JIT is guided by type information.[38]
  • Shine, a fork of LuaJIT with many extensions, including a module system and a macro system.[39]
  • Glua, a modified version embedded into the game Garry's Mod as its scripting language.[40]
  • Teal, a statically typed Lua dialect written in Lua.[41]
  • PICO-8, a "fantasy video game console", uses a subset of Lua known as PICO-8 Lua.
  • Pluto, a superset of Lua 5.4 offering enhanced syntax, libraries, and better developer experience, all while staying compatible with regular Lua.[42]

In addition, the Lua users community provides some power patches on top of the reference C implementation.[43]

See also

Notes

Template:Notelist

References

<templatestyles src="Reflist/styles.css" />

  1. ↑ Script error: No such module "Citation/CS1".
  2. ↑ a b c Script error: No such module "citation/CS1".
  3. ↑ Script error: No such module "Citation/CS1".
  4. ↑ a b c d Script error: No such module "citation/CS1".
  5. ↑ Script error: No such module "citation/CS1".
  6. ↑ Script error: No such module "citation/CS1".
  7. ↑ Script error: No such module "citation/CS1".
  8. ↑ Script error: No such module "citation/CS1".
  9. ↑ Script error: No such module "citation/CS1".
  10. ↑ Script error: No such module "citation/CS1".
  11. ↑ Script error: No such module "citation/CS1".
  12. ↑ Script error: No such module "citation/CS1".
  13. ↑ Script error: No such module "citation/CS1".
  14. ↑ Script error: No such module "Citation/CS1".
  15. ↑ Script error: No such module "citation/CS1".
  16. ↑ Script error: No such module "citation/CS1".
  17. ↑ a b Script error: No such module "citation/CS1".
  18. ↑ Script error: No such module "citation/CS1".
  19. ↑ Script error: No such module "citation/CS1".
  20. ↑ Script error: No such module "citation/CS1".
  21. ↑ Script error: No such module "citation/CS1".
  22. ↑ Script error: No such module "citation/CS1".
  23. ↑ Script error: No such module "citation/CS1".
  24. ↑ Script error: No such module "citation/CS1".
  25. ↑ Script error: No such module "citation/CS1".
  26. ↑ Script error: No such module "citation/CS1".
  27. ↑ Script error: No such module "citation/CS1".
  28. ↑ Script error: No such module "citation/CS1".
  29. ↑ Script error: No such module "citation/CS1".
  30. ↑ a b Script error: No such module "citation/CS1".
  31. ↑ Script error: No such module "citation/CS1".
  32. ↑ Script error: No such module "citation/CS1".
  33. ↑ Script error: No such module "citation/CS1".
  34. ↑ Script error: No such module "citation/CS1".
  35. ↑ Script error: No such module "citation/CS1".
  36. ↑ Script error: No such module "citation/CS1".
  37. ↑ Script error: No such module "citation/CS1".
  38. ↑ Script error: No such module "citation/CS1".
  39. ↑ Script error: No such module "citation/CS1".
  40. ↑ Script error: No such module "citation/CS1".
  41. ↑ Script error: No such module "citation/CS1".
  42. ↑ Script error: No such module "citation/CS1".
  43. ↑ Script error: No such module "citation/CS1".

Script error: No such module "Check for unknown parameters".

Further reading

  • Script error: No such module "citation/CS1". (The 1st ed. is available online.)
  • Script error: No such module "citation/CS1".
  • Script error: No such module "citation/CS1".
  • Script error: No such module "citation/CS1".
  • Script error: No such module "citation/CS1".
  • Script error: No such module "citation/CS1". Chapters 6 and 7 are dedicated to Lua, while others look at software in Brazil more broadly.
  • Script error: No such module "citation/CS1".
  • Script error: No such module "citation/CS1".
  • Script error: No such module "citation/CS1".
  • Script error: No such module "citation/CS1".
  • Script error: No such module "Citation/CS1".
  • Script error: No such module "citation/CS1". Interview with Roberto Ierusalimschy.
  • Script error: No such module "Citation/CS1". How the embeddability of Lua impacted its design.
  • Script error: No such module "Citation/CS1".
  • Lua papers and theses

External links

Script error: No such module "Side box". Script error: No such module "Sister project links".Script error: No such module "Check for unknown parameters".

Script error: No such module "Navbox". Script error: No such module "Navbox". Script error: No such module "Navbox". Script error: No such module "Authority control". Template:Portal bar