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.

1 Answer 1

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.

7
  • The code seems fine. I still haven't figured out this code output. I'm on fedora. How to test this? Can you tell me?
    – Mega Bang
    Oct 11 at 6:53
  • 1
    This code is setting the g:os variable I suppose on Fedora it should set it to Linux (at least it what it does on Ubuntu). On Windows it set it to Windows. You can verify the variable value with the command :echo g:os Oct 11 at 6:55
  • Showing error E121: Undefined variable: g:os
    – Mega Bang
    Oct 11 at 6:59
  • 1
    I have tested on Ubuntu and this code is working (I was confused that in Lua 0 is true). Oct 11 at 7:20
  • 1
    OMG, It is working.
    – Mega Bang
    Oct 11 at 7:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.