Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Lua
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
== 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]]. 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 [[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]]. 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]]. === Syntax === 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. <syntaxhighlight lang="lua"> local variable </syntaxhighlight> The declaration of a variable with a value of 10. <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. <syntaxhighlight lang="lua"> -- Single line comment --[[ Multi-line comment --]] </syntaxhighlight> {{anchor|Factorial example}}The [[factorial]] function is implemented in this example:<!-- referred to elsewhere in this article --> <syntaxhighlight lang="lua"> function factorial(n) local x = 1 for i = 2, n do x = x * i end return x end </syntaxhighlight> === Control flow === 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. 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> === Functions === 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: <syntaxhighlight lang="lua"> 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 </syntaxhighlight> Any future calls to <code>print</code> will now be routed through the new function, and because of Lua's [[Scope (programming)#Lexical scoping|lexical scoping]], the old print function will only be accessible by the new, modified print. Lua also supports [[Closure (computer programming)|closures]], as demonstrated below: <syntaxhighlight lang="lua"> 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.]] </syntaxhighlight> 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. === 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 [[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. <syntaxhighlight lang="lua"> 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. </syntaxhighlight> 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> <syntaxhighlight 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> By using a table to store related functions, it can act as a namespace. <syntaxhighlight lang="lua"> 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 </syntaxhighlight> 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 <code>1</code> is distinct from a string key <code>"1"</code>. <syntaxhighlight lang="lua"> 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. </syntaxhighlight> 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> <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> 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 [[#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]]. <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]], [[object-oriented programming]] can be emulated using functions and tables. An object is formed by putting methods and fields in a table. [[Inheritance (object-oriented programming)|Inheritance]] (both single and multiple) can be implemented with [[#Metatables|metatables]], delegating nonexistent methods and fields to a parent object. There is no such concept as "class" with these techniques; rather, [[prototype-based programming|prototypes]] are used, similar to [[Self (programming language)|Self]] or [[JavaScript]]. 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: <syntaxhighlight lang="lua"> 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) </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^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) </syntaxhighlight> ==== 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. <syntaxhighlight lang="lua"> 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 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) </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>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)