-- A comment in Lua starts with a double-hyphen and runs to the end of the line.--[[ Multi-line strings & comments are adorned with double square brackets. ]]--[=[ Comments like this can have other --[[comments]] nested. ]=]

Lua's treatment of functions as first-class values is shown in the following example, where the print function's behavior is modified:

dolocaloldprint=print-- Store current print function as oldprintfunctionprint(s)-- Redefine print function, the usual print function can still be usedifs=="foo"thenoldprint("bar")elseoldprint(s)endendend

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.

functionaddto(x)-- Return a new function that adds x to the argumentreturnfunction(y)--[[ When we refer to the variable x, which is outside of the current scope and whose lifetime would be shorter than that of this anonymous function, Lua creates a closure.]]returnx+yendendfourplus=addto(4)print(fourplus(3))-- Prints 7

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.

A table is a collection of key and data pairs, where the data is referenced by key; in other words, it's a hashedheterogeneousassociative array. A key (index) can be of any data type except nil. A numeric key of 1 is considered distinct from a string key of "1".

Tables are created using the {} constructor syntax:

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

Tables are always passed by reference:

a_table={x=10}-- Creates a new table, with one entry mapping "x" to the number 10.print(a_table["x"])-- Prints the value associated with the string key, in this case 10.b_table=a_tableb_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.

By using a numerical key, the table resembles an array data type. Lua arrays are 1-based: the first index is 1 rather than 0 as it is for many other programming languages (though an explicit index of 0 is allowed).

A simple array of strings:

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

The length of a table is defined to be any integer index such that is not nil and is nil; moreover, if is nil, can be zero. For a regular array, with non-nil values from 1 to a given , its length is exactly that , 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).[3]

Extensible semantics is a key feature of Lua, and the metatable concept allows Lua's tables to be customized in powerful ways. The following example demonstrates an "infinite" table. For any , fibs[n] will give the thFibonacci 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].returnvalues[n]end})

Although Lua does not have a built-in concept of classes, they can be implemented using two language features: first-class functions and tables. By placing functions and related data into a table, an object is formed. Inheritance (both single and multiple) can be implemented via the metatable mechanism, telling the object to look up nonexistent methods and fields in parent object(s).

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

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

Vector={}-- Create a table to hold the class methodsfunctionVector:new(x,y,z)-- The constructorlocalobject={x=x,y=y,z=z}setmetatable(object,{__index=Vector})-- InheritancereturnobjectendfunctionVector:magnitude()-- Another member function-- Reference the implicit object using selfreturnmath.sqrt(self.x^2+self.y^2+self.z^2)endvec=Vector:new(0,1,0)-- Create a vectorprint(vec:magnitude())-- Call a member function using ":" (output: 1)print(vec.x)-- Access a member variable using "." (output: 0)

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

Like most CPUs, and unlike most virtual machines (which are stack-based), the Lua VM is register-based, and therefore more closely resembles an actual hardware design. The register architecture both avoids excessive copying of values and reduces the total number of instructions per function. The virtual machine of Lua 5 is one of the first register-based pure VMs to have a wide use.[5]Perl's Parrot and Android's Dalvik are two other well-known register-based VMs.

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

Lua is intended to be embedded into other applications, and accordingly it provides a robust, easy-to-use CAPI. The API is divided into two parts: the Lua core and the Lua auxiliary library.[7]

The Lua API is fairly straightforward because its design eliminates the need for manual reference management in C code, unlike Python's API. The API, like the language, is minimalistic. Advanced functionality is provided by the auxiliary library, which consists largely of preprocessormacros which make complex table operations more palatable.

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, as well as functions for manipulating tables through the stack. The Lua stack is somewhat different from a traditional stack; the stack can be indexed directly, for example. Negative indices indicate offsets from the top of the stack (for example, −1 is the last element), while positive indices indicate offsets from the bottom.

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