Kurzreferenz

Lua Spickzettel

Umfassender Referenzleitfaden für Lua: Syntaxgrundlagen, Tabellen und Arrays, Schleifen, Metatables, objektorientierte Programmierung und Standardbibliothek.

· Veröffentlicht

Lua ist eine leistungsfähige, effiziente, leichtgewichtige und einbettbare Skriptsprache zur Erweiterung von Anwendungen.

Grundlegende Syntax

Kommentare

-- Einzeiliger Kommentar

--[[
  Mehrzeiliger Kommentar
--]]

Kurzschreibweise für Funktionsaufrufe

Klammern können weggelassen werden, wenn eine Funktion genau ein Zeichenkettenliteral oder einen Tabellenkonstruktor erhält:

print("Hello World")  <==>  print "Hello World"
dofile('app.lua')     <==>  dofile 'app.lua'
config({ x = 1 })     <==>  config{ x = 1 }

Tabellen & Arrays

Tabellen sind Luas einzige Datenstruktur. Arrays verwenden 1-basierte Indizierung:

-- Leere Tabelle
local t = {}

-- Key-Value-Tabelle (Dictionary)
local user = { name = "Alice", age = 30 }
user.role = "admin"
user["email"] = "[email protected]"

-- Sequentielles Array (1-basierter Index)
local fruits = { "apple", "banana", "cherry" }
print(fruits[1])  -- gibt "apple" aus
print(#fruits)    -- Längenoperator (3)

Kontrollfluss & Schleifen

Bedingungen

Nur false und nil sind in Lua falsy. 0 und "" sind truthy:

if score >= 90 then
  grade = "A"
elseif score >= 80 then
  grade = "B"
else
  grade = "C"
end

Schleifen

-- While-Schleife
local count = 1
while count <= 5 do
  count = count + 1
end

-- Repeat...until-Schleife (läuft mindestens einmal)
repeat
  count = count - 1
until count == 0

-- Numerische For-Schleife: for var = start, stop [, step]
for i = 1, 10, 2 do
  print(i) -- 1, 3, 5, 7, 9
end

-- Generische For-Schleife: ipairs (Array) und pairs (Dictionary)
for index, value in ipairs(fruits) do
  print(index, value)
end

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

Funktionen

Definitionen & Mehrere Rückgabewerte

-- Mehrere Rückgabewerte
local function min_max(a, b)
  if a < b then
    return a, b
  else
    return b, a
  end
end

local minimum, maximum = min_max(10, 5)

-- Variable Argumentenanzahl (varargs)
local function sum(...)
  local s = 0
  for _, v in ipairs({...}) do
    s = s + v
  end
  return s
end

Metatables & Objektorientierte Programmierung

Metatables & Metamethoden

local Vector = {}
Vector.__index = Vector

function Vector.new(x, y)
  local instance = setmetatable({}, Vector)
  instance.x = x
  instance.y = y
  return instance
end

-- Metamethode für Vektoraddition
function Vector.__add(a, b)
  return Vector.new(a.x + b.x, a.y + b.y)
end

function Vector:__tostring()
  return string.format("(%d, %d)", self.x, self.y)
end

local v1 = Vector.new(1, 2)
local v2 = Vector.new(3, 4)
local v3 = v1 + v2
print(v3) -- "(4, 6)"

Metamethoden-Referenz

Metamethode Auslösendes Ereignis
__index Lesen eines nicht existierenden Feldes (t[k])
__newindex Zuweisen an ein nicht existierendes Feld (t[k] = v)
__tostring String-Konvertierung (tostring(t))
__call Aufruf der Tabelle wie eine Funktion (t())
__add, __sub Addition (+), Subtraktion (-)
__mul, __div Multiplikation (*), Division (/)
__eq, __lt, __le Vergleich (==, <, <=)
__concat Verkettung (..)

Standardbibliothek-APIs

String-Funktionen

string.len("hello")             -- 5 (#"hello" also works)
string.lower("HELLO")           -- "hello"
string.upper("hello")           -- "HELLO"
string.sub("hello", 2, 4)       -- "ell"
string.format("%s = %d", "x", 5)-- "x = 5"
string.gsub("banana", "a", "o") -- "bonono"
string.find("hello world", "wor") -- 7, 9

Tabellen-Funktionen

table.insert(fruits, "orange")     -- Am Ende anhängen
table.insert(fruits, 1, "grape")   -- Am Index 1 einfügen
table.remove(fruits, 1)            -- Erstes Element entfernen
table.concat(fruits, ", ")         -- Strings verbinden: "apple, banana"
table.sort(fruits)                 -- Array an Ort und Stelle sortieren

Mathematische Funktionen

math.abs(-10)         -- 10
math.floor(3.7)       -- 3
math.ceil(3.2)        -- 4
math.max(1, 9, 4)     -- 9
math.random(1, 100)   -- Zufallszahl zwischen 1 und 100

Referenzen

Verwandte Themen