I have a function that creates an object (in this case, a Hammerspoon Notify object), and I would like to pass this object as the parameter to an anonymous function that is itself an argument to a function call.
That's a very convoluted explanation, but I think an example makes it pretty clear.
function main()
local n = hs.notify(...)
print(n) -- `hs.notify: Title (0x7fbd2b5318f8)`
hs.timer.doAfter(1, function(n)
print(n) -- nil
n:withdraw() -- error: attempt to index a nil value (local 'n')
end)
end
The output of this is that n
prints fine the first time (hs.notify: Title (0x7fbd2b5318f8)
), but is nil
the second time, inside the anonymous function, and it throws an error: attempt to index a nil value (local 'n')
.
This sort of makes sense, because I'm never really passing it in. Is there a way to pass it in?
The signature of the hs.timer.doAfter
call is: hs.timer.doAfter(sec, fn) -> timer
(http://www.hammerspoon.org/docs/hs.timer.html#doAfter)
print(n)
statement, a good IDE would warn you that you have assignedn
a value that is never used, which would help you detect the hiding that Kurt explains in his answer. – Orelee