/ Lua-Cheatsheet
Lua-Hilfe
Toolbox · Lua 5.4.1

Lua auf einen Blick

Die wichtigsten Muster für start.lua – lokal verfügbar, kurz und kopierbar.

start.lua
Toolbox-Kontext Das Skript startet beim Klick auf eine Tool-Karte. Timeout 0 bedeutet unbegrenzt. Tools sind vertrauenswürdig und dürfen über os und io auf das System zugreifen.

Nur eine laufende Instanz

-- toolbox: single-instance

-- Während dieses Skript läuft, wird seine
-- Tool-Karte rot angezeigt und gesperrt.
-- Ohne die Direktive sind parallele Starts erlaubt.

Variablen & Typen

local name = "Toolbox"
local count = 3
local enabled = true
local nothing = nil

-- Typen prüfen
type(name)       -- "string"
tostring(count)  -- "3"
tonumber("42")   -- 42

Operatoren

-- Rechnen: + - * / // % ^
local half = 7 // 2       -- 3
local text = "Lua " .. "5.4"
local length = #text

-- Vergleich: == ~= < > <= >=
-- Logik: and, or, not

Bedingungen

if count > 10 then
    print("groß")
elseif count > 0 then
    print("positiv")
else
    print("leer")
end

Schleifen

for i = 1, 5 do
    print(i)
end

local i = 1
while i <= 3 do
    i = i + 1
end

repeat
    i = i - 1
until i == 0

Funktionen

local function greet(name)
    return "Hallo " .. name
end

local function position()
    return 10, 20
end

local x, y = position()
print(greet("Toolbox"), x, y)

Tabellen

local tool = {
    name = "Backup",
    tags = { "files", "daily" }
}

print(tool.name)
print(tool.tags[1]) -- ab 1 indiziert

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

Strings

local path = [[C:\Projekte\Toolbox]]
local upper = string.upper("lua")
local found = string.find("start.lua", "lua")
local formatted = string.format("%s: %d", "Dateien", 4)

Dateien

local file, err = io.open("status.txt", "w")
if not file then
    error(err)
end

file:write("fertig\n")
file:close()

Fehler behandeln

local ok, result = pcall(function()
    assert(false, "etwas ging schief")
end)

if not ok then
    print("Fehler:", result)
end

Module

-- helper.lua
local M = {}
function M.run()
    return "fertig"
end
return M

-- start.lua
local helper = require("helper")
print(helper.run())

Gültigkeitsbereiche

local outer = "sichtbar"
do
    local inner = "nur im Block"
    print(outer, inner)
end

-- Ohne local wird eine globale Variable erzeugt.
-- Globale Namen möglichst vermeiden.

Listen & ipairs

local files = { "a.txt", "b.txt" }
table.insert(files, "c.txt")
local last = table.remove(files)

for index, file in ipairs(files) do
    print(index, file)
end

Mehrfachwerte & Varargs

local function bounds()
    return 10, 20
end

local function join(...)
    return table.concat({ ... }, ", ")
end

local min, max = bounds()
print(join("Lua", min, max))

String-Muster

local text = "build-2026.log"
local year = text:match("build%-(%d+)%.log")

local clean = text:gsub("[^%w%.%-]", "_")
for word in string.gmatch("a,b,c", "[^,]+") do
    print(word)
end

Zeit & Datum

local now = os.time()
local stamp = os.date("%Y-%m-%d %H:%M:%S", now)
print(stamp)

local started = os.clock()
-- Arbeit ...
print("CPU-Sekunden", os.clock() - started)

Coroutinen

local worker = coroutine.create(function()
    coroutine.yield("Schritt 1")
    return "fertig"
end)

local ok, value = coroutine.resume(worker)
assert(ok, value)
print(value)

Metatables

local defaults = { timeout = 30 }
local config = setmetatable({}, {
    __index = defaults
})

print(config.timeout) -- 30
config.timeout = 10

Defensiv aufräumen

local file <close> = assert(io.open("data.txt", "r"))
local content = file:read("*a")
-- Lua 5.4 schließt file beim Verlassen
-- des Gültigkeitsbereichs automatisch.

assert(#content > 0, "Datei ist leer")

In Toolbox verfügbare Bibliotheken

baseosstringcoroutinepackage tablemathutf8io

Toolbox-Rezepte unter Windows

Programm starten

-- start benötigt einen leeren Fenstertitel vor dem Pfad
local command = [[start "" "C:\Program Files\App\app.exe"]]
local ok, kind, code = os.execute(command)
assert(ok, string.format("Start fehlgeschlagen: %s %s", kind, code))

Ordner öffnen

local folder = [[C:\Projekte]]
os.execute('explorer "' .. folder .. '"')

-- Relative Pfade beziehen sich auf das
-- Arbeitsverzeichnis von Toolbox.

Umgebungsvariablen

local profile = assert(os.getenv("USERPROFILE"))
local temp = os.getenv("TEMP") or profile
print(profile, temp)

Sicheres Kommando-Quoting

local function quote(value)
    assert(not value:find('"'), "Ungültiges Anführungszeichen")
    return '"' .. value .. '"'
end

-- Keine ungeprüften Eingaben an os.execute übergeben.