Call an anonymous function with a local variable as a parameter

I have a function that creates an object (in this case, a Hammerspoon Notify object), and I would like to pass this object as a parameter to an anonymous function, which in itself is an argument to the function call.

This is a very confusing explanation, but I think the example makes this 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 the nprints for the first time (s hs.notify: Title (0x7fbd2b5318f8)), but within a second time nilwithin the anonymous function and it produces an error: attempt to index a nil value (local 'n').

This approach makes sense because I never pass it on. Is there any way to pass it on? Call Signature hs.timer.doAfter: hs.timer.doAfter(sec, fn) -> timer( http://www.hammerspoon.org/docs/hs.timer.html#doAfter )

+4
1

n, n . , , , , , -, -local n .

, , n . n , , hs.notify(...).

function main()
    local n = hs.notify(...)
    print(n)          -- `hs.notify: Title (0x7fbd2b5318f8)`
    hs.timer.doAfter(1, function() -- <== no argument
        print(n)      -- nil
        n:withdraw()  -- error: attempt to index a nil value (local 'n')
    end)
end
+8

Source: https://habr.com/ru/post/1648069/


All Articles