This first edition was written for Lua 5.0. While still largely relevant for later versions, there are some differences.
The fourth edition targets Lua 5.3 and is available at Amazon and other bookstores.
By buying the book, you also help to support the Lua project.


22.2 – Other System Calls

The os.exit function terminates the execution of a program. The os.getenv function gets the value of an environment variable. It receives the name of the variable and returns a string with its value:

    print(os.getenv("HOME"))    --> /home/lua
If the variable is not defined, the call returns nil. The function os.execute runs a system command; it is equivalent to the system function in C. It receives a string with the command and returns an error code. For instance, both in Unix and in DOS-Windows, you can write the following function to create new directories:
    function createDir (dirname)
      os.execute("mkdir " .. dirname)
    end
The os.execute function is powerful, but it is also highly system dependent.

The os.setlocale function sets the current locale used by a Lua program. Locales define behavior that is sensitive to cultural or linguistic differences. The setlocale function has two string parameters: the locale name and a category, which specifies what features the locale will affect. There are six categories of locales: "collate" controls the alphabetic order of strings; "ctype" controls the types of individual characters (e.g., what is a letter) and the conversion between lower and upper cases; "monetary" has no influence in Lua programs; "numeric" controls how numbers are formatted; "time" controls how date and time are formatted (i.e., function os.date); and "all" controls all the above functions. The default category is "all", so that if you call setlocale with only the locale name it will set all categories. The setlocale function returns the locale name or nil if it fails (usually because the system does not support the given locale).

    print(os.setlocale("ISO-8859-1", "collate"))   --> ISO-8859-1

The category "numeric" is a little tricky. Although Portuguese and other Latin languages use a comma instead of a point to represent decimal numbers, the locale does not change the way that Lua parses numbers (among other reasons because expressions like print(3,4) already have a meaning in Lua). Therefore, you may end with a system that cannot recognize numbers with commas, but cannot understand numbers with points either:

    -- set locale for Portuguese-Brazil
    print(os.setlocale('pt_BR'))    --> pt_BR
    print(3,4)                      --> 3    4
    print(3.4)       --> stdin:1: malformed number near `3.4'