Lua-System docs

# Module `system`

Platform independent system calls for Lua.

## Fields

windows | Flag to identify Windows.

## Environment

getenv (name) | Gets the value of an environment variable.
getenvs () | Returns a table with all environment variables.
setenv (name[, value]) | Sets an environment variable.

## Random

random ([length=1]) | Generate random bytes.

## Terminal

isatty (file) | Checks if a file-handle is a TTY.
termsize () | Get the size of the terminal in rows and columns.

## Terminal_Windows

getconsoleflags (file) | Gets console flags (Windows).
listconsoleflags (fh) | Debug function for console flags (Windows).
setconsoleflags (file, bitflags) | Sets the console flags (Windows).

## Terminal_Posix

detachfds () | Creates new file descriptions for `stdout` and `stderr`.
getnonblock (fd) | Gets non-blocking mode status for a file (Posix).
listtermflags (fh) | Debug function for terminal flags (Posix).
setnonblock (fd, make_non_block) | Enables or disables non-blocking mode for a file (Posix).
tcgetattr (fd) | Get termios state (Posix).
tcsetattr (fd, actions, termios) | Set termios state (Posix).

## Terminal_Input

_readkey () | Reads a key from the console non-blocking.
readansi (timeout[, fsleep=system.sleep]) | Reads a single key, if it is the start of ansi escape sequence then it reads the full sequence.
readkey (timeout[, fsleep=system.sleep]) | Reads a single byte from the console, with a timeout.

## Terminal_UTF-8

CODEPAGE_UTF8 | UTF8 codepage.
getconsolecp () | Gets the current console code page (Windows).
getconsoleoutputcp () | Gets the current console output code page (Windows).
setconsolecp (cp) | Sets the current console code page (Windows).
setconsoleoutputcp (cp) | Sets the current console output code page (Windows).
utf8cwidth (utf8_char[, ambiguous_width=1]) | Get the width of a utf8 character for terminal display.
utf8swidth (utf8_string[, ambiguous_width=1]) | Get the width of a utf8 string for terminal display.

## Time

gettime () | Get system time.
monotime () | Get monotonic time.
sleep (seconds[, precision=16]) | Sleep without a busy loop.

## Terminal_Backup

autotermrestore () | Backs up terminal settings and restores them on application exit.
termbackup () | Returns a backup of terminal settings for stdin/out/err.
termrestore (backup) | Restores terminal settings from a backup
termwrap (f) | Wraps a function to automatically restore terminal settings upon returning.

## Fields

windows
  Flag to identify Windows.
  - windows `true` if on Windows, `false` otherwise.

## Environment

getenv (name)
  Gets the value of an environment variable.

  NOTE: Windows has multiple copies of environment variables. For this reason, the setenv function will not work with Lua's os.getenv on Windows. If you want to use setenv then consider patching os.getenv with this implementation of getenv.

  ### Parameters:

  - name string name of the environment variable

  ### Returns:

  string or nil value of the environment variable, or nil if the variable is not set
getenvs ()
  Returns a table with all environment variables.

  ### Returns:

  table table with all environment variables and their values
setenv (name[, value])
  Sets an environment variable.

  NOTE: Windows has multiple copies of environment variables. For this reason, the setenv function will not work with Lua's os.getenv on Windows. If you want to use it then consider patching os.getenv with the implementation of system.getenv.

  ### Parameters:

  - name string name of the environment variable
  - value string value of the environment variable, if `nil` the variable will be deleted (on Windows, setting an empty string, will also delete the variable) (optional)

  ### Returns:

  boolean success

## Random

random ([length=1])
  Generate random bytes. This uses `BCryptGenRandom()` on Windows, `getrandom()` on Linux, `arc4random_buf` on BSD, and `/dev/urandom` on other platforms. It will return the requested number of bytes, or an error, never a partial result.

  ### Parameters:

  - length int number of bytes to get (default 1)

  ### Returns:

  string string of random bytes

  ### Or

  1. nil
  2. string error message

## Terminal

Unix: see https://blog.nelhage.com/2009/12/a-brief-introduction-to-termios-termios3-and-stty/

Windows: see https://learn.microsoft.com/en-us/windows/console/console-reference

isatty (file)
  Checks if a file-handle is a TTY.

  ### Parameters:

  - file file the file-handle to check, one of io.stdin, io.stdout, io.stderr.

  ### Returns:

  boolean true if the file is a tty

  ### Usage:

      local system = require('system')
      if system.isatty(io.stdin) then
          -- enable ANSI coloring etc on Windows, does nothing in Posix.
          local flags = system.getconsoleflags(io.stdout)
          system.setconsoleflags(io.stdout, flags + sys.COF_VIRTUAL_TERMINAL_PROCESSING)
      end

