Question

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 enviromental variable "OS" gives me the name of the system's OS, but is there some variable that exists on both Windows and most flavors of Unix that can be checked?

Was it helpful?

Solution

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'.

OTHER TIPS

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

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.

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top