Lua (limbaj de programare)

De la Wikipedia, enciclopedia liberă
Salt la: Navigare, căutare
Paradigmă imperativ, scripting, (procedural, prototype-based programare orientata pe obiecte), funcțională
Apărut în 1993
Dezvoltat de Roberto Ierusalimschy
Waldemar Celes
Luiz Henrique de Figueiredo
Ultima versiune 5.2.3
Implementări principale Lua, LuaJIT, LLVM-Lua, Lua Alchemy
Dialecte Metalua, Idle, GSL Shell
Influențat de C++, CLU, Modula, Scheme, SNOBOL
Influențe Io, GameMonkey, Squirrel, Falcon, MiniD
OS multi platformă
Licență Licență MIT

Lua (pronunțat în engleză /luːə/, din portugheză lua /ˈlu.(w)ɐ/ înseamnă lună[1]) este un limbaj de programare multi-paradigmă creat ca limbaj de scripting cu semantică extensibilă. Întrucât e scris în ANSI C, Lua este un limbaj cross-platform.[1] Lua are un API C relativ simplu.[2]

Exemple de cod[modificare | modificare sursă]

Clasicul program „hello world” poate fi scris în modul următor:

print('Hello World!')

Comentarea utilizează următoarea sintaxă, similară ca în Ada, Eiffel, Haskell, SQL și VHDL:

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

The factorial function is implemented as a function in this example:

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

Loops[modificare | modificare sursă]

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

--condition = true
while condition do
until condition
for i = first,last,delta do     --delta may be negative, allowing the for loop to count down or up

The generic for loop:

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

would iterate over the table _G using the standard iterator function pairs, until it returns nil.

Functions[modificare | modificare sursă]

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

  local oldprint = print   -- Store current print function as oldprint
  function print(s)        -- Redefine print function, the usual print function can still be used
    if s == "foo" then

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 of the current
         scope and whose lifetime would be shorter than that of this anonymous
         function, Lua creates a closure.]]
           return x + y
fourplus = 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.

Tables[modificare | modificare sursă]

Tables are the most important data structure (and, by design, the only built-in composite data type) in Lua, and are the foundation of all user-created types. They are conceptually similar to associative arrays in PHP and dictionaries in Python.

A table is a collection of key and data pairs, where the data is referenced by key; in other words, it's a hashed heterogeneous associative 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_table
b_table["x"] = 20   -- The value in the table has been changed to 20.
print(b_table["x"]) -- Prints 20.
print(a_table["x"]) -- Also prints 20, because a_table and b_table both refer to the same table.

As record[modificare | modificare sursă]

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

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

As namespace[modificare | modificare sursă]

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

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

As array[modificare | modificare sursă]

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 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).[3]

An array of objects:

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

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

Metatables[modificare | modificare sursă]

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 n, fibs[n] will give the nth 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]

Object-oriented programming[modificare | modificare sursă]

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

Creating a basic vector object:

Vector = {}                   -- Create a table to hold the class methods
function Vector:new(x, y, z)  -- The constructor
  local object = { x = x, y = y, z = z }
  setmetatable(object, { __index = Vector })  -- Inheritance
  return object
function Vector:magnitude()   -- Another member function
  -- Reference the implicit object using self
  return math.sqrt(self.x^2 + self.y^2 + self.z^2)
vec = Vector:new(0, 1, 0)     -- Create a vector
print(vec:magnitude())        -- Call a member function using ":" (output: 1)
print(vec.x)                  -- Access a member variable using "." (output: 0)

Internals[modificare | modificare sursă]

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]

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

C API[modificare | modificare sursă]

Lua is intended to be embedded into other applications, and accordingly it provides a robust, easy-to-use C API. 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 preprocessor macros which make complex table operations more palatable.

Stack[modificare | modificare sursă]

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.

Example[modificare | modificare sursă]

Here is an example of calling a Lua function from C:

#include <stdio.h>
#include <stdlib.h>
#include <lua.h>
#include <lauxlib.h>
int main(void)
    lua_State *L = luaL_newstate();
    if (luaL_dostring(L, "function foo (x,y) return x+y end")) {
    lua_getglobal(L, "foo");
    lua_pushinteger(L, 5);
    lua_pushinteger(L, 3);
    lua_call(L, 2, 1);
    printf("Result: %d\n", lua_tointeger(L, -1));
    return 0;

Running this example gives:

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

Referințe și note[modificare | modificare sursă]

  1. ^ a b About Lua”. Accesat la 19 iunie 2013. 
  2. ^ Yuri Takhteyev (21 aprilie 2013). „From Brazil to Wikipedia”. Foreign Affairs. Accesat la 25 aprilie 2013. 
  3. ^ Lua 5.1 Reference Manual”. 2012. Accesat la 16 octombrie 2012. 
  4. ^ Lua 5.1 Source Code”. 2006. Accesat la 24 martie 2011. 
  5. ^ Ierusalimschy, R.; Figueiredo, L. H.; Celes, W. (2005). „The implementation of Lua 5.0”. J. Of Universal Comp. Sci. 11 (7): 1159–1176. 
  6. ^ Kein-Hong Man (2006). „A No-Frills Introduction to Lua 5.1 VM Instructions. 
  7. ^ Lua 5.2 Reference Manual”. Accesat la 23 octombrie 2012. 

Bibliografie[modificare | modificare sursă]

Legături externe[modificare | modificare sursă]

Wikimedia Commons conține materiale multimedia legate de Lua (limbaj de programare)