termsize ()
  Get the size of the terminal in rows and columns.

  ### Returns:

  1. int the number of rows
  2. int the number of columns

  ### Or

  1. nil
  2. string error message

## Terminal_Windows

getconsoleflags (file)
  Gets console flags (Windows). The `CIF_` and `COF_` constants are available on the module table. Where `CIF` are the input flags (for use with io.stdin) and `COF` are the output flags (for use with io.stdout/io.stderr).

  Note: See setconsolemode documentation for more information on the flags.

  ### Parameters:

  - file file file handle to operate on, one of io.stdin, io.stdout, io.stderr

  ### Returns:

  bitflags the current console flags.

  ### Or

  1. nil
  2. string error message

  ### Usage:

      local system = require('system')

      local flags = system.getconsoleflags(io.stdout)
      print("Current stdout flags:", tostring(flags))

      if flags:has_all_of(system.COF_VIRTUAL_TERMINAL_PROCESSING + system.COF_PROCESSED_OUTPUT) then
          print("Both flags are set")
      else
          print("At least one flag is not set")
      end

listconsoleflags (fh)
  Debug function for console flags (Windows). Pretty prints the current flags set for the handle.

  ### Parameters:

  - fh file handle (io.stdin, io.stdout, io.stderr)

  ### Usage:

      -- Print the flags for stdin/out/err
      system.listconsoleflags(io.stdin)
      system.listconsoleflags(io.stdout)
      system.listconsoleflags(io.stderr)

setconsoleflags (file, bitflags)
  Sets the console flags (Windows). The `CIF_` and `COF_` constants are available on the module table. Where `CIF` are the input flags (for use with io.stdin) and `COF` are the output flags (for use with io.stdout/io.stderr).

  To see flag status and constant names check listconsoleflags.

  Note: not all combinations of flags are allowed, as some are mutually exclusive or mutually required. See setconsolemode documentation

  ### Parameters:

  - file file file handle to operate on, one of io.stdin, io.stdout, io.stderr
  - bitflags bitflags the flags to set/unset

  ### Returns:

  boolean `true` on success

  ### Or

  1. nil
  2. string error message

  ### Usage:

      local system = require('system')
      system.listconsoleflags(io.stdout) -- List all the available flags and their current status

      local flags = system.getconsoleflags(io.stdout)
      assert(system.setconsoleflags(io.stdout,
              flags + system.COF_VIRTUAL_TERMINAL_PROCESSING)

      system.listconsoleflags(io.stdout) -- List again to check the differences

## Terminal_Posix

detachfds ()
  Creates new file descriptions for `stdout` and `stderr`. Even if the file descriptors are unique, they still might point to the same file description, and hence share settings like `O_NONBLOCK`. This means that if one of them is set to non-blocking, the other will be as well. This can lead to unexpected behavior.

  This function is used to detach `stdout` and `stderr` from the original file descriptions, and create new file descriptions for them. This allows independent control of flags (e.g., `O_NONBLOCK`) on `stdout` and `stderr`, avoiding shared side effects.

  Does not modify `stdin` (fd 0), and does nothing on Windows.

  ### Returns:

  boolean `true` on success, or throws an error on failure.

  ### See also:

  setnonblock
getnonblock (fd)
  Gets non-blocking mode status for a file (Posix).

  ### Parameters:

  - fd file file handle to operate on, one of io.stdin, io.stdout, io.stderr

  ### Returns:

  bool `true` if set to non-blocking, `false` if not. Always returns `false` on Windows.

  ### Or

  1. nil
  2. string error message
  3. int errnum

  ### See also:

  setnonblock
listtermflags (fh)
  Debug function for terminal flags (Posix). Pretty prints the current flags set for the handle.

  ### Parameters:

  - fh file handle (io.stdin, io.stdout, io.stderr)

  ### Usage:

      -- Print the flags for stdin/out/err
      system.listconsoleflags(io.stdin)
      system.listconsoleflags(io.stdout)
      system.listconsoleflags(io.stderr)

setnonblock (fd, make_non_block)
  Enables or disables non-blocking mode for a file (Posix). Check detachfds in case there are shared file descriptions.

  ### Parameters:

  - fd file file handle to operate on, one of io.stdin, io.stdout, io.stderr
  - make_non_block boolean a truthy value will enable non-blocking mode, a falsy value will disable it.

  ### Returns:

  bool `true`, if successful

  ### Or

  1. nil
  2. string error message
  3. int errnum

  ### See also:

  - getnonblock
  - detachfds

  ### Usage:

      local sys = require('system')
      sys.detachfds() -- detach stdout and stderr, so only stdin becomes non-blocking

      -- set io.stdin to non-blocking mode
      local old_setting = sys.getnonblock(io.stdin)
      sys.setnonblock(io.stdin, true)

      -- do stuff

      -- restore old setting
      sys.setnonblock(io.stdin, old_setting)

tcgetattr (fd)

  Get termios state (Posix). The terminal attributes is a table with the following fields:

  - `iflag` input flags
  - `oflag` output flags
  - `lflag` local flags
  - `cflag` control flags
  - `ispeed` input speed
  - `ospeed` output speed
  - `cc` control characters

  ### Parameters:

  - fd file file handle to operate on, one of io.stdin, io.stdout, io.stderr

  ### Returns:

  error message if failed

  ### Or

  termios terminal attributes, if successful. On Windows the bitflags are all 0, and the `cc` table is empty.

  ### Or

  1. nil
  2. string error message
  3. int errnum

  ### Usage:

      local system = require('system')

      local status = assert(tcgetattr(io.stdin))
      if status.iflag:has_all_of(system.I_IGNBRK) then
          print("Ignoring break condition")
      end

tcsetattr (fd, actions, termios)
  Set termios state (Posix). This function will set the flags as given.

  The `I_`, `O_`, and `L_` constants are available on the module table. They are the respective flags for the `iflags`, `oflags`, and `lflags` bitmasks.

  To see flag status and constant names check listtermflags. For their meaning check the manpage.

  Note: only `iflag`, `oflag`, and `lflag` are supported at the moment. The other fields are ignored.

  ### Parameters:

  - fd file file handle to operate on, one of io.stdin, io.stdout, io.stderr
  - actions integer one of `TCSANOW`, `TCSADRAIN`, `TCSAFLUSH`
  - termios a table with bitflag fields:
    - iflag bitflags if given will set the input flags (optional)
    - oflag bitflags if given will set the output flags (optional)
    - lflag bitflags if given will set the local flags (optional)

  ### Returns:

  bool `true`, if successful. Always returns `true` on Windows.

  ### Or

  1. nil
  2. string error message
  3. int errnum

  ### Usage:

      local system = require('system')

      local status = assert(tcgetattr(io.stdin))
      if not status.lflag:has_all_of(system.L_ECHO) then
          -- if echo is off, turn echoing newlines on
          tcsetattr(io.stdin, system.TCSANOW, { lflag = status.lflag + system.L_ECHONL }))
      end

