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.

Hotschke
  • 9,402
  • 6
  • 46
  • 53
Mert Nuhoglu
  • 9,695
  • 16
  • 79
  • 117
  • 2
    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. – Etan Reisner Jan 12 '16 at 14:18
  • 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. – Etan Reisner Jan 12 '16 at 14:19
  • 2
    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. – Mert Nuhoglu Jan 12 '16 at 15:28
  • 1
    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 . – Etan Reisner Jan 12 '16 at 15:33
  • did you end up finding a solution to this? – Charlie Parker Mar 15 '16 at 19:08
  • My security settings do include the "allowance" of Hammerspoon. The issue remains that for me, similar to yours, wherein the returning value is `nil`. – kuanb Dec 20 '16 at 06:16

1 Answers1

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.

Marc Balmer
  • 1,780
  • 1
  • 11
  • 18