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
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
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.
Unixes should have the $HOME variable (while Windows doesn't have that), so you can check it (after checking the OS variable is empty).
You can try package.config:sub(1,1)
. It returns the path separator, which is '\\'
on Windows and '/'
on Unixes...
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'.