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

1

9

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.

Fonz answered 12/1, 2016 at 12:35 Comment(6)
If that's the default lua repl (or similar) then drop local. Each line is executed in its own chunk so your local variable isn't in scope anymore for the next line.Delmore
Also don't solve your question with an update to the question itself. File an answer and, if you think it is the correct one and no one else answers, then accept it.Delmore
Thank you @EtanReisner, actually dropping local solved the unexpected behavior. I think this is the actual answer. Please file it as answer, and I will accept it.Fonz
That issue should not affect an actual script being run by the application itself in the normal way. That's an artifact of how the lua repl works. I don't know what permissions issue you say you fixed but that if that fixed the actual script then that's the solution to your real problem. The local issue at the repl is a side-issue to that issue .Delmore
did you end up finding a solution to this?Showers
My security settings do include the "allowance" of Hammerspoon. The issue remains that for me, similar to yours, wherein the returning value is nil.Cocke
F
2

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.

Ferino answered 2/1, 2017 at 11:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.