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
CODEPAGE_UTF8 | UTF8 codepage. |
_readkey () | Reads a key from the console non-blocking. |
autotermrestore () | Backs up terminal settings and restores them on application exit. |
getconsolecp () | Gets the current console code page (Windows). |
getconsoleflags (file) | Gets console flags (Windows). |
getconsoleoutputcp () | Gets the current console output code page (Windows). |
getnonblock (fd) | Gets non-blocking mode status for a file (Posix). |
isatty (file) | Checks if a file-handle is a TTY. |
listconsoleflags (fh) | Debug function for console flags (Windows). |
listtermflags (fh) | Debug function for terminal flags (Posix). |
readansi (timeout) | Reads a single key, if it is the start of ansi escape sequence then it reads the full sequence. |
readkey (timeout) | Reads a single byte from the console, with a timeout. |
setconsolecp (cp) | Sets the current console code page (Windows). |
setconsoleflags (file, bitflags) | Sets the console flags (Windows). |
setconsoleoutputcp (cp) | Sets the current console output code page (Windows). |
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). |
termbackup () | Returns a backup of terminal settings for stdin/out/err. |
termrestore (backup) | Restores terminal settings from a backup |
termsize () | Get the size of the terminal in rows and columns. |
termwrap (f) | Wraps a function to automatically restore terminal settings upon returning. |
utf8cwidth (utf8_char) | Get the width of a utf8 character for terminal display. |
utf8swidth (utf8_string) | 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. |
Fields
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
CryptGenRandom()
on Windows, 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
- nil
- string error message
Terminal
Windows: see https://learn.microsoft.com/en-us/windows/console/console-reference
- CODEPAGE_UTF8
-
UTF8 codepage.
To be used with system.setconsoleoutputcp and system.setconsolecp.
- CODEPAGE_UTF8 The Windows CodePage for UTF8.
- _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
- nil on error
- string error message
- int errnum (on posix)
- 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
- nil if the backup was already created
- string error message
- getconsolecp ()
-
Gets the current console code page (Windows).
Returns:
-
int
the current code page (always 65001 on Posix systems)
- getconsoleflags (file)
-
Gets console flags (Windows).
The
CIF_
andCOF_
constants are available on the module table. WhereCIF
are the input flags (for use with io.stdin) andCOF
are the output flags (for use with io.stdout/io.stderr).Note: See setconsolemode documentation for more information on the flags.
Parameters:
Returns:
-
bitflags
the current console flags.
Or
- nil
- 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
- getconsoleoutputcp ()
-
Gets the current console output code page (Windows).
Returns:
-
int
the current code page (always 65001 on Posix systems)
- getnonblock (fd)
-
Gets non-blocking mode status for a file (Posix).
Parameters:
Returns:
-
bool
true
if set to non-blocking,false
if not. Always returnsfalse
on Windows.Or
- nil
- string error message
- int errnum
- isatty (file)
-
Checks if a file-handle is a TTY.
Parameters:
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
- listconsoleflags (fh)
-
Debug function for console flags (Windows).
Pretty prints the current flags set for the handle.
Parameters:
Usage:
-- Print the flags for stdin/out/err system.listconsoleflags(io.stdin) system.listconsoleflags(io.stdout) system.listconsoleflags(io.stderr)
- listtermflags (fh)
-
Debug function for terminal flags (Posix).
Pretty prints the current flags set for the handle.
Parameters:
Usage:
-- Print the flags for stdin/out/err system.listconsoleflags(io.stdin) system.listconsoleflags(io.stdout) system.listconsoleflags(io.stderr)
- readansi (timeout)
-
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 system.sleep 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 to0
. In case of an ANSI sequence, it will return the full sequence as a string.Parameters:
- timeout number the timeout in seconds.
Returns:
- string the character that was received (can be multi-byte), or a complete ANSI sequence
-
string
the type of input:
"char"
for a single key,"ansi"
for an ANSI sequence
Or
- readkey (timeout)
-
Reads a single byte from the console, with a timeout.
This function uses system.sleep 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.2 seconds.
It returns immediately if a byte is available or if
timeout
is less than or equal to0
.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.
Returns:
-
byte
the byte value that was read.
Or
- nil if no key was read
-
string
error message;
"timeout"
if the timeout was reached.
- 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 (alwaystrue
on Posix systems) - setconsoleflags (file, bitflags)
-
Sets the console flags (Windows).
The
CIF_
andCOF_
constants are available on the module table. WhereCIF
are the input flags (for use with io.stdin) andCOF
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 successOr
- nil
- 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
- 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 (alwaystrue
on Posix systems) - setnonblock (fd, make_non_block)
-
Enables or disables non-blocking mode for a file (Posix).
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 successfulOr
- nil
- string error message
- int errnum
See also:
Usage:
local sys = require('system') -- 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 flagsoflag
output flagslflag
local flagscflag
control flagsispeed
input speedospeed
output speedcc
control characters
Parameters:
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
- nil
- string error message
- 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_
, andL_
constants are available on the module table. They are the respective flags for theiflags
,oflags
, andlflags
bitmasks.To see flag status and constant names check listtermflags. For their meaning check the manpage.
Note: only
iflag
,oflag
, andlflag
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:
Returns:
-
bool
true
, if successful. Always returnstrue
on Windows.Or
- nil
- string error message
- 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
- 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
- termsize ()
-
Get the size of the terminal in rows and columns.
Returns:
- int the number of rows
- int the number of columns
Or
- nil
- string error message
- 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
- utf8cwidth (utf8_char)
-
Get the width of a utf8 character for terminal display.
Parameters:
- utf8_char string the utf8 character to check, only the width of the first character will be returned
Returns:
-
int
the display width in columns of the first character in the string (0 for an empty string)
Or
- nil
- string error message
- utf8swidth (utf8_string)
-
Get the width of a utf8 string for terminal display.
Parameters:
- utf8_string string the utf8 string to check
Returns:
-
int
the display width of the string in columns (0 for an empty string)
Or
- nil
- 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, ornil+err
on failure