Can I separate `init.lua` to different components in Hammerspoon?
Asked Answered
T

1

14

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?

Tennietenniel answered 15/6, 2017 at 6:5 Comment(1)
Usually you would do it with require() or dofile(). Not sure if those are available in your environment.Clementina
G
18

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.

Graaf answered 15/6, 2017 at 7:8 Comment(4)
Thanks. It worked. Seems that the return value of the require function is a boolean value. hs.alert.show(AppWatcher) showed true.Tennietenniel
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.Graaf
What if you have a spoon, and want to separate it into multiple files? Can the main spoon/init.lua file include other files?Helman
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.)Graaf

© 2022 - 2024 — McMap. All rights reserved.