Hammerspoon: Help with kill function

Created on 29 Sep 2020  路  3Comments  路  Source: Hammerspoon/hammerspoon

I want to relaunch the app and I'm using the following code:

hs.application.get("App Name"):kill()
hs.application.open("App Name")

If the app is running at that time, code works as expected.

If the app is not running, hs.application.open does not run.

Most helpful comment

The approach by @latenitefilms is close for your original problem. The problem with your original approach is that if "App Name" isn't currently running, then hs.application.get("App Name"):kill() becomes nil:kill() which generates the error "attempt to index a nil value" and stops execution of the code.

Something like this should be closer to what your original statement suggests you want:

~lua
-- remove local if you want to use this function outside of the file in which it is defined
-- (e.g. in the console)
local function launchOrRelaunch(appName)
local app = hs.application.get(appName)
if app then
app:kill()
end
hs.application.open(appName)
end
~

Then invoke it when you want as launchOrRelanuch("App Name")

All 3 comments

Maybe try something like this?

local function launchOrKillApp(appName)
    local app = hs.application.get(appName)
    if app then
        app:kill()
    else
        hs.application.open(appName)
    end
end

The approach by @latenitefilms is close for your original problem. The problem with your original approach is that if "App Name" isn't currently running, then hs.application.get("App Name"):kill() becomes nil:kill() which generates the error "attempt to index a nil value" and stops execution of the code.

Something like this should be closer to what your original statement suggests you want:

~lua
-- remove local if you want to use this function outside of the file in which it is defined
-- (e.g. in the console)
local function launchOrRelaunch(appName)
local app = hs.application.get(appName)
if app then
app:kill()
end
hs.application.open(appName)
end
~

Then invoke it when you want as launchOrRelanuch("App Name")

@latenitefilms @asmagill Thank you. That worked perfectly!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jiahut picture jiahut  路  3Comments

aaronjensen picture aaronjensen  路  3Comments

latenitefilms picture latenitefilms  路  3Comments

asmagill picture asmagill  路  4Comments

agzam picture agzam  路  3Comments