Skip to content

Instantly share code, notes, and snippets.

@Zbizu
Last active April 2, 2024 07:55
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Zbizu/43df621b3cd0dc460a76f7fe5aa87f30 to your computer and use it in GitHub Desktop.
Save Zbizu/43df621b3cd0dc460a76f7fe5aa87f30 to your computer and use it in GitHub Desktop.
operating system (OS) detection in Lua
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
@TheBlckbird
Copy link

That worked. Thanks!

@kevmul
Copy link

kevmul commented Jan 2, 2024

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

@TheBlckbird
Copy link

TheBlckbird commented Jan 2, 2024

I used this to play a sound using the command each OS provides:

  • afplay on macOS
  • play 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment