Lua
Lua | |
---|---|
Lua logo |
|
Basic data | |
Paradigms : | Script language , imperative , functional , object-oriented |
Publishing year: | 1993 |
Designer: | Roberto Ierusalimschy |
Developer: | Roberto Ierusalimschy, Waldemar Celes, Luiz Henrique de Figueiredo |
Current version | 5.4.0 (June 29, 2020) |
Typing : | dynamically weak ( weak typing ) |
Important implementations : | Lua , LuaJIT, LLVM-Lua, LuaCLR |
Dialects: | Metalua, Idle, GSL Shell |
Influenced by: | C ++ , CLU , Modula , Scheme , SNOBOL |
Affected: | Falcon , GameMonkey , Io , JavaScript , Julia , MiniD , Moonscript , Red , Ruby , Squirrel |
Operating system : | platform independent |
License : | MIT license |
www.lua.org |
Lua ( Portuguese for moon ) is an imperative and extensible scripting language for integration into programs in order to be able to further develop and maintain them more easily. One of the special features of Lua is the small size of the compiled script interpreter .
Lua programs are mostly platform-independent and are translated into bytecode before they are executed . Although Lua can also be used to write standalone programs, it is primarily designed as an embedded scripting language for other programs. In this respect it is comparable to Tcl . Advantages of Lua are the small size of 120 kB, the expandability and the high speed compared to other scripting languages.
The Lua interpreter is a C - library are addressed, which is also an API for the runtime environment includes the interpreter for calls from the C program. Using the API, different parts of the program can be written in C (or C ++) and Lua, while variables and functions remain accessible in both directions (i.e. a function in Lua can call a function in C / C ++ and vice versa).
There is also a free JIT compiler called LuaJIT that supports revision 5.1 of the language.
Lua is in ANSI-C implements and supports imperative and functional programming. However, if you implement objects yourself using metatables, object-oriented programming is also possible.
history
Lua was developed in 1993 by Roberto Ierusalimschy, Luiz Henrique de Figueiredo and Waldemar Celes in the Computer Graphics Technology Group of the Pontifical Catholic University of Rio de Janeiro in Brazil . Lua is free software and was published up to version 4 under its own BSD license , from version 5 under the MIT license .
use
Lua can be used to write standalone programs as well as serve as an embedded language.
To get individual components of a computer game such as For example, to separate configuration files or the AI of computer-controlled characters or opponents from the game engine , Lua is often used in the development of computer games. This makes the usually expensively developed game engine more flexible and enables reusability associated with less effort, which is why Lua is used in the area of proprietary games.
Also, some newer, especially dynamic and tiling - window manager to use Lua for configuration and control, including awesome and Ion3 .
syntax
Data types
In addition to the data types nil , boolean , number (with the internal subtypes integer and float ), string , function, userdata and thread , Lua recognizes the only structured data type table (table).
A table is an associative data field , i.e. a collection of key-data pairs. The key (index) can have any data type (except nil). A distinction is also made between the number key 1 and the string key "1". In contrast to C-like languages, table indexing starts with 1.
Tables can be created in the following ways:
T = {} -- Erzeugt eine leere Tabelle und weist sie der Variablen mit dem Namen T zu.
T = {"ja", "nein", "?"} -- Eine Tabelle mit 3 Elementen, wobei T[1] == "ja", T[2] == "nein" und T[3] == "?".
T = {[1] = "ja", [2] = "nein", [3] = "?"} -- Wie Zeile vorher, nur mit expliziter Indizierung.
T = {[-900] = 3, [900] = 4} -- Tabelle mit 2 Elementen, aber unregelmäßigen Indizes.
T = {x=5, y=10} -- Typisches assoziatives Datenfeld mit T["x"], T["y"] (auch als T.x, T.y zugreifbar)
T = {x=5, y=10; "ja", "nein"} -- Gemischte Tabelle mit T.x, T.y, T[1], T[2]
T = {Nachricht = "wahl", {"ja", "nein", "?"}} -- Tabellen können weitere Tabellen enthalten.
Assignments
a = 5
b = "hi"
local a = a
-- Einfache Zuweisungen. Variablen sind nicht typisiert und können verschiedene Datentypen haben.
-- Lokale Variablen (definiert mit "local") sind auf den aktuellen Namensbereich beschränkt.
a, b, c = 1, 2, 3 -- Mehrfachzuweisungen sind erlaubt.
a, b = b, a -- Wertetausch: Anweisungen werden von rechts nach links ausgewertet.
a, b = 4, 5, "6" -- Überflüssige Werte (Bsp: "6") werden ausgewertet, aber verworfen.
a, b = "da" -- Fehlende Werte auf der rechten Seite werden mit "nil" ersetzt.
a = nil -- Zerstört a. Der Speicherbereich von a wird vom Garbage-Collector freigegeben.
a = z -- Falls z nicht definiert ist, wird "nil" zugewiesen und somit a freigegeben.
a = "3" + "2" -- Der Operator + erwartet Zahlen, die Zeichenketten werden also
-- in Zahlen konvertiert, also erfolgt hier die Zuweisung a = 5.
a = 3 .. 2 -- Der Verbindungsoperator erwartet Zeichenketten, die Zahlen werden
-- konvertiert - a = "32".
local a <const> = 5 -- lexikalische (lokale) Konstanten wurden in Lua 5.4 eingeführt
local f <close> = io.open(file) -- ebenfalls ab 5.4: to-close-Variablen mit ähnlicher Semantik
-- wie Pythons Context Manager (with ...)
Functions
Functions can be created with the keyword function
. Functions do not have a fixed number of parameters and return values.
function probe(zahl1, zahl2, text, tabelle)
zahl3 = zahl1 + zahl2
zahl4 = zahl1 - zahl2
print(text)
if tabelle ~= nil then
print(tabelle.eintrag)
end
return zahl3,zahl4
end
probe(10, 20, "Hallo ", {eintrag = "Welt"}) -- erlaubter Funktionsaufruf
x,y = probe(10,20) -- ebenfalls erlaubter Aufruf, text und tabelle sind nil.
When the function is called, not all variables have to be transferred. Missing parameters automatically have the zero value nil
. The same goes for return values. This makes it easier to implement function overloads, but the incidence of runtime errors increases.
Reserved keywords
and break do else elseif end false for function goto if in
local nil not or repeat return then true until while
The keyword nil
stands (next to false ) for false and generally for uninitialized variables or uninterpretable values.
Sample code
The classic hello world program looks like this:
print("Hallo Welt!")
Comments can be single-line or multi-line:
-- Ein Kommentar in Lua beginnt mit zwei Bindestrichen und geht bis zum Ende der Zeile.
--[[Kommentare können auch über mehrere
Zeilen ausgeweitet werden, sodass die Dokumentation
des Quellcodes leichter fällt.]]
Example of a recursion (calculation of the factorial ):
function factorial(n)
if n == 0 then
return 1
end
return n * factorial(n - 1)
end
With the short-circuit operators "and" and "or" the function can be written in a shorter way (this corresponds to the selection operator ?: From C and related languages):
function factorial(n)
return n == 0 and 1 or n * factorial(n - 1)
end
Functions are considered first-class objects in Lua . This means in particular that functions can be generated dynamically during runtime and (also existing) variables can be assigned. The following example shows how the variable print
(which points to a standard function of the Lua library) is overwritten with another function:
do
local oldprint = print -- aktuelle (globale) print-Funktion über oldprint zugreifbar machen
function print(s) -- Neue (globale) Definition von print, ...
oldprint("I say: " .. s) -- ... die die alte print-Funktion aufruft.
end
end
Commands in Lua can be terminated with a semicolon . If several commands are in one line, this makes the code easier to read.
The syntax is based on that of Pascal , which makes it easier for beginners to get started with Lua. In contrast to languages derived from Pascal, Lua uses "==" and not "=" as a comparison operator, "=" as an assignment operator (instead of ": =" in Pascal) and "~ =" for unequal (instead of "<>." ").
Modules
Lua can be expanded as required with user-defined modules. To manage these, the package manager LuaRocks, written in Lua, is available.
A list of common Lua modules:
module | description |
---|---|
LuaFileSystem | Access to folder structures and file properties. |
LuaDoc | Documentation tool for Lua source code. |
LuaSocket | Library for socket programming. |
LuaSQL | Lua interface for PostgreSQL , ODBC , MySQL , SQLite , Oracle , and OLE DB . |
stdlib | Library for common programming tasks; refers to lists, tables, functional programming, regular expressions , objects, pretty -printing and getopt. |
MD5 | simple cryptographic hash function |
Copas | Dispatcher based on co-routines that can be used by TCP / IP servers. |
LuaZip | Library that can read from ZIP files . |
LuaInterface | Connection between Lua and Microsoft's .NET Common Language Runtime (CLR). |
LuaBitOps | A C based extension for Lua for bitwise operations on numbers. |
LuaXML | Simple connection between XML and Lua. |
Lanes | Allows different Lua environments to run in parallel. |
Penlight | Library that simplifies the handling of tables, arrays , strings, file paths, folders, data and functional programming applications. |
Oil | Simple and efficient Object Request Broker ( CORBA ). |
literature
- Roberto Ierusalimschy: Programming in Lua , 4th edition, Open Source Press, 2016, ISBN 978-8-59037-986-7 .
- Roberto Ierusalimschy, LH Figueiredo, W. Celes: Lua 5.1 Reference Manual , August 2006, ISBN 85-903798-3-3 .
- Kurt Jung, Aaron Brown: Beginning Lua Programming , Wrox, 2007, ISBN 0-470-06917-1 .
- Claus Kühnel, Daniel Zwirner: Lua: Use of Lua in Embedded Systems , 2nd edition, Script Verlag Kühnel, 2012, ISBN 978-3-90785-715-1 .
- David Young: Learning Game AI Programming with Lua , Packt Publishing, 2014, ISBN 1-783-28133-2 .
Web links
- Lua.org - official website (English and Portuguese)
- Lua Unofficial FAQ
- LuaRocks - package manager and repository
- Lua Users Wiki
- Awesome Lua on GitHub
- Learn Lua in 15 minutes
- Fast, lightweight, embedded scripting with Lua by Jan Bornholdt, Wedel University of Applied Sciences