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.
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!
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()becomesnil: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")