Hammerspoon’s configuration files are written in Lua, so a basic knowledge of the language is very useful to be an effective user of Hammerspoon. In this 2-part article I will show you the basics of Lua so you can read and write Hammerspoon configuration. Along the way you will discover that Lua is a surprisingly powerful language.
Lua is a scripting language created in 1993, and focused from the beginning in being an embedded language for extending other applications. It is easy to learn and use while having pretty powerful features, and is frequently used in games, but also in many other applications including, of course, Hammerspoon.
Lua includes all the common flow-control structures you might expect. Some examples:
local info = "No package selected"
if pkg and pkg ~= "" then
info, st = hs.execute("/usr/local/bin/brew info " .. pkg)
if st == nil then
info = "No information found about formula '" .. pkg .. "'!"
In this example, in addition to the if statement, you can see in the line that runs
hs.execute that Lua functions can return multiple values (which is not the same as returning an array, which counts as a single value). Within the function, this is implemented simply by separating the values with commas in the
return statement, like this:
return val1, val2. You can also see in action the following operators:
== for equality;
~= for inequality (in this respect it differs from most C-like languages, which use
.. for string concatenation;
and for the logical AND operation (by extension, you can deduct that
not are also available).
local doReload = false
for _,file in pairs(files) do
if file:sub(-4) == ".lua" and (not string.match(file, '/[.]#')) then
doReload = true
In this example we see the for statement in its so-called generic form:
for <var> in <expression> do <block> end
This statement loops the variables over the values returned by the expressions, executing the block with each the consecutive value until it becomes