## Terminal_Input

_readkey ()
  Reads a key from the console non-blocking. This function should not be called directly, but through the system.readkey or system.readansi functions. It will return the next byte from the input stream, or `nil` if no key was pressed.

  On Posix, io.stdin must be set to non-blocking mode using setnonblock and canonical mode must be turned off using tcsetattr, before calling this function. Otherwise it will block. No conversions are done on Posix, so the byte read is returned as-is.

  On Windows this reads a wide character and converts it to UTF-8. Multi-byte sequences will be buffered internally and returned one byte at a time.

  ### Returns:

  integer the byte read from the input stream

  ### Or

  nil if no key was pressed

  ### Or

  1. nil on error
  2. string error message
  3. int errnum (on posix)
readansi (timeout[, fsleep=system.sleep])
  Reads a single key, if it is the start of ansi escape sequence then it reads the full sequence. The key can be a multi-byte string in case of multibyte UTF-8 character. This function uses system.readkey, and hence `fsleep` to wait until either a key is available or the timeout is reached. It returns immediately if a key is available or if `timeout` is less than or equal to `0`. In case of an ANSI sequence, it will return the full sequence as a string.

  ### Parameters:

  - timeout number the timeout in seconds.
  - fsleep function the function to call for sleeping. (default system.sleep)

  ### Returns:

  1. string the character that was received (can be multi-byte), or a complete ANSI sequence
  2. string the type of input: `"ctrl"` for 0-31 and 127 bytes, `"char"` for other UTF-8 characters, `"ansi"` for an ANSI sequence

  ### Or

  1. nil in case of an error
  2. string error message; `"timeout"` if the timeout was reached.
  3. string partial result in case of an error while reading a sequence, the sequence so far. The function retains its own internal buffer, so on the next call the incomplete buffer is used to complete the sequence.

  ### Usage:

      local key, keytype = system.readansi(5)
      if keytype == "char" then ... end -- printable character
      if keytype ~= "char" then ... end -- non-printable character or sequence
      if keytype == "ansi" then ... end -- a multi-byte sequence, but not a UTF8 character
      if keytype ~= "ansi" then ... end -- a valid UTF8 character (which includes control characters)
      if keytype == "ctrl" then ... end -- a single-byte ctrl character (0-31, 127)

