lua-basics
Skill1 starsChanged 15 days agoMITView on GitHub
Lua language fundamentals for developers new to Lua: types, local vs global variables, conditionals (falsy values: only nil and false), functions (named, anonymous, multiple returns, variadic), tables as arrays and dictionaries (1-indexed!), iterating with ipairs/pairs, strings (pattern matching, format, split), closures, error handling (pcall/xpcall), OOP with the colon syntax, the Fibaro class system, and common gotchas (table reference semantics, # operator limitations, tostring/tonumber). USE FOR: help with Lua syntax, understanding why code behaves unexpectedly, table/string/function patterns, OOP in Lua.
1 other project uses a version of this.
Adopted by
Most recently taken up by
- germanfndez/fiveai-skillstheir own version, first seen Sep 10, 2026
Other versions1 project uses a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 1
- germanfndez/fiveai-skills★ 19same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository18 other files it gives its agents.
- AGENTS.mdAGENTS.md
- .github/copilot-instructions.mdCopilot instructions
- code-tourSkill
- flua-setupSkill
- flua-troubleshootingSkill
- hc3-lua-scenesSkill
- hc3-rest-apiSkill
- hc3-write-safetySkill
- network-device-testSkill
- plua-migrationSkill
- quickapp-apiSkill
- quickapp-patternsSkill
- quickapp-testSkill
- quickapp-troubleshootingSkill
- quickapp-typesSkill
- quickapp-uiSkill
- qwikchildSkill
- skill-creatorSkill
The file
Files
Lua Basics for QuickApp Developers
A practical Lua reference for developers who are new to Lua but have experience in other programming languages. Focused on patterns you'll actually use in Fibaro QuickApps.
Types
Lua has 8 types: nil, boolean, number, string, table, function, userdata, thread.
print(type(nil)) -- "nil"
print(type(true)) -- "boolean"
print(type(42)) -- "number"
print(type(3.14)) -- "number" (no int/float split in Lua 5.3+)
print(type("hello")) -- "string"
print(type({})) -- "table"
print(type(print)) -- "function"Variables: local vs global
Always prefer local. Global variables pollute _G and can collide across files.
x = 10 -- GLOBAL (avoid)
local y = 20 -- local to this scope (prefer)In a QuickApp, instance state goes on self:
function QuickApp:onInit()
self.myTimer = nil -- instance variable — safe
self.count = 0
endConditionals
if x > 10 then
print("big")
elseif x > 5 then
print("medium")
else
print("small")
endFalsy values: only nil and false. Zero and empty string are truthy!
if 0 then print("truthy") end -- prints!
if "" then print("truthy") end -- prints!
if nil then print("truthy") end -- does NOT print
if false then print("truthy") end -- does NOT printTernary idiom:
local label = active and "ON" or "OFF"
-- caution: if first branch could be false/nil, use an if/else insteadFunctions
-- Named function
function add(a, b)
return a + b
end
-- Equivalent (functions are values)
local add = function(a, b)
return a + b
end
-- Multiple return values
local function minmax(a, b)
return math.min(a,b), math.max(a,b)
end
local lo, hi = minmax(10, 3) -- lo=3, hi=10
-- Variadic arguments
local function sum(...)
local total = 0
for _, v in ipairs({...}) do total = total + v end
return total
end
print(sum(1,2,3,4)) -- 10Functions must be defined before they are called — Lua runs top to bottom:
-- Forward declaration for mutual recursion
local isEven, isOdd
isEven = function(n) return n == 0 or isOdd(n - 1) end
isOdd = function(n) return n ~= 0 and isEven(n - 1) endTables
Tables are Lua's only data structure — they act as both arrays and dictionaries.
As array (1-indexed!)
local fruits = {"apple", "banana", "cherry"}
print(fruits[1]) -- "apple" (NOT fruits[0])
print(#fruits) -- 3
table.insert(fruits, "date") -- append
table.insert(fruits, 2, "avocado") -- insert at position 2
table.remove(fruits, 1) -- remove first element
table.sort(fruits) -- sort in placeAs dictionary
local person = { name = "Alice", age = 30 }
person.city = "London"
person["country"] = "UK"
print(person.name) -- "Alice"
person.age = nil -- remove fieldIterating
Ordered integer keys:
for i, v in ipairs(fruits) do print(i, v) endAll keys (unordered):
for key, value in pairs(person) do print(key, "=", value) endNumeric for:
for i = 1, 10 do print(i) end -- 1 to 10
for i = 10, 1, -1 do print(i) end -- 10 down to 1Strings
local s = "Hello, World!"
print(#s) -- 13
print(s:upper()) -- "HELLO, WORLD!"
print(s:sub(1, 5)) -- "Hello" (1-indexed, inclusive)
print(s:find("World")) -- 8 14
-- Concatenation
local msg = "Temperature: " .. tostring(temp) .. "°C"
-- Formatting
local msg = string.format("Device %d: %.1f°C", id, temp)
-- Pattern matching
local year, month, day = ("2024-03-15"):match("(%d+)-(%d+)-(%d+)")
-- Split (Fibaro extension)
local parts = ("a,b,c"):split(",") -- {"a","b","c"}Closures
A function that captures variables from its enclosing scope:
function QuickApp:onInit()
local count = 0 -- captured by the closure below
setInterval(function()
count = count + 1
self:debug("Tick", count) -- self is also captured
end, 1000)
endError Handling
-- pcall: protected call — catches errors
local ok, result = pcall(function()
return json.decode(rawString)
end)
if ok then
print(result.key)
else
self:error("Decode failed:", result) -- result is the error message
end
-- assert: error if condition false
assert(value ~= nil, "value is required")
-- raise error
error("something went wrong")
error({code = 404, msg = "not found"}) -- can be any valueObject-Oriented Programming
The colon syntax
obj:method(arg) is syntax sugar for obj.method(obj, arg) — passes the object as self.
-- These are identical:
self:debug("hello")
QuickApp.debug(self, "hello")Defining methods on QuickApp
function QuickApp:doSomething(x)
self:debug("doing", x)
return x * 2
endCreating your own classes (Fibaro class system)
class 'MyHelper'
function MyHelper:__init(name)
self.name = name
self.data = {}
end
function MyHelper:add(item)
table.insert(self.data, item)
end
function MyHelper:count()
return #self.data
end
local h = MyHelper("test")
h:add("item1")
print(h:count()) -- 1Inheritance
class 'MySensor'(QuickAppChild)
function MySensor:__init(device)
QuickAppChild.__init(self, device) -- MUST call parent __init
end
function MySensor:onInit()
self:debug("MySensor", self.id, "started")
endCommon Gotchas
# is unreliable with holes or non-integer keys
local t = {1, 2, nil, 4} -- hole: #t is undefined
local t = {a=1, b=2} -- #t == 0 (no integer keys)Tables are references, not copies
local a = {1, 2, 3}
local b = a -- b IS a (same table)
b[1] = 99
print(a[1]) -- 99!
-- Shallow copy:
local function copy(t)
local c = {}
for k, v in pairs(t) do c[k] = v end
return c
endAlways use tostring / tonumber for conversions
local s = tostring(42) -- "42"
local n = tonumber("3.14") -- 3.14
local n = tonumber("abc") -- nil (always check)
if n then ... endBuild strings efficiently with table.concat
-- Slow (creates many intermediate strings):
local s = ""
for i = 1, 100 do s = s .. tostring(i) .. "," end
-- Fast:
local parts = {}
for i = 1, 100 do parts[i] = tostring(i) end
local s = table.concat(parts, ",")Useful Standard Library
math.floor(3.7) -- 3
math.ceil(3.2) -- 4
math.abs(-5) -- 5
math.max(1,5,3) -- 5
math.random(1,10) -- random int 1–10
string.format("%.2f", 3.14159) -- "3.14"
string.format("%05d", 42) -- "00042"
string.rep("ab", 3) -- "ababab"
table.concat({"a","b","c"}, "-") -- "a-b-c"
os.time() -- Unix timestamp
os.date("%Y-%m-%d %H:%M:%S") -- "2024-03-15 14:30:00"
os.date("*t") -- {year,month,day,hour,min,sec,...}Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

