How can I determine the OS of the system from within a Lua script?

前端 未结 5 1320
离开以前
离开以前 2021-02-12 12:36

Ok I need to determine the system\'s OS from a Lua script, but Lua as such has no API for this, so I use os.getenv() and query enviromental variables. On Windows checking the en

相关标签:
5条回答
  • 2021-02-12 13:18

    When lua is compiled, it is configured slightly differently depending on what operating system it is compiled for.

    Many of the strings which are set in the 'package' module can thus be used to distinguish which system it was compiled for.

    For instance, when lua loads C-based modules which are distributed as dynamic libraries, it has to know the extension used for those libraries, which is different on each OS.

    Thus, you can use a function like the following to determine the OS.

    local BinaryFormat = package.cpath:match("%p[\\|/]?%p(%a+)")
    if BinaryFormat == "dll" then
        function os.name()
            return "Windows"
        end
    elseif BinaryFormat == "so" then
        function os.name()
            return "Linux"
        end
    elseif BinaryFormat == "dylib" then
        function os.name()
            return "MacOS"
        end
    end
    BinaryFormat = nil
    
    0 讨论(0)
  • 2021-02-12 13:18

    I guess that if you just need Windows/Unix detection, you could check the filesystem for the existence of /etc or /bin or /boot directories. Aditionally, if you need to know which distro is it, most Linux distros have a little file in /etc showing the distro and version, sadly they all name it differently.

    0 讨论(0)
  • 2021-02-12 13:21

    Unixes should have the $HOME variable (while Windows doesn't have that), so you can check it (after checking the OS variable is empty).

    0 讨论(0)
  • 2021-02-12 13:23

    You can try package.config:sub(1,1). It returns the path separator, which is '\\' on Windows and '/' on Unixes...

    0 讨论(0)
  • 2021-02-12 13:34

    On a Unix system, try os.capture 'uname' where os.capture is defined below:

    function os.capture(cmd, raw)
      local f = assert(io.popen(cmd, 'r'))
      local s = assert(f:read('*a'))
      f:close()
      if raw then return s end
      s = string.gsub(s, '^%s+', '')
      s = string.gsub(s, '%s+$', '')
      s = string.gsub(s, '[\n\r]+', ' ')
      return s
    end
    

    This will help on all flavors of unix and on Mac OSX. If it fails, you might be on a Windows system? Or check os.getenv 'HOME'.

    0 讨论(0)
提交回复
热议问题