1

Related to this post, Detect OS in Vimscript

This configuration detects and sets the operating system in Vim. It uses conditional statements to determine if the OS is Windows or Unix-like.

if !exists("g:os")
    if has("win64") || has("win32") || has("win16")
        let g:os = "Windows"
    else
        let g:os = substitute(system('uname'), '\n', '', '')
    endif
endif

Is there a more efficient or elegant way to achieve this in Lua?

PS: I'm a newbie at this. This is my first try. Please let me know if it needs any fix.

if not vim.g.os then
    local is_windows = vim.fn.has("win64") or vim.fn.has("win32") or vim.fn.has("win16")
    if is_windows then
        vim.g.os = "Windows"
    else
        local uname_output = vim.fn.system('uname')
        vim.g.os = string.gsub(uname_output, '\n', '')
    end
end

There's a bug. This code shows Windows in my fedora system.

Vivian De Smedt
  • 16,336
  • 3
  • 18
  • 37
Mega Bang
  • 199
  • 11

1 Answers1

1

I would do:

if vim.fn.exists('g:os') == 0 then
    local is_windows = vim.fn.has("win64") == 1 or vim.fn.has("win32") == 1 or vim.fn.has("win16") == 1
    if is_windows then
        vim.g.os = "Windows"
    else
        local uname_output = vim.fn.system('uname')
        vim.g.os = string.gsub(uname_output, '\n', '')
    end
end

But I have tested your code and with Neovim 9.2 in the absence of the g:os variable it seems to work fine too.

Vivian De Smedt
  • 16,336
  • 3
  • 18
  • 37