11

I would like to separate init.lua script used in Hammerspoon to enhance the readability and maintainance.

So it looks like the following:

  • init.lua
  • AppWatcher.lua
  • WiFiWatcher.lua
  • KeyRemap.lua

And then from within init.lua I would read these files and make the watcher activate.

However, it seems that there is no such function defined (maybe I may be missing it, though). Is it possible to separate the logic like that in Hammerspoon?

Blaszard
  • 30,954
  • 51
  • 153
  • 233
  • Usually you would do it with `require()` or `dofile()`. Not sure if those are available in your environment. – Forivin Jun 15 '17 at 06:15

1 Answers1

14

Yes, you can do this using require.

If you put your Lua files in ~/.hammerspoon/, you can then load them using require('modulename'). For example, if you have the following modules:

  • ~/.hammerspoon/AppWatcher.lua
  • ~/.hammerspoon/WiFiWatcher.lua
  • ~/.hammerspoon/KeyRemap.lua

Then you can load them from ~/.hammerspoon/init.lua like this:

local AppWatcher  = require('AppWatcher')
local WiFiWatcher = require('WiFiWatcher')
local KeyRemap    = require('KeyRemap')

You can load any Lua modules, as long as they appear in package.path. To see the directories you can use, take a look at HammerSpoon's package.path setup file. This references the default Lua package.path, which is defined in luaconf.h.

If you want to put your Lua modules in a directory not included in package.path, you can do it by adding them to the LUA_PATH_5_3 or LUA_PATH environment variables.

Jack Taylor
  • 5,588
  • 19
  • 35
  • Thanks. It worked. Seems that the return value of the `require` function is a boolean value. `hs.alert.show(AppWatcher)` showed `true`. – Blaszard Jun 17 '17 at 04:25
  • The return value is whatever is returned from the module. Often it will be a table that contains all the functions the module is exporting. That particular module must be returning true on success and false on failure, or something like that. – Jack Taylor Jun 17 '17 at 13:53
  • What if you have a spoon, and want to separate it into multiple files? Can the main spoon/init.lua file include other files? – Brad Parks Oct 01 '20 at 20:57
  • As long as the modules you are trying to load are in Lua's package.path, you should be able to load them from anywhere. (Again, though, I don't have a Mac, so I can't actually test this out.) – Jack Taylor Oct 02 '20 at 01:38