Last active
December 21, 2024 13:13
-
-
Save Zbizu/43df621b3cd0dc460a76f7fe5aa87f30 to your computer and use it in GitHub Desktop.
operating system (OS) detection in Lua
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getOS() | |
-- ask LuaJIT first | |
if jit then | |
return jit.os | |
end | |
-- Unix, Linux variants | |
local fh,err = assert(io.popen("uname -o 2>/dev/null","r")) | |
if fh then | |
osname = fh:read() | |
end | |
return osname or "Windows" | |
end |
Nice! I used this in my NeoVim utils. Had to make a slight modification.
-- /user.getOS.lua
local getOS = {}
function getOS.getName()
local osname
-- ask LuaJIT first
if jit then
return jit.os
end
-- Unix, Linux variants
local fh, err = assert(io.popen("uname -o 2>/dev/null", "r"))
if fh then
osname = fh:read()
end
return osname or "Windows"
end
return getOS
Then you can call in another file
-- /some/otherFile.lua
local getOS = require("user.getOS")
if getOs.getName() == "Windows" then <doSomething> end
I used this to play a sound using the command each OS provides:
afplay
on macOSplay
on Linux- idc about Windows
https://github.com/TheBlckbird/neovim-config/blob/master/lua/sounds.lua:
local M = {}
local function getOS()
-- ask LuaJIT first
if jit then
return jit.os
end
-- Unix, Linux variants
local fh, err = assert(io.popen("uname -o 2>/dev/null", "r"))
if fh then
Osname = fh:read()
end
return Osname or "Windows"
end
function M.play(sound_file)
vim.schedule(function()
local command = ""
if getOS() == "OSX" then
command = "afplay"
elseif getOS() == "Linux" then
command = "play"
else
return
end
command = command .. " " .. sound_file .. " &"
os.execute(command)
end)
end
return M
This is a terrible solution for CLI apps, it re-opens and re-initializes conout 4-5 times in a row, leading not just to a seizure-flashing console windows, but also to all kinds of bugs down the road
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That worked. Thanks!