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

前端 未结 5 1312
离开以前
离开以前 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
    

提交回复
热议问题