How to properly import a lua script from a lower directory into another one, +Hammerspoon

315 Views Asked by At

I am trying to create an organized library for lu functions to be configured in the hammerspoon init script, however the import syntax that I have found online doesnt seem to work the same way, or perhaps i am ignorant to something..

I have seen answers that you can require them directly if they are in the same directory, but for the sake of organization I am curious if this is possible

init.lua:

local web_elem_poc = require "web_elements/web_elem_poc.lua"

doc = {}

function doc.init()
    web_elem_poc.helloWorld("1234")
end

web_elem_poc.lua:

function web_elem_poc.helloWorld(content)

    hs.hotkey.bind(
      {"cmd", "alt", "ctrl"}, "W",
       function()
        hs.alert.show(content)
      end
    )
end 

return 0

Hammerspoon error:

{...}
web_elements/web_elem_poc.dylib'
    no file '~/.local/share/hammerspoon/site/lib/web_elements/web_elem_poc.dylib'
    no file '~/.local/share/hammerspoon/site/lib/web_elements/web_elem_poc.so'
stack traceback:
    [C]: in function 'rawrequire'
    ...poon.app/Contents/Resources/extensions/hs/_coresetup.lua:662: in function 'require'
    /Users/AVONSTU1/.hammerspoon/init.lua:1: in main chunk
    [C]: in function 'xpcall'
    ...poon.app/Contents/Resources/extensions/hs/_coresetup.lua:723: in function 'hs._coresetup.setup'
    (...tail calls...)

Can someone please spot the issue?

I am using Hammerspoon and hitting refresh config. I have tried several forms of require including as you see using the import as an object and refering to it that way and just importing the script and using the function directly.

1

There are 1 best solutions below

0
On

In the init.lua file, you will want to import the file web_elements.web_elem_poc without the extension by using the following code:

local web_elem_poc = require "web_elements.web_elem_poc"
web_elem_poc.helloWorld("This is cool!")

In the web_elem_poc.lua file, you will need to define the web_elem_poc module and the helloWorld function as follows:

local web_elem_poc = {}

function web_elem_poc.helloWorld(content)
  print("This is web_elem_poc.helloWorld with content: ".. content)
end

return web_elem_poc

Assuming that the directory structure looks like this:

<>/init.lua
<>/web_elements.web_elem_poc.lua

You should see the message This is web_elem_poc.helloWorld with content: This is cool! printed on the console.