readkey (timeout[, fsleep=system.sleep])
  Reads a single byte from the console, with a timeout. This function uses `fsleep` to wait until either a byte is available or the timeout is reached. The sleep period is exponentially backing off, starting at 0.0125 seconds, with a maximum of 0.1 seconds. It returns immediately if a byte is available or if `timeout` is less than or equal to `0`.

  Using system.readansi is preferred over this function. Since this function can leave stray/invalid byte-sequences in the input buffer, while system.readansi reads full ANSI and UTF8 sequences.

  ### Parameters:

  - timeout number the timeout in seconds.
  - fsleep function the function to call for sleeping; `ok, err = fsleep(secs)` (default system.sleep)

  ### Returns:

  byte the byte value that was read.

  ### Or

  1. nil if no key was read
  2. string error message when the timeout was reached (`"timeout"`), or if sleep failed.

## Terminal_UTF-8

CODEPAGE_UTF8
  UTF8 codepage. To be used with system.setconsoleoutputcp and system.setconsolecp.
  - CODEPAGE_UTF8 The Windows CodePage for UTF8.
getconsolecp ()
  Gets the current console code page (Windows).

  ### Returns:

  int the current code page (always 65001 on Posix systems)

  ### Or

  1. nil
  2. string error message
getconsoleoutputcp ()
  Gets the current console output code page (Windows).

  ### Returns:

  int the current code page (always 65001 on Posix systems)

  ### Or

  1. nil
  2. string error message
setconsolecp (cp)
  Sets the current console code page (Windows).

  ### Parameters:

  - cp int the code page to set, use system.CODEPAGE_UTF8 (65001) for UTF-8

  ### Returns:

  bool `true` on success (always `true` on Posix systems)

  ### Or

  1. nil
  2. string error message
setconsoleoutputcp (cp)
  Sets the current console output code page (Windows).

  ### Parameters:

  - cp int the code page to set, use system.CODEPAGE_UTF8 (65001) for UTF-8

  ### Returns:

  bool `true` on success (always `true` on Posix systems)

  ### Or

  1. nil
  2. string error message
utf8cwidth (utf8_char[, ambiguous_width=1])
  Get the width of a utf8 character for terminal display.

  ### Parameters:

  - utf8_char string or int the utf8 character, or unicode codepoint, to check, only the width of the first character will be returned
  - ambiguous_width int the width to return for ambiguous width characters (usually 1 or 2) (default 1)

  ### Returns:

  int the display width in columns of the first character in the string (0 for an empty string)

  ### Or

  1. nil
  2. string error message
utf8swidth (utf8_string[, ambiguous_width=1])
  Get the width of a utf8 string for terminal display.

  ### Parameters:

  - utf8_string string the utf8 string to check
  - ambiguous_width int the width to return for ambiguous width characters (1 or 2) (default 1)

  ### Returns:

  int the display width of the string in columns (0 for an empty string)

  ### Or

  1. nil
  2. string error message

## Time

gettime ()
  Get system time. The time is returned as the seconds since the epoch (1 January 1970 00:00:00).

  ### Returns:

  number seconds (fractional)
monotime ()
  Get monotonic time. The time is returned as the seconds since system start.

  ### Returns:

  number seconds (fractional)
sleep (seconds[, precision=16])
  Sleep without a busy loop. This function will sleep, without doing a busy-loop and wasting CPU cycles.

  ### Parameters:

  - seconds number seconds to sleep (fractional).
  - precision integer minimum stepsize in milliseconds (Windows only, ignored elsewhere) (default 16)

  ### Returns:

  `true` on success, or `nil+err` on failure

## Terminal_Backup

autotermrestore ()
  Backs up terminal settings and restores them on application exit. Calls termbackup to back up terminal settings and sets up a GC method to automatically restore them on application exit (also works on Lua 5.1).

  ### Returns:

  boolean true

  ### Or

  1. nil if the backup was already created
  2. string error message
termbackup ()
  Returns a backup of terminal settings for stdin/out/err. Handles terminal/console flags, Windows codepage, and non-block flags on the streams. Backs up terminal/console flags only if a stream is a tty.

  ### Returns:

  table with backup of terminal settings
termrestore (backup)
  Restores terminal settings from a backup

  ### Parameters:

  - backup table the backup of terminal settings, see termbackup.

  ### Returns:

  boolean true
termwrap (f)
  Wraps a function to automatically restore terminal settings upon returning. Calls termbackup before calling the function and termrestore after.

  ### Parameters:

  - f function function to wrap

  ### Returns:

  function wrapped function

generated by LDoc 1.5.0 Last updated 2026-04-26 10:36:21