Skip to content

Instantly share code, notes, and snippets.

@Zbizu
Last active December 21, 2024 13:13
Show Gist options
  • 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

@Kein
Copy link

Kein commented Dec 21, 2024

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