Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua Hammerspoon: hs.window.focusedWindow() is nil when assigned to a variable

I use an automation software called hammerspoon on osx.

When I use the following code in hammerspoon's console, win is nil:

> local win = hs.window.focusedWindow()
> win
nil

But actually the function returns some value:

> hs.window.focusedWindow()
hs.window: Hammerspoon Console (0x60000025f798)

This strange behavior breaks all window moving/sizing functions such as:

hs.hotkey.bind({"cmd", "alt", "ctrl"}, "H", function()
    local win = hs.window.focusedWindow()
    local f = win:frame()

    f.x = f.x - 10
    win:setFrame(f)
end)

Hammerspoon gives this error:

/Users/mertnuhoglu/.hammerspoon/init.lua:6: attempt to index a nil value (local 'win')
stack traceback:
    /Users/mertnuhoglu/.hammerspoon/init.lua:6: in function </Users/mertnuhoglu/.hammerspoon/init.lua:4>
stack traceback:

I don't know if this problem is caused by my computer or something else.

I have osx yosemite, version 10.10.5 and hammerspoon 0.9.43.

Update:

I found solution of the error. It is due to Privacy settings of osx.

Solution:

Prefences > Security > Privacy > Allow Apps: Hammerspoon

But still, I don't understand why hs.window.focusedWindow() returns something if it is not assigned to a variable and it returns nil when it is assigned to a variable.

like image 793
Mert Nuhoglu Avatar asked Jan 12 '16 12:01

Mert Nuhoglu


1 Answers

Hammerspoon executes each line as it's own chunk, so local variables are only available in that chunk, and no longer once the chunk has been executed.

If you want to access variables after execution of a chunk, make them global, i.e. drop the 'local' keyword.

like image 70
Marc Balmer Avatar answered Nov 02 '22 22:11

Marc Balmer