EMZETT.
Login

Kurz: do local x = 99 — eigener Block, verdeckt das äußere x print(x) end print(x)

Teil des Kurses Lua

Kapitel 2 von 8 im Kurs Lua. Mit Fortschritt, Quiz und Zertifikat auf der Lernseite.

Variablen: local vs. global

local x = 10            -- lokal (im Block gültig): immer bevorzugen
y = 20                  -- global (überall sichtbar): meist ein Fehler!
local a, b, c = 1, 2   -- c ist nil
print(x, y, a, b, c)
 
do
    local x = 99        -- eigener Block, verdeckt das äußere x
    print(x)
end
print(x)
 
local PI <const> = 3.14159       -- Konstante (Lua 5.4)
print(PI)
print(undefiniert)                -- nicht gesetzte Variablen sind nil

Ausgabe:

10	20	1	2	nil
99
10
3.14159
nil

Namen: Buchstaben, Ziffern, _; nicht mit Ziffer beginnen; Groß-/Kleinschreibung zählt. Verwende immer local: Globale sind langsamer und eine Quelle schwer auffindbarer Fehler.

Die Grundtypen

TypBeispielHinweis
nilnilkein Wert
booleantrue, false
number42, 3.14, 0xFF, 1e3seit 5.3 mit Ganzzahl- und Fließkomma-Untertyp
string"Text", 'Text'unveränderlich
table{1, 2}, {a = 1}die einzige Datenstruktur
functionfunction() endFunktionen sind Werte
threadCoroutine
userdataC-Daten (eingebettet)
print(type(5), math.type(5), math.type(5.0), math.type("5"))
print(7 / 2, 7 // 2, 7 % 3, 2 ^ 10, -7 // 2, -7 % 3)
print(10 / 2, 3 | 5, 3 & 5, 3 ~ 5, ~0, 1 << 4, 256 >> 2)
print(math.maxinteger, math.mininteger)
print(math.maxinteger + 1 == math.mininteger)
print(0.1 + 0.2 == 0.3, math.abs(0.1 + 0.2 - 0.3) < 1e-9)
print(math.floor(3.7), math.ceil(3.2), math.sqrt(144), math.pi)
print(math.max(3, 9, 4), math.min(3, 9, 4), math.abs(-5), math.fmod(7, 3))
print(math.tointeger(3.0), math.tointeger(3.5), tonumber("42"), tonumber("abc"), tonumber("ff", 16), tonumber("  12  "))
print(string.format("%.2f", 3.14159), 10 // 3, 10.0 // 3)
print(1e15, 2^53, 100 // 1, 3 == 3.0)

Ausgabe:

number	integer	float	nil
3.5	3	1	1024.0	-4	2
5.0	7	1	6	-1	16	64
9223372036854775807	-9223372036854775808
true
false	true
3	4	12.0	3.1415926535898
9	3	5	1
3	nil	42	nil	255	12
3.14	3	3.0
1e+15	9.007199254741e+15	100	true

Der Operator / liefert immer eine Fließkommazahl, // die Ganzzahldivision (abgerundet).

Strings

local s = "Hallo Welt"
print(#s, s:upper(), s:lower(), s:len())
print(s:sub(1, 5), s:sub(-4), s:sub(7))
print(s:find("Welt"), s:find("xyz"))
print(s:rep(2, " | "), s:reverse())
print(s:byte(1), string.char(72, 105))
print(("x"):rep(3), ("  trim  "):match("^%s*(.-)%s*$") .. "|")
print("Zeile 1\nZeile 2\tTab \"Anführungszeichen\" \\")
print([[Roh-String über
mehrere Zeilen, \n bleibt wörtlich]])
print("5" + 3, "10" * "2", 5 .. 3, 10 .. "")   -- automatische Umwandlung
print(tostring(42) .. "!", tostring(nil), tostring(true), tostring(1.5))
print(#"Grüße", utf8.len("Grüße"))
for _, code in utf8.codes("Hä") do io.write(code, " ") end
print()
print("a" < "b", "Z" < "a", "abc" == "abc")
print(string.format("%5d|%-5s|%05.1f|%x|%q", 42, "ab", 3.14159, 255, "Zeile\n2"))

Ausgabe:

10	HALLO WELT	hallo welt	10
Hallo	Welt	Welt
7	nil
Hallo Welt | Hallo Welt	tleW ollaH
72	Hi
xxx	trim|
Zeile 1
Zeile 2	Tab "Anführungszeichen" \
Roh-String über
mehrere Zeilen, \n bleibt wörtlich
8	20	53	10
42!	nil	true	1.5
7	5
72 228
true	true	true
   42|ab   |003.1|ff|"Zeile\
2"

Strings sind Bytefolgen; # zählt Bytes. Für Unicode gibt es die Bibliothek utf8. Die Methodenschreibweise s:upper() ist Kurzform für string.upper(s).

Operatoren und Vorrang

GruppeOperatoren
Rechnen+ - * / // % ^
Vergleich== ~= < <= > >= (ungleich ist ~=!)
Logikand or not
Text.. (verketten), # (Länge)
Bits& | ~ << >> ~

and/or liefern Werte, nicht nur true/false. Das ergibt das typische Muster für Standardwerte und “Ternär”:

local name = nil
print(name or "Gast")
local alter = 17
print(alter >= 18 and "volljährig" or "minderjährig")
print(false or nil, nil and 1, 0 and "ja", "" or "leer")
print(not nil, not 0, 1 == 1.0, "1" == 1)

Ausgabe:

Gast
minderjährig
nil	nil	ja
true	false	true	false

Merke

  • Immer local; Konstanten mit <const>
  • Zahlen: Ganzzahl und Fließkomma, // für Ganzzahldivision, ^ Potenz
  • Strings: .., #, Methoden wie s:upper(); Bytefolgen (utf8-Bibliothek für Unicode)
  • Ungleich ist ~=
  • x or standard und bedingung and a or b als Idiome

Übungsaufgabe

Rechne 17 // 5, 17 % 5 und 17 / 5 aus und gib sie formatiert mit string.format aus.

Quiz zur Selbstkontrolle

Weiter im Kurs

Zurück: Einführung und erstes Programm

Weiter: Kontrollfluss und Funktionen

Alle Kapitel: Lua im Überblick