Skip to content

darktjm/lua-glib

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

37 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Module glib

This package wraps the GLib library fairly thinly.

Unlike other lua-glib implementations, this is not meant to be a stepping stone for GTK+ support. It is meant to be a portability and utility library. There are other projects which provide support for GTK+ and other various derivatives of GLib.

Some features this library provides that other wrappers with similar scope don't are:

  • 132 functions, 10 variables, 6 custom datatypes (adding 103 more functions as type methods), all documented using LuaDoc. Having the GLib docs on hand helps, but is not strictly necessary. Documentation is organized into mostly the same sections as the GLib documentation.
  • Streaming support where glib has it (e.g. conversion, checksums). This means that rather than requiring all input at once, it can be fed in piece-wise. For example, see _convert_ .
  • Improved process spawn support, including redirection to/from lua “native” files and asynchronous lua readers and writers. See spawn and process .
  • Global functions for gettext support (e.g. _ ())

The specific version against which this was developed was 2.32.4; I have scanned the documentation for added symbols, and it should compile as far back as version 2.26 with a few minor missing features (search for “available with GLib” or “ignored with GLib”). The reason 2.26 was chosen is that it is the oldest version permitted with the GLIB_VERSION_MIN_REQUIRED macro, even though I could've gone as low as 2.18 without significant loss of functionality. I have also in the mean time added a few bits from versions up to 2.42.2, and updated compilability to 2.68.3.

The sections which are mostly supported are Version Information, Character Set Conversion (including streaming), Unicode Manipulation (skipping the low-level support functions and others which would really need low-level Lua Unicode support), Base64 Encoding (including streaming), Data Checksums (including streaming), Secure HMAC Digests (including streaming), Internationalization (including gettext macros, but excluding some of the low-level support functions), Miscellaneous Utility Functions (except for bit operations, which really need to be added to lua-bit, and a few other low-level/internal-use type functions), Timers, Spawning Processes (including some extra features), File Utilities (except a few MS library compatibility functions and memory mapped files), URI Functions, Hostname Utilities, Shell-related Utilities, Perl-compatible regular expressions, Simle XML Subset Parser (without vararg functions since building varargs generically is not possible), Key-value file parser, and Bookmark file parser.

The only Standard Macros supported are the OS and path separator macros. Date and Time Functions are mostly unsupported; the only one which could not be replaced by a native Lua time library is usleep, which is supported. The GTimeZone and GDateTime sections are not supported for the same reason.

No support is provided for Type Conversion Macros, Byte Order Macros, Numerical Definitions, or Miscellaneous Macros, as they are all either too low-level or C-specific. No support is provided for Atomic Operations, Threads, Thread Pools, or Asynchronous queues; use a Lua-specific threading module instead (such as Lanes). No support is provided for The Main Event Loop, as its utility versus implementation effort seems low. No support is provided for Dynamic Loading of Modules, because lua already does that. No support is provided for Memory Allocation or Memory Slices, since you shouldn't be doing that in Lua. IO Channels also seem below my minimum utility-to-effort ratio. There is no direct support for the Error Reporting, Message Output, and Debugging Functions. There is no support for replacing the log handlers or setting the fatality flags in log messages, although that may come some day. The String Utility Functions are C-specific, and not supported. The Hook Functions seem useless for Lua. The Lexical Scanner is not very configurable and hard to bind to Lua; use a made-for-Lua scanner instead like Lpeg. No support is provided for the Commandline option parser, as adapting it to Lua would remove most of its convenience and there are plenty of other similar libraries for lua. The Glob-style pattern matching is too simplistic and can easily be emulated using regex-style patterns (for example, see glob.lua, which should be packaged with this). The UNIX-specific and Windows-specific functions are not supported, since such blatantly non-portable functions should not be used. The Testing framework is not supported, because a Lua-specific framework would be more suited to the task. None of the GLib Data Types are supported, although there may be merit in eventually supporting the GVariant type somewhat.

Eventually, this may be split into multiple modules, so that uselses stuff can be removed. However, removing useless stuff from GLib is not easy, so having Lua bindings for what's there is not necessarily harmful.

This package was split off from my odin-lua project, so it uses an Odinfile to build (and in fact requires itself to be present for odin-lua to work, so it needs to be compiled by hand the first time anyway). It's just one C file, though, so it shouldn't be too hard to make a shared object out of it, linked to the glib and lua libraries. For example, on amd64 Linux (may need to change -fPIC on other architectures):

gcc -O2 -fPIC `pkg-config glib-2.0 --cflags --libs` -llua -shared -o glib.so lua-glib.c

Or you could use Lake:

lake NEEDS=gtk -lua lua-glib.c

This documentation was built as follows (again, this is in the Odinfile):

ldoc.lua -p lua-glib -o lua-glib -d . -f discount -t 'Lua GLib Library' lua-glib.c

Using ldoc-1.2.0, with a patch to escape underscores in in-line references:

--- ldoc/markup.lua
+++ ldoc/markup.lua
@@ -42,6 +42,9 @@
    if backtick_references then
       res  = res:gsub('`([^`]+)`',function(name)
          local ref,err = markup.process_reference(name)
+         if not plain and ref then -- a nastiness with markdown.lua and underscores
+            name = name:gsub('_','\\_')
+         end
          if ref then
             return ('<a href="%s">%s</a> '):format(ldoc.href(ref),name)
          else

And lua-discount, changed to use the system discount library:

rm -f *.h
make DISCOUNT_OBJS= LIBS=-lmarkdown

The discount version I used was 2.1.5a, with everything enabled, and compiled with -fPIC to enable linking with shared libraries.

Note that since LDoc does not support error return sections, I have used exception sections (@raise) instead.

For Bitbucket, I have converted this documentation to rst using pandoc and a bit of filtering. See the Lua filtering code in Odinfile; this almost certainly needs Odin for best results. I chose rst because markdown doesn't do tables (at least not in a way that's compatible with anything pandoc can produce). Originally, I used textile because github appears to display markup as ASCII if it takes too long to process, and only textile seemed to be fast enough. However, textile output is broken on bitbucket and it seemed easier to just use the rst output I had already tweaked.

Questions/comments to darktjm@gmail.com.

version GLib version string.
os Operating system.
dir_separator Directory separator.
searchpath_separator Path list separator
log ([domain][, level], msg) Log a message, GLib-style.
_convert_ ([str]) Stream character conversion function returned by convert .
convert ([str[, to[, from[, fallback]]]]) Convert strings from one character set to another.
validate (c) Check if unicode character is valid.
isalpha (c) Check if Unicode character is alphabetic.
iscntrl (c) Check if Unicode character is a control character.
isdefined (c) Check if Unicode character is explicitly defined in the Unicode standard.
isdigit (c) Check if Unicode character is a decimal digit.
isgraph (c) Check if Unicode character is a visible, printable character.
islower (c) Check if Unicode character is a lower-case alphabetic character.
ismark (c) Check if Unicode character is a mark.
isprint (c) Check if Unicode character is printable.
ispunct (c) Check if Unicode character is a punctuation or symbol character.
isspace (c) Check if Unicode character is whitespace.
istitle (c) Check if Unicode character is titlecase.
isupper (c) Check if Unicode character is upper-case.
isxdigit (c) Check if Unicode character is hexadecimal digit.
iswide (c) Check if Unicode character is wide.
iswide_cjk (c) Check if Unicode character is wide in legacy East Asian locales.
iszerowidth (c) Check if Unicode character is zero-width.
toupper (c) Convert Unicode character to upper-case.
tolower (c) Convert Unicode character to lower-case.
totitle (c) Convert Unicode character to title case.
digit_value (c) Convert digit to its numeric value.
xdigit_value (c) Convert hexadecimal digit to its numeric value.
type (c) Find Unicode character class.
break_type (c) Find Unicode character's line break classification.
get_mirror_char (c) Find Unicode mirroring character.
get_script (c) Find ISO 15924 script for a Unicode character.
utf8_sub (s[, first[, last]]) Obtain a substring of a utf-8-encoded string.
utf8_len (s) Obtain the number of code points in a utf-8-encoded string.
utf8_validate (s) Check if a string is valid UTF-8.
utf8_strup (s) Convert UTF-8 string to upper-case.
utf8_strdown (s) Convert UTF-8 string to lower-case.
utf8_casefold (s) Convert UTF-8 string to case-independent form.
utf8_normalize (s[, compose[, compatible]]) Perform standard Unicode normalization on a UTF-8 string.
utf8_collate (s1, s2) Compare UTF-8 strings for collation.
utf8_collate_key (s) Create a comparison key for a UTF-8 string.
utf8_collate_key_for_filename (s) Create a comparison key for a UTF-8 filename string.
utf8_to_utf16 (s) Convert a UTF-8 string to UTF-16.
utf8_to_ucs4 (s) Convert a UTF-8 string to UCS-4.
utf16_to_utf8 (s) Convert a UTF-16 string to UTF-8.
utf16_to_ucs4 (s) Convert a UTF-16 string to UCS-4.
ucs4_to_utf16 (s) Convert a UCS-4 string to UTF-16.
ucs4_to_utf8 (s) Convert a UCS-4 string to UTF-8.
to_utf8 (c) Convert a UCS-4 code point to UTF-8.
_base64_encode_ ([s]) Stream Base64-encoding function returned by base64_encode .
base64_encode ([s]) Base64-encode a string.
_base64_decode_ ([s]) Stream Base64-decoding function returned by base64_decode .
base64_decode ([s]) Base64-decode a string.
_sum_ ([s][, raw]) Stream checksum/hash calculation function type.
md5sum ([s[, raw]]) Compute MD5 checksum of a string.
sha1sum ([s[, raw]]) Compute SHA1 checksum of a string.
sha256sum ([s[, raw]]) Compute SHA256 checksum of a string.
_hmac_ ([s][, raw]) Stream HMAC calculation function.
md5hmac (key[, s[, raw]]) Compute secure HMAC digest using MD5.
sha1hmac (key[, s[, raw]]) Compute secure HMAC digest using SHA1.
sha256hmac (key[, s[, raw]]) Compute secure HMAC digest using SHA256.
textdomain ([domain[, path[, encoding]]]) Set or query text message database location.
_ (s) Replace text with its translation.
Q_ (s) Replace text and context with its translation.
C_ (c, s) Replace text and context with its translation.
N_ (s) Mark text for translation.
NC_ (c, s) Mark text for translation with context.
ngettext (singular, plural, n) Replace text with its number-appropriate translation.
get_locale_variants ([locale]) Obtain list of valid locale names.
sleep (t) Suspend execution for some seconds.
usleep (t) Suspend execution for some microseconds.
random ([low[, high]]) Obtain a psuedorandom number.
rand_new ([seed]) Obtain a psuedorandom number generator, given a seed.
application_name ([name]) Set or get localized application name.
prgname ([name]) Set or get program name.
getenv (name) Get environment variable value.
setenv (name, value[, replace]) Set environment variable value.
unsetenv (name) Remove environment variable.
listenv () Obtain names of all environment variables.
get_user_name () Obtain system user name for current user.
get_real_name () Obtain full user name for current user.
get_dir_name (d) Obtain a standard directory name.
get_host_name () Obtain current host name.
get_current_dir () Obtain current working directory.
path_is_absolute (d) Check if a directory is absolute.
path_split_root (d) Split the root part from a path.
path_get_basename (d) Obtain the last element of a path.
path_get_dirname (d) Obtain all but the last element of a path.
build_filename (...) Construct a file name from its path constituents.
build_path (sep, ...) Construct a path from its constituents.
path_canonicalize (f) Canonicalize a path name.
qsort (t[, cmp]) Sort a table using a stable quicksort algorithm.
cmp (a, b) Compare two objects.
timer_new () Create a stopwatch-like timer.

Class timer

timer:start () Start or reset the timer.
timer:stop () Stop the timer if it is running.
timer:continue () Resume the timer if it is stopped.
timer:elapsed () Return the amount of time counted so far.
spawn (args) Run a command asynchronously.

Class process

process:read_ready (...) Check if input is available from process standard output.
process:read_err_ready (...) Check if input is available from process standard error.
process:read (...) Read data from a process' standard output.
process:read_err (...) Read data from a process' standard error.
process:lines () Return an iterator which reads lines from the process' standard output.
process:lines_err () Return an iterator which reads lines from the process' standard error.
process:write_ready () Check if writing to the process' standard input will block.
process:write (...) Write to a process' standard input.
process:close () Close the process' standard input channel.
process:io_wait ([check_in[, check_out[, check_err]]]) Check for process activity.
process:pid () Return the glib process ID for the process.
process:status () Return the status of the running process.
process:check_exit_status () Check if the process return code was an error.
process:wait () Wait for process termination and clean up.
file_get (name) Return contents of a file as a string.
file_set (name, contents) Set contents of a file to a string.
is_file (name) Test if the given path points to a file.
is_dir (name) Test if the given path points to a directory.
is_symlink (name) Test if the given path points to a symbolic link.
is_exec (name) Test if the given path points to an executable file.
exists (name) Test if the given path points to a file or directory.
umask ([mask]) Change default file and directory creation permissions mask.
mkstemp (tmpl[, perm]) Create a unique temporary file from a pattern.
open_tmp ([tmpl]) Create a unique temporary file in the standard temporary directory.
read_link (name) Read the contents of a soft link.
mkdir_with_parents (name[, mode]) Create a directory and any required parent directories.
mkdtemp (tmpl[, mode]) Create a unique tempoarary directory from a pattern.
dir_make_tmp ([tmpl]) Create a unique temporary directory in the standard temporary directory.
dir (d) Returns an iterator which lists entries in a directory.
rename (old, new) Rename a file sytem entity.
mkdir (name[, mode]) Create a directory.
stat (name[, fields]) Retrieve information on a file system entry.
remove (name) Remove a file sytem entity.
chmod (name, perm) Change filesystem entry permissions.
can_read (name) Test if fileystem object can be read.
can_write (name) Test if fileystem object can be written to.
chdir (dir) Change current working directory.
utime (name[, atime[, mtime]]) Change timestamp on filesystem object.
link (target, name[, soft]) Create a link.
uri_reserved_chars_allowed_in_path Allowed characters in a path.
uri_reserved_chars_allowed_in_path_element Allowed characters in path elements.
uri_reserved_chars_allowed_in_userinfo Allowed characters in userinfo (RFC 3986).
uri_reserved_chars_generic_delimiters Generic delimiter characters (RFC 3986).
uri_reserved_chars_subcomponent_delimiters Subcomponent delimiter characters (RFC 3986).
uri_parse_scheme (uri) Extract scheme from URI.
uri_escape_string (s[, allow[, utf8]]) Escapes a string for use in a URI.
uri_unescape_string (s[, illegal]) Unescapes an escaped string.
uri_list_extract_uris (list) Splits an URI list conforming to the text/uri-list MIME type (RFC 2483).
filename_from_uri (uri) Converts an ASCII-encoded URI to a local filename.
filename_to_uri (file[, host]) Converts an absolute filename to an escaped ASCII-encoded URI.
hostname_to_ascii (hostname) Convert a host name to its canonical ASCII form.
hostname_to_unicode (hostname) Convert a host name to its canonical Unicode form.
hostname_is_non_ascii (hostname) Check if a host name contains Unicode characters.
hostname_is_ascii_encoded (hostname) Check if a host name contains ASCII-encoded Unicode characters.
hostname_is_ip_address (hostname) Check if a string is an IPv4 or IPv6 numeric address.
shell_parse_argv (cmdline) Parse a command line into an argument vector, but without variable and glob pattern expansion.
shell_quote (s) Quote a string so it is interpreted unmodified as a shell argument.
shell_unquote (s) Unquote a string quoted for use as a shell argument.
regex_new (pattern[, cflags[, mflags]]) Compile a regular expression for use in matching functions.
regex_escape_string (s) Escapes a string so it is a literal in a regular expression.

Class regex

regex:get_pattern () Get the pattern string used to create this regex.
regex:get_max_backref () Get the highest back reference in the pattern.
regex:get_has_cr_or_lf () Check if pattern contains explicit CR or LF references.
regex:get_max_lookbehind () Get the number of characters in the longest lookbehind assertion in the pattern.
regex:get_capture_count () Get the number of capturing subpatterns in the pattern.
regex:get_string_number (name) Get the number of the capturing subexpression with the given name.
regex:get_compile_flags () Get the names of all compile flags set when regex was created.
regex:get_match_flags () Get the names of all matching flags set when regex was created.
regex:find (s[, start[, mflags]]) Search for a match in a string.
regex:tfind (s[, start[, mflags]]) Search for a match in a string.
regex:match (s[, start[, mflags]]) Search for a match in a string.
regex:gmatch (s[, start[, mflags]]) Search for all matches in a string.
regex:gfind (s[, start[, mflags]]) Search for all matches in a string.
regex:gtfind (s[, start[, mflags]]) Search for all matches in a string.
regex:split (s[, start[, mflags[, max]]]) Split a string with a regular expression separator.
regex:gsub (s, repl[, start[, n[, mflags]]]) Replace occurrences of regular expression in string.
markup_escape_text (s) Escape text so GMarkup XML parsing will return it to original.
_gmarkup_start_element_ (ctx, name, attr_names, attr_values) The function called when an opening tag of an element is seen.
_gmarkup_end_element_ (ctx, name[, pop]) The function called when an ending tag of an element is seen.
_gmarkup_text_ (ctx, text) The function called when text within an element is seen.
_gmarkup_passthrough_ (ctx, text) The function called when unprocessed text is seen.
_gmarkup_error_ (ctx, text) The function called when an error occurs during parsing.
markup_parse_context_new (options) Create GMarkup parser.
markup_parse_context:end_parse () Finish parsing.
markup_parse_context:get_position () Obtain current position in source text.
markup_parse_context:get_element () Obtain the name of the current element being processed.
markup_parse_context:get_element_stack () Obtain the complete path of element names to the current element being processed.
markup_parse_context:parse (s) Parse some text.
key_file_new () Create a new, empty key file.

Class key_file

key_file:set_list_separator (sep) Sets character to separate values in lists.
key_file:load_from_file (f[, dirs[, keep_com[, keep_trans]]]) Load a file.
key_file:load_from_data (s[, keep_com[, keep_trans]]) Load data.
key_file:to_data () Convert entire key file to a string.
key_file:save_to_file (name) Writes out contents of key file.
key_file:get_start_group () Get the start group of the key file.
key_file:get_groups () Get the names of all groups in the key file.
key_file:get_keys (group) Get the names of all keys in a group.
key_file:has_group (group) Check if group exists.
key_file:has_key (group, key) Check if key exists.
key_file:raw_get (group, key) Obtain raw value of a key.
key_file:get (group, key[, locale]) Obtain value of a key.
key_file:get_boolean (group, key) Obtain value of a boolean key.
key_file:get_number (group, key) Obtain value of a numeric key.
key_file:get_list (group, key[, locale]) Obtain value of a string list key.
key_file:get_boolean_list (group, key) Obtain value of a boolean list key.
key_file:get_number_list (group, key) Obtain value of a number list key.
key_file:get_comment ([group[, key]]) Obtain comment above a key or group.
key_file:raw_set (group, key, value) Set raw value of a key.
key_file:set (group, key, value[, locale]) Set value of a key.
key_file:set_boolean (group, key, value) Set value of a boolean key.
key_file:set_number (group, key, value) Set value of a numeric key.
key_file:set_list (group, key, value[, locale]) Set value of a string list key.
key_file:set_boolean_list (group, key, value) Set value of a boolean list key.
key_file:set_number_list (group, key) Set value of a number list key.
key_file:set_comment (comment[, group[, key]]) Set comment above a key or group.
key_file:remove (group[, key]) Remove a group or key.
key_file:remove_comment ([group[, key]]) Remove comment above a key or group.
bookmark_file_new () Create a new, empty bookmark file.
bookmark_file:load_from_file (f[, use_dirs]) Load a file.
bookmark_file:load_from_data (s) Load data.
bookmark_file:to_data () Convert bookmark file to a string.
bookmark_file:to_file (f) Write bookmark file to a file.
bookmark_file:has_item (uri) Check if bookmark file has given URI.
bookmark_file:has_group (uri, group) Check if bookmark file has given URI in a given group.
bookmark_file:has_application (uri, app) Check if bookmark file has given URI registered by a given application.
bookmark_file:__len () Get the number of bookmarks.
bookmark_file:uris () Get all URIs.
bookmark_file:title (uri) Get title for URI
bookmark_file:description (uri) Get description for URI
bookmark_file:mime_type (uri) Get MIME type for URI
bookmark_file:is_private (uri) Get private flag for URI
bookmark_file:icon (uri) Get icon for URI.
bookmark_file:added (uri) Get time URI was added.
bookmark_file:modified (uri) Get time URI was last modified.
bookmark_file:visited (uri) Get time URI was last visited.
bookmark_file:groups (uri) Get list of groups to which URI belongs.
bookmark_file:applications (uri) Get list of applications which registered this URI.
bookmark_file:boomark_file:app_info (uri, app) Obtain registration information for application which registered URI.
bookmark_file:set_title ([uri], title) Set title for URI
bookmark_file:set_description ([uri], desc) Set description for URI
bookmark_file:set_mime_type (uri, mime_type) Set MIME type for URI
bookmark_file:set_is_private (uri, private) Set private flag for URI
bookmark_file:set_icon (uri, icon, mime_type) Set icon for URI.
bookmark_file:set_added (uri, time) Set time URI was added.
bookmark_file:set_modified (uri, time) Set time URI was modified.
bookmark_file:set_visited (uri, time) Set time URI was visited.
bookmark_file:set_groups (uri) Set list of groups to which URI belongs.
bookmark_file:set_app_info (uri, app, exec[, rcount[, stamp]]) Set registration information for application which registered URI.
bookmark_file:add_group (uri, group) Add a group to the list of groups URI belongs to.
bookmark_file:add_application (uri, app, exec) Add an application to the list of applications that registered this URI.
bookmark_file:remove_group (uri, group) Remove a group from the list of groups URI belongs to.
bookmark_file:remove_application (uri, app) Remove an application from the list of applications that registered this URI.
bookmark_file:remove (uri) Remove URI.
bookmark_file:move (uri, new) Change URI, retaining group and application information.

Version Information

version

GLib version string. Version of running glib (not the one it was compiled against). The format is major.minor.micro.

Usage:

gver = tonumber(glib.version:match '(.*)%.')
print(gver > 2.30)

Standard Macros

os
Operating system. A string representing the operating system: ‘win32', ‘beos', ‘unix', ‘unknown'
dir_separator
Directory separator. Unlike GLib's directory separator, this includes both valid values under Win32.
searchpath_separator
Path list separator

Message Logging

log ([domain][, level], msg)

Log a message, GLib-style. This is a wrapper for g_log().

Parameters:

  • domain: string The log domain. This parameter may be absent to use G_LOG_DOMAIN.

  • level: string The log level. Acceptable values are:

    • ‘crit'/‘critical'
    • ‘debug'
    • ‘err'/‘error'
    • ‘info'
    • ‘msg'/‘message'
    • ‘warn'/‘warning'

    This parameter may be absent along with domain to indicate ‘msg'.

  • msg: string The log message. Unlike g_log(), no formatting is permitted. Collect and format your string before logging.

Character Set Conversion

_convert_ ([str])

Stream character conversion function returned by convert . This function is returned by convert to support converting streams piecewise. Simply call with string arguments, accumulating the returned strings. When finished with the stream, call with no arguments. This will return the final string to append and reset the stream for reuse.

Parameters:

  • str: string The next piece of the string to convert; absent to finish conversion

Usage:

c = glib.convert(nil, 'utf-8', 'latin1')
while true do
  buf = inf:read(4096)
  if not buf then break end
  outf:write(c(buf))
end
outf:write(c())

Returns:

string The next piece of the converted string

see also:

convert

convert ([str[, to[, from[, fallback]]]])

Convert strings from one character set to another. This is a wrapper for g_convert() and friends. To convert a stream, pass in no arguments or nil for str. The return value is either the converted string, or a function matching the _convert_ function.

Parameters:

  • str: string The string to convert, or nil/absent to produce a streaming converter
  • to: string The target character set. This may be nil or absent to indicate the current locale. This may be ‘filename' to indicate the filename character set.
  • from: string The target character set. This may be nil or absent to indicate the current locale. This may be ‘filename' to indicate the filename character set.
  • fallback: string Any characters in from which have no equivalent in to are converted to this string. This is not supported in stream mode.

Returns:

  1. string Converted string, if str was specified
  2. function stream convert function, if str was nil or missing

Raises:

Returns nil and error message string on error.

see also:

_convert_

Unicode Manipulation

validate (c)

Check if unicode character is valid. This is a wrapper for g_unichar_validate().

Parameters:

  • c: string |number The Unicode character, as either an integer or a utf-8 string.

Returns:

boolean True if c is valid

Raises:

Generates argument error if c is a string but not valid UTF-8.

isalpha (c)

Check if Unicode character is alphabetic. This is a wrapper for g_unichar_isalpha().

Parameters:

  • c: string |number The Unicode character, as either an integer or a utf-8 string.

Returns:

boolean True if c is alphabetic

Raises:

Generates argument error if c is a string but not valid UTF-8.

iscntrl (c)

Check if Unicode character is a control character. This is a wrapper for g_unichar_iscntrl().

Parameters:

  • c: string |number The Unicode character, as either an integer or a utf-8 string.

Returns:

boolean True if c is a control character

Raises:

Generates argument error if c is a string but not valid UTF-8.

isdefined (c)

Check if Unicode character is explicitly defined in the Unicode standard. This is a wrapper for g_unichar_isdefined().

Parameters:

  • c: string |number The Unicode character, as either an integer or a utf-8 string.

Returns:

boolean True if c is defined

Raises:

Generates argument error if c is a string but not valid UTF-8.

isdigit (c)

Check if Unicode character is a decimal digit. This is a wrapper for g_unichar_isdigit().

Parameters:

  • c: string |number The Unicode character, as either an integer or a utf-8 string.

Returns:

boolean True if c is a digit-like character

Raises:

Generates argument error if c is a string but not valid UTF-8.

see also:

isgraph (c)

Check if Unicode character is a visible, printable character. This is a wrapper for g_unichar_isgraph().

Parameters:

  • c: string |number The Unicode character, as either an integer or a utf-8 string.

Returns:

boolean True if c is a graphic character

Raises:

Generates argument error if c is a string but not valid UTF-8.

islower (c)

Check if Unicode character is a lower-case alphabetic character. This is a wrapper for g_unichar_islower().

Parameters:

  • c: string |number The Unicode character, as either an integer or a utf-8 string.

Returns:

boolean True if c is lower-case.

Raises:

Generates argument error if c is a string but not valid UTF-8.

ismark (c)

Check if Unicode character is a mark. This is a wrapper for g_unichar_ismark().

Parameters:

  • c: string |number The Unicode character, as either an integer or a utf-8 string.

Returns:

boolean True if c is a non-spacing mark, combining mark, or enclosing mark

Raises:

Generates argument error if c is a string but not valid UTF-8.

isprint (c)

Check if Unicode character is printable. This is a wrapper for g_unichar_isprint().

Parameters:

  • c: string |number The Unicode character, as either an integer or a utf-8 string.

Returns:

boolean True if c is printable, even if blank

Raises:

Generates argument error if c is a string but not valid UTF-8.

ispunct (c)

Check if Unicode character is a punctuation or symbol character. This is a wrapper for g_unichar_ispunct().

Parameters:

  • c: string |number The Unicode character, as either an integer or a utf-8 string.

Returns:

boolean True if c is a punctuation or symbol character

Raises:

Generates argument error if c is a string but not valid UTF-8.

isspace (c)

Check if Unicode character is whitespace. This is a wrapper for g_unichar_isspace().

Parameters:

  • c: string |number The Unicode character, as either an integer or a utf-8 string.

Returns:

boolean True if c is whitespace

Raises:

Generates argument error if c is a string but not valid UTF-8.

istitle (c)

Check if Unicode character is titlecase. This is a wrapper for g_unichar_istitle().

Parameters:

  • c: string |number The Unicode character, as either an integer or a utf-8 string.

Returns:

boolean True if c is titlecase alphabetic

Raises:

Generates argument error if c is a string but not valid UTF-8.

isupper (c)

Check if Unicode character is upper-case. This is a wrapper for g_unichar_isupper().

Parameters:

  • c: string |number The Unicode character, as either an integer or a utf-8 string.

Returns:

boolean True if c is upper-case alphabetic

Raises:

Generates argument error if c is a string but not valid UTF-8.

isxdigit (c)

Check if Unicode character is hexadecimal digit. This is a wrapper for g_unichar_isxdigit().

Parameters:

  • c: string |number The Unicode character, as either an integer or a utf-8 string.

Returns:

boolean True if c is a hexadecimal digit

Raises:

Generates argument error if c is a string but not valid UTF-8.

see also:

iswide (c)

Check if Unicode character is wide. This is a wrapper for g_unichar_iswide().

Parameters:

  • c: string |number The Unicode character, as either an integer or a utf-8 string.

Returns:

boolean True if c is double-width

Raises:

Generates argument error if c is a string but not valid UTF-8.

iswide_cjk (c)

Check if Unicode character is wide in legacy East Asian locales. This is a wrapper for g_unichar_iswide_cjk().

Parameters:

  • c: string |number The Unicode character, as either an integer or a utf-8 string.

Returns:

boolean True if c is double-width normally or in legacy East-Asian locales

Raises:

Generates argument error if c is a string but not valid UTF-8.

iszerowidth (c)

Check if Unicode character is zero-width. This is a wrapper for g_unichar_iszerowidth().

Parameters:

  • c: string |number The Unicode character, as either an integer or a utf-8 string.

Returns:

boolean True if c is a zero-width combining character

Raises:

Generates argument error if c is a string but not valid UTF-8.

toupper (c)

Convert Unicode character to upper-case. This is a wrapper for g_unichar_toupper().

Parameters:

  • c: string |number The Unicode character, as either an integer or a utf-8 string.

Returns:

string |number The result of conversion, as either an integer or a utf-8 string, depending on what c was.

Raises:

Generates argument error if c is a string but not valid UTF-8.

tolower (c)

Convert Unicode character to lower-case. This is a wrapper for g_unichar_tolower().

Parameters:

  • c: string |number The Unicode character, as either an integer or a utf-8 string.

Returns:

string |number The result of conversion, as either an integer or a utf-8 string, depending on what c was.

Raises:

Generates argument error if c is a string but not valid UTF-8.

totitle (c)

Convert Unicode character to title case. This is a wrapper for g_unichar_totitle().

Parameters:

  • c: string |number The Unicode character, as either an integer or a utf-8 string.

Returns:

string |number The result of conversion, as either an integer or a utf-8 string, depending on what c was.

Raises:

Generates argument error if c is a string but not valid UTF-8.

digit_value (c)

Convert digit to its numeric value. This is a wrapper for g_unichar_digit_value().

Parameters:

  • c: string |number The Unicode character, as either an integer or a utf-8 string.

Returns:

number The digit's numeric value

Raises:

Generates argument error if c is a string but not valid UTF-8. Returns -1 if c is not a digit.

see also:

isdigit

xdigit_value (c)

Convert hexadecimal digit to its numeric value. This is a wrapper for g_unichar_xdigit_value().

Parameters:

  • c: string |number The Unicode character, as either an integer or a utf-8 string.

Returns:

number The hex digit's numeric value

Raises:

Generates argument error if c is a string but not valid UTF-8. Returns -1 if c is not a hex digit.

see also:

isxdigit

type (c)

Find Unicode character class. This is a wrapper for g_unichar_type().

Parameters:

  • c: string |number The Unicode character, as either an integer or a utf-8 string.

Returns:

string The character's class; one of: control, format, unassigned, private_use, surrogate, lowercase_letter, modifier_letter, other_letter, titlecase_letter, uppercase_letter, spacing_mark, enclosing_mark, non_spacing_mark, decimal_number, letter_number, other_number, connect_punctuation, dash_punctuation, close_punctuation, final_punctuation, initial_punctuation, other_punctuation, open_punctuation, currency_symbol, modifier_symbol, math_symbol, other_symbol, line_separator, paragraph_separator, space_separator.

Raises:

Generates argument error if c is a string but not valid UTF-8.

break_type (c)

Find Unicode character's line break classification. This is a wrapper for g_unichar_break_type().

Parameters:

  • c: string |number The Unicode character, as either an integer or a utf-8 string.

Returns:

string The line break classification; one of: mandatory, carriage_return, line_feed, combining_mark, surrogate, zero_width_space, inseperable, non_breaking_glue, contingent, space, after, before, before_and_after, hyphen, non_starter, open_punctuation, close_punctuation, quotation, exclamation, ideographic, numeric, infix_separator, symbol, alphabetic, prefix, postfix, complex_context, ambiguous, unknown, next_line, word_joiner, hangul_l_jamo, hangul_v_jamo, hangul_t_jamo, hangul_lv_syllable, hangul_lvt_syllable, close_parenthesis, conditional_japanese_starter, hebrew_letter.

Raises:

Generates argument error if c is a string but not valid UTF-8.

get_mirror_char (c)

Find Unicode mirroring character. This is a wrapper for g_unichar_get_mirror_char().

Parameters:

  • c: string |number The Unicode character, as either an integer or a utf-8 string.

Returns:

string |number |nil nil if the character has no mirror; otherwise, the mirror character. The returned character is either an integer or a utf-8 string, depending on the input.

Raises:

Generates argument error if c is a string but not valid UTF-8.

get_script (c)

Find ISO 15924 script for a Unicode character. This is a wrapper for g_unichar_get_script().

This is only available with GLib 2.30 or later.

Parameters:

  • c: string |number The Unicode character, as either an integer or a utf-8 string.

Returns:

string The four-letter ISO 15924 script code for c.

Raises:

Generates argument error if c is a string but not valid UTF-8.

utf8_sub (s[, first[, last]])

Obtain a substring of a utf-8-encoded string. This is not a wrapper for g_utf8_substring(), but instead code which emulates string.sub using g_utf8_offset_to_pointer() and g_utf8_strlen(). Positive positions start at the beginining of the string, and negative positions start at the end. Position numbers refer to code points rather than byte offsets.

Parameters:

  • s: string The utf-8-encoded source string
  • first: number The first Unicode code point (default is 1)
  • last: number The last Unicode code point (default is -1)

Returns:

string The requested substring. Out-of-bound ranges result in an empty string.

utf8_len (s)

Obtain the number of code points in a utf-8-encoded string. This is a wrapper for g_utf8_strlen().

Parameters:

Returns:

number The length of s, in code points.

utf8_validate (s)

Check if a string is valid UTF-8. This is a wrapper for g_utf8_validate().

Parameters:

Returns:

boolean True if s is valid UTF-8.

utf8_strup (s)

Convert UTF-8 string to upper-case. This is a wrapper for g_utf8_strup().

Parameters:

Returns:

string s, with all lower-case characters converted to upper-case

utf8_strdown (s)

Convert UTF-8 string to lower-case. This is a wrapper for g_utf8_strdown().

Parameters:

Returns:

string s, with all upper-case characters converted to lower-case

utf8_casefold (s)

Convert UTF-8 string to case-independent form. This is a wrapper for g_utf8_casefold().

Parameters:

Returns:

string s, in a form that is suitable for case-insensitive direct string comparison.

utf8_normalize (s[, compose[, compatible]])

Perform standard Unicode normalization on a UTF-8 string. This is a wrapper for g_utf8_normalize(). The four standard normalizations are NFD (the default), NFC (compose), NFKD (compatible), and NFKC (compose, compatible).

Parameters:

  • s: string The string to normalize
  • compose: boolean If true, perform canonical composition. Otherwise, leave in decomposed form.
  • compatible: boolean If true, decompose using compatibility decompostions. Otherwise, only decompose using canonical decompositions.

Returns:

string The normalized UTF-8 string.

utf8_collate (s1, s2)

Compare UTF-8 strings for collation. This is a wrapper for g_utf8_collate().

Parameters:

Returns:

number Numeric comparison result: less than zero if s1 comes before s2, greater than zero if s1 comes after s2, and zero if s1 and s2 are equivalent.

see also:

utf8_collate_key (s)

Create a comparison key for a UTF-8 string. This is a wrapper for g_utf8_collate_key().

Parameters:

Returns:

string A form of the string which can be compared using direct string comparison rather than utf8_collate.

see also:

utf8_collate_key_for_filename (s)

Create a comparison key for a UTF-8 filename string. This is a wrapper for g_collate_key_for_filename().

Parameters:

Returns:

string A form of the string which can be compared using direct string comparison. Dots and numeric sequences are treated differently. There is no equivalent utf8_collate_filename().

see also:

utf8_to_utf16 (s)

Convert a UTF-8 string to UTF-16. This is a wrapper for g_utf8_to_utf16().

Parameters:

Returns:

string s, converted to UTF-16

Raises:

Returns nil followed by an error message if s is not valid UTF-8.

utf8_to_ucs4 (s)

Convert a UTF-8 string to UCS-4. This is a wrapper for g_utf8_to_ucs4().

Parameters:

Returns:

string s, converted to UCS-4

Raises:

Returns nil followed by an error message if s is not valid UTF-8.

utf16_to_utf8 (s)

Convert a UTF-16 string to UTF-8. This is a wrapper for g_utf16_to_utf8().

Parameters:

Returns:

string s, converted to UTF-8

Raises:

Returns nil followed by an error message if s is not valid UTF-16.

utf16_to_ucs4 (s)

Convert a UTF-16 string to UCS-4. This is a wrapper for g_utf16_to_ucs4().

Parameters:

Returns:

string s, converted to UCS-4

Raises:

Returns nil followed by an error message if s is not valid UTF-16.

ucs4_to_utf16 (s)

Convert a UCS-4 string to UTF-16. This is a wrapper for g_utf8_to_utf16().

Parameters:

Returns:

string s, converted to UTF-16

Raises:

Returns nil followed by an error message if s is not valid UCS-4.

ucs4_to_utf8 (s)

Convert a UCS-4 string to UTF-8. This is a wrapper for g_utf16_to_utf8().

Parameters:

Returns:

string s, converted to UTF-8

Raises:

Returns nil followed by an error message if s is not valid UCS-4.

to_utf8 (c)

Convert a UCS-4 code point to UTF-8. This is a wrapper for g_unichar_to_utf8().

Parameters:

  • c: string |number The Unicode character, as either an integer or a utf-8 string.

Returns:

string A UTF-8 string representing c. Note that this basically has no effect if c is a single-character string already.

Raises:

Generates argument error if c is a string but not valid UTF-8.

Base64 Encoding

_base64_encode_ ([s])

Stream Base64-encoding function returned by base64_encode . This function is returned by base64_encode to support piecewise-encoding streams. Simply call with string arguments, accumulating the returned strings. When finished with the stream, call with no arguments. This will return the final string to append and reset the stream for reuse.

Parameters:

  • s: string The next piece of the string to convert; absent to finish conversion

Usage:

enc = glib.base64_encode()
while true do
  buf = inf:read(4096)
  if not buf then break end
  outf:write(enc(buf))
end
outf:write(enc())

Returns:

string The next piece of the converted string

see also:

base64_encode

base64_encode ([s])

Base64-encode a string. This is a wrapper for g_base64_encode() and friends.

Parameters:

Returns:

string |function The base64-encoded stream (without newlines), or a function to do the same on a stream.

see also:

_base64_encode_

_base64_decode_ ([s])

Stream Base64-decoding function returned by base64_decode . This function is returned by base64_decode to support piecewise-decoding streams. Simply call with string arguments, accumulating the returned strings. When finished with the stream, call with no arguments. This will return the final string to append and reset the stream for reuse.

Parameters:

  • s: string The next piece of the string to convert; absent to finish conversion

Usage:

dec = glib.base64_decode()
while true do
  buf = inf:read(4096)
  if not buf then break end
  outf:write(dec(buf))
end
outf:write(dec())

Returns:

string The next piece of the converted output

see also:

base64_decode

base64_decode ([s])

Base64-decode a string. This is a wrapper for g_base64_deocde() and friends.

Parameters:

  • s: string The data to decode. If absent, return a function like base64_decode for decoding a stream.

Returns:

string |function The decoded form of the base64-encoded stream, or a function to do the same on a stream.

see also:

_base64_decode_

Data Checksums

_sum_ ([s][, raw])

Stream checksum/hash calculation function type. This function is returned by md5sum , sha1sum , or sha256sum to support computing stream checksums piecewise. Simply call with string arguments, until the stream is complete. Then, call with an absent or nil argument to return the final checksum. Doing so invalidates the state, so that the function returns an error from that point forward.

Parameters:

  • s: string The next piece of the string to checksum; absent or nil to finish checksum
  • raw: boolean True if checksum should be returned in binary form. Otherwise, return the lower-case hexadecimal-encoded form (ignored if s is not nil)

Usage:

sumf = glib.md5sum()
while true do
  buf = inf:read(4096)
  if not buf then break end
  sumf(buf)
end
sum = sumf()

Returns:

|nil |string Nothing unless s is absent or nil. Otherwise, return the computed checksum.

Raises:

If the state is invalid, always return nil.

see also:

md5sum ([s[, raw]])

Compute MD5 checksum of a string. This is a wrapper for g_checksum_new() and friends.

Parameters:

  • s: string The data to checksum. If absent, return a function like _sum_ to checksum a stream piecewise.
  • raw: boolean True if checksum should be returned in binary form. Otherwise, return the lower-case hexadecimal-encoded form (ignored if s is nil)

Returns:

string |function The MD5 checksum or a stream converter function.

see also:

_sum_

sha1sum ([s[, raw]])

Compute SHA1 checksum of a string. This is a wrapper for g_checksum_new() and friends.

Parameters:

  • s: string The data to checksum. If absent, return a function like _sum_ to checksum a stream piecewise.
  • raw: boolean True if checksum should be returned in binary form. Otherwise, return the lower-case hexadecimal-encoded form (ignored if s is nil)

Returns:

string |function The SHA1 checksum or a stream converter function.

see also:

_sum_

sha256sum ([s[, raw]])

Compute SHA256 checksum of a string. This is a wrapper for g_checksum_new() and friends.

Parameters:

  • s: string The data to checksum. If absent, return a function like _sum_ to checksum a stream piecewise.
  • raw: boolean True if checksum should be returned in binary form. Otherwise, return the lower-case hexadecimal-encoded form (ignored if s is nil)

Returns:

string |function The SHA256 checksum or a stream converter function.

see also:

_sum_

Secure HMAC Digests

_hmac_ ([s][, raw])

Stream HMAC calculation function. This function is returned by md5hmac , sha1hmac , or sha256hmac to support computing stream digests piecewise. Simply call with string arguments, until the stream is complete. Then, call with an absent or nil argument to return the final digest. Doing so invalidates the state, so that the function returns an error from that point forward.

Parameters:

  • s: string The next piece of the string to digest; absent or nil to finish digest
  • raw: boolean True if digest should be returned in binary form. Otherwise, return the lower-case hexadecimal-encoded form (ignored if s is not nil)

Usage:

hmacf = glib.md5hmac(key)
while true do
  buf = inf:read(4096)
  if not buf then break end
  hmacf(buf)
end
hmac = hmacf()

Returns:

|nil |string Nothing unless s is absent or nil. Otherwise, return the computed digest.

Raises:

If the state is invalid, always return nil.

see also:

md5hmac (key[, s[, raw]])

Compute secure HMAC digest using MD5. This is a wrapper for g_hmac_new() and friends.

This is only available with GLib 2.30 or later.

Parameters:

  • key: string HMAC key
  • s: string The data to digest. If absent, return a function like _hmac_ to digest a stream piecewise.
  • raw: boolean True if digest should be returned in binary form. Otherwise, return the lower-case hexadecimal-encoded form (ignored if s is nil)

Returns:

string |function The MD5 HMAC digest or a stream converter function.

see also:

_hmac_

sha1hmac (key[, s[, raw]])

Compute secure HMAC digest using SHA1. This is a wrapper for g_hmac_new() and friends.

This is only available with GLib 2.30 or later.

Parameters:

  • key: string HMAC key
  • s: string The data to digest. If absent, return a function like _hmac_ to digest a stream piecewise.
  • raw: boolean True if digest should be returned in binary form. Otherwise, return the lower-case hexadecimal-encoded form (ignored if s is nil)

Returns:

string |function The SHA1 HMAC digest or a stream converter function.

see also:

_hmac_

sha256hmac (key[, s[, raw]])

Compute secure HMAC digest using SHA256. This is a wrapper for g_hmac_new() and friends.

This is only available with GLib 2.30 or later.

Parameters:

  • key: string HMAC key
  • s: string The data to digest. If absent, return a function like _hmac_ to digest a stream piecewise.
  • raw: boolean True if digest should be returned in binary form. Otherwise, return the lower-case hexadecimal-encoded form (ignored if s is nil)

Returns:

string |function The SHA256 HMAC digest or a stream converter function.

see also:

_hmac_

Internationalization

Note that in general, you will need to use os.setlocale and textdomain to initialize this. For example, for the application myapp, with locale files under the current directory:

os.setlocale("")
glib.textdomain("myapp", glib.get_current_dir())

To extract messages from Lua files using these functions, the following command can be used (may require recent gettext to support -k:g and lua):

xgettext -L lua -kQ_:1g -kC_:1c,2 -kNC_:1c,2 -kN_ -kglib.ngettext:1,2 \
         -ofile.po file.lua

to produce file.po from file.lua.

textdomain ([domain[, path[, encoding]]])

Set or query text message database location. Before this function is called, a default message database is used. This sets or queries the domain (also known as package or application) name, and optionally sets or queries the domain's physical file system location. It may also be used to set the encoding of output messages if not the default for the locale. Note that none of the exported translation functions take a domain name parameter, so this function may need to be called before every translation from a different domain.

Parameters:

  • domain: string |nil The domain to use for subsequent translation calls. If nil or missing, no change is made.
  • path: string |nil The path to message files, if not the system default. If nil or missing, no change is made.
  • encoding: string |nil The encoding of translation output. If nil or missing, no change is made.

Returns:

  1. string The current (new if set) domain for future translations.
  2. string The path to the translation strings for the current domain.
  3. string The encoding used for output messages. If nil, the locale's default is used.
_ (s)

Replace text with its translation. This is a wrapper for _(). It resides in the global symbol table rather than in glib .

Parameters:

  • s: string The text to translate

Returns:

string The translated text, or s if there is no translation

Q_ (s)

Replace text and context with its translation. This is a wrapper for Q_(). It resides in the global symbol table rather than in glib .

Parameters:

  • s: string the optional context, followed by a vertical bar, followed by the text to translate

Returns:

string The translated text, or s with its context stripped if there is no translation

C_ (c, s)

Replace text and context with its translation. This is a wrapper for C_(). It resides in the global symbol table rather than in glib .

Parameters:

Returns:

string The translated text, or s if there is no translation

N_ (s)

Mark text for translation. This is a wrapper for N_(). It resides in the global symbol table rather than in glib .

Parameters:

  • s: string The text to translate

Returns:

string s

NC_ (c, s)

Mark text for translation with context. This is a wrapper for NC_(). It resides in the global symbol table rather than in glib .

Parameters:

Returns:

  1. string s
  2. string c
ngettext (singular, plural, n)

Replace text with its number-appropriate translation. This is a wrapper for g_dngettext().

Parameters:

  • singular: string The text to translate if n is 1
  • plural: string The text to translate if n is not 1
  • n: number The number of items being translated

Returns:

string The translated text, or singular if there is no translation and n is 1, or plural if there is no translation and n is not 1.

get_locale_variants ([locale])

Obtain list of valid locale names. This is a wrapper for g_get_locale_variants() and g_get_language_names().

This is only available with GLib 2.28 or later.

Parameters:

  • locale: string If present, find valid locale names derived from this. Otherwise, find valid names for the default locale (including C).

Returns:

{string ,...}A table array containing valid names for the locale, in order of preference.

Date and Time Functions

sleep (t)

Suspend execution for some seconds. This is a wrapper for g_usleep().

Parameters:

  • t: number Number of seconds to sleep (microsecond accuracy)
usleep (t)

Suspend execution for some microseconds. This is a wrapper for g_usleep().

Parameters:

  • t: number Number of microseconds to sleep

Random Numbers

Note that no high-level wrapper functions are provided similar to those in cmorris' glib wrapper. Instead, pure Lua functions should be used:

function shuffle(a)
    local i
    for i = 1, #a do
        local r = glib.random(#a)
        local t = a[i]
        a[i] = a[r]
        a[r] = t
    end
end

function choice(a)
    if #a == 0 then
        return nil
    end
    return a[glib.random(#a)];
end

function sample(a, n)
    local b = {}
    local s = {}
    local i
    for i = 1, n do
        -- warning, this could take a while if n is near #a
        repeat
            r = glib.random(#a)
            -- to force this to run in predictable time, do this:
            -- while not b[r] do r = r % #a + 1 end
        until not b[r]
        b[r] = true
        s[i] = a[r]
    end
    return s
end
random ([low[, high]])

Obtain a psuedorandom number. This is a wrapper for g_random() and friends. This is a clone of the standard Lua math.random , but using a different random number algorithm. Note that there is no way to set the seed; use rand_new if you need to do that. In fact, you can simply replace random with the results of rand_new if you want to simulate setting a seed for this function.

Parameters:

  • low: number If high is present, this is the low end of the range of random integers to return
  • high: number If present, return a range of random integers, from low to high inclusive. If not present, return a floating point number in the range from zero to one exclusive of one. If low is not present, and high is, low is 1.

Usage:

-- set a seed for glib.random
glib.random = glib.rand_new(seed)

see also:

rand_new ([seed])

Obtain a psuedorandom number generator, given a seed. This is a wrapper for g_rand_new() and friends.

Parameters:

  • seed: number |{number ,...} seed (if not specified, one will be selected by the library). This may be either a number or a table array of numbers.

Returns:

function A function with the same behavior as random .

see also:

random

Miscellaneous Utility Functions

application_name ([name])

Set or get localized application name. This is a wrapper for g_get_application_name() and friends.

Parameters:

  • name: string If present, set the application name

Returns:

string The name of the application, as set by a previous invocation of this function.

see also:

prgname

prgname ([name])

Set or get program name. This is a wrapper for g_get_prgname() and friends.

Parameters:

  • name: string If present, set the program name

Returns:

string The name of the program, as set by a previous invocation of this function.

see also:

application_name

getenv (name)

Get environment variable value. This is a wrapper for g_getenv(). It is safer to use this than os.getenv if you are going to modify the environment.

Parameters:

  • name: string Name of environment variable to retrieve

Returns:

string Value of variable (string) if present; otherwise nil

see also:

setenv (name, value[, replace])

Set environment variable value. This is a wrapper for g_setenv(). If you use this, you should use glib.`getenv`_ instead of os.getenv as well.

Parameters:

  • name: string Name of variable to set
  • value: string New value of variable
  • replace: boolean True to replace if exists; otherwise leave old value

Returns:

boolean True if set succeeded; false otherwise

see also:

unsetenv (name)

Remove environment variable. This is a wrapper for g_unsetenv(). If you use this, you should use glib.`getenv`_ instead of os.getenv as well.

Parameters:

  • name: string Name of variable to remove from environment

see also:

listenv ()

Obtain names of all environment variables. This is a wrapper for g_listenv().

Returns:

{string ,...}An array table whose entries are environment variable names

get_user_name ()

Obtain system user name for current user. This is a wrapper for g_get_user_name().

Returns:

string The name of the user

get_real_name ()

Obtain full user name for current user. This is a wrapper for g_get_real_name().

Returns:

string The full name of the user, or Unknown if this cannot be obtained.

get_dir_name (d)

Obtain a standard directory name. This is a wrapper for g_get_*_dir().

Parameters:

  • d: string The directory to obtain; one of cache, config, data, desktop, documents, download, home, music, pictures, runtime, share, system_config, system_data, templates, tmp, videos, list. list just returns this list of names.

Returns:

string |{string ,...}The directory (a string) if there can be only one; if there can be more than one, the list of directories is returned as a table array of strings. Currently, only list, system_data, and system_config return more than one.

Raises:

If there is no standard directory of the given kind, returns nil.

get_host_name ()

Obtain current host name. This is a wrapper for g_get_host_name().

Returns:

string The local host name. This is not guaranteed to be a unique identifier for the host, or in any way related to its DNS entry.

get_current_dir ()

Obtain current working directory. This is a wrapper for g_get_current_dir().

Returns:

string The current working directory, as an absolute path.

path_is_absolute (d)

Check if a directory is absolute. This is a wrapper for g_path_is_absolute().

Parameters:

  • d: string The directory to check

Returns:

boolean True if d is absolute; false otherwise.

path_split_root (d)

Split the root part from a path. This is a wrapper for g_path_skip_root().

Parameters:

Returns:

  1. string |nil The root part. If the path is not absolute, this will be nil.
  2. string The non-root part
path_get_basename (d)

Obtain the last element of a path. This is a wrapper for g_path_get_basename(). Note that if the last element of a path is blank, this may return the second-to-last element. Also, if this is simply a directory separator, the directory separator is returned. In other words, it is not possible to reconstruct the original file name by appending results from this function.

Parameters:

Returns:

string The last path element of the path

path_get_dirname (d)

Obtain all but the last element of a path. This is a wrapper for g_path_dirname(). Note that if there is no parent element, and the path is relative, . may be returned. If the path is absolute, the absolute prefix may be returned even if it is the only element present. If there is a terminating directory separator, this may return the same path element as path_get_basename .

Parameters:

Returns:

string All but the last element of the path.

build_filename (...)

Construct a file name from its path constituents. This is a wrapper for g_build_filenamev(). There is no inverse operation, but it can be implemented in Lua:

-- assumes multiple consecutive directory separators are the same as
-- just one separator (true on non-root in Windows and everywhere in UNIX)
-- but as a counterexample, AmigaOS has no . and .., but instead uses
-- blank to mean both:
--    "" == UNIX .  "/x" == ../x "x///y" == UNIX x/../../y
function split_filename(f)
    local res = {}
    local r
    r, f = glib.path_split_root(f)
    -- note: it may be a good idea to trim r as well:
    --  convert ^[dir_sep]+$ to dir_sep[0] (strip duplicate dir_sep)
    --  convert ^([^dir_sep].*?)[dir_sep]*$ to \1 (stip trailing dir_sep)
    local rx = glib.regex_new('[' .. glib.regex_escape_string(glib.dir_separator) .. ']')
    local i, e, laste
    for i, e in ipairs(rx:split(f)) do
        if e ~= '' then table.insert(res, e) end
        laste = e
    end
    if laste == '' then table.insert(res, '') end
end

Parameters:

  • ...: {string ,...}|string ,... If the first parameter is a table, this table contains a list of path element strings. Otherwise, all parameters are taken to be the path element strings.

Returns:

string The result of concatenating all supplied path elements, separated by at most one directory separator as appropriate.

build_path (sep, ...)

Construct a path from its constituents. This is a wrapper for g_build_pathv(). Note that blank elements are simply ignored. If blank elements are required, use Lua instead:

function build_path(sep, ...)
    local i, v
    local ret = ''
     for i, v in ipairs{...} do
       if i > 1 then ret = ret .. sep end
       ret = ret .. v
     end
end

Also, there is no inverse function. This can be emulated using regex:split :

function split_path(p, sep)
   local rx = glib.regex_new(glib.regex_escape_string(sep))
   return rx:split(p)
end

Parameters:

  • sep: string The path element separator
  • ...: {string ,...}|string ,... If the first parameter is a table, this table contains a list of path element strings. Otherwise, all parameters are taken to be the path element strings.

Returns:

string The result of concatenating all supplied path elements, separated by at most one path separator.

see also:

build_filename

path_canonicalize (f)

Canonicalize a path name. This does not wrap anything in GLib, as GLib does not provide such a function. This function converts a path name to an absolute path name with all relative path references (i.e., . and ..) removed and symbolic links resolved. Additional steps are taken on Windows in an attempt to resolve the myriad of ways a path name may be specified, including short-to-long name conversion, case normalization (for path elements which exist), and UNC format consolidation. Note that there are several unresolvable issues: On Windows, there may be host names in the path, which are hard to resolve even with DNS. Also, both Windows and UNIX might have the same path mounted in two different places, and sometimes it's hard to tell that they are the same (and no extra effort is put into checking, either).

Parameters:

Returns:

string The canonicalized file name. Note that on Windows, the canonical name always uses backslashes for directory separators.

Raises:

Returns nil followed by an error message if there is a problem

qsort (t[, cmp])

Sort a table using a stable quicksort algorithm. This is a wrapper for g_qsort_with_data(). This sorts a table in-place the same way as table.sort does, but it performs an extra comparison if necessary to determine of two elements are equal (i.e., cmp(a, b) == cmp(b, a) == false). If so, they are sorted in the order they appeared in the original table. The extra comparison can be avoided by returning a number instead of a boolean from the comparison function; in this case, the number's relationship with 0 indicates a's relationship with b.

Parameters:

  • t: table Table to sort
  • cmp: function Function to use for comparison; takes two table elements and returns true if the first is less than the second. If not specified, Lua's standard less-than operator is used. The function may also return an integer instead of a boolean, in which case the number must be 0, less than 0, or greater than 0, indicating a is equal to, less than, or greater than b, respectively.

see also:

cmp (a, b)

Compare two objects. This function returns the difference between two objects. If the sub operation is available in the first object's metatable, that is called. Otherwise, if both parameters are numbers, they are subtracted. Otherwise, if they are both strings, they are byte-wise compared and their relative order is returned. Finally, as a last resort, the standard less-than operator is used, possibly twice, to indicate relative order.

Parameters:

  • a: string |number The first object
  • b: string |number The second object

Returns:

integer Greater than zero if a is greater than b; less than zero if a is less than b; zero if a is equal to b.

see also:

utf8_collate

Timers

timer_new ()

Create a stopwatch-like timer. This is a wrapper for g_timer_new().

Returns:

timer A timer object

Class timer

timer:start ()
Start or reset the timer. This is a wrapper for g_timer_start().
timer:stop ()
Stop the timer if it is running. This is a wrapper for g_timer_stop().
timer:continue ()
Resume the timer if it is stopped. This is a wrapper for g_timer_continue().
timer:elapsed ()

Return the amount of time counted so far. This is a wrapper for g_timer_elapsed().

Returns:

number The time counted so far, in seconds.

Spawning Processes

spawn (args)

Run a command asynchronously. This is a wrapper for g_spawn_async_with_pipes(). The other spawn functions can easily be emulated using this.

Parameters:

  • args: table |string

    If the parameter is a string, parse the string as a shell command and execute it. Otherwise, the command is taken from the table. If the table has no array component, the command must be specified using the cmd field. Otherwise, the array elements specify the argument vector of the command. If both are provided, the command to actually execute is cmd, but the first array element is still passed in as the proposed process name. In addition to the command arguments and cmd field, the following fields specify options for the spawned command:

    stdin: file|string|boolean (default = false)

    Specify the standard input to the process. If this is a file descriptor, it must be opened in read mode; its contents will be the process' standard input. If this is a string, it names a file to be opened for reading. The file name may be blank to indicate that the standard input should be inherited from the current process. The file name may be prefixed with an exclamation point to open in binary mode; otherwise it is opened in normal (text) mode. Any other value is evaluated as a boolean; true means that a pipe should be opened such that proc:write() writes to the process, and false means that no standard input should be provided at all (equivalent to UNIX /dev/null).

    stdout: file|string|boolean (default = true)

    Specify the standard output for the process. If this is a file descriptor, it must be opened in write mode; the process' standard output will be written to that file. If this is a string, it names a file to be opened for appending. The file name may be blank to indicate that the standard output should be inherited from the current process. The file name may be prefixed with an exclamation point to open in binary mode; otherwise it is opened in normal (text) mode. Any other value is evaluated as a boolean; true means that a pipe should be opened such that proc:read() reads from the process, and false means that standard output should be ignored.

    stderr: file|string|boolean (default = “”)

    Specify the standard error for the process. See the stdout description for details; the only difference is in which functions are used to read from the pipe (read_err and friends).

    env: table

    Specify the environment for the process. If this is not provided, the environment is inherited from the parent. Otherwise, all keys in the table correspond to variables, and the values correspond to those variables' values. Only these variables will be set in the spawned process.

    path: boolean (default = true)

    If this is present and false, do not use the standard system search path to find the command to execute.

    chdir: string

    If this is present, change to the given directory when executing the commmand. Otherwise, it will execute in the current working directory.

    cmd: string

    If this is present, and there are no array entries in this table, it is parsed as a shell command to construct the command to run. Otherwise, it is the command to execute instead of the first element of the argument array.

Usage:

-- fully quoted arguments
p = glib.spawn {'cat', f}
f_cont = p:wait()

-- generic command line; parsed by glib rather than shell so relatively safe
p = glib.spawn{cmd='cat /tmp/xyz'}
-- or p = glib.spawn('cat /tmp/xyz')
xyz_cont = p:wait()

-- fully quoted arguments, but with renamed argv[0] if supported
p = glib.spawn{'concatenate', f, cmd='/bin/cat'}
f_cont = p:wait()

-- write output to a file
-- more portable than tacking >file to the command
of = open('/tmp/of', 'w')
p = glib.spawn{'cat', f, stdout=of}
p:wait()
of:close()

Returns:

process An object representing the process.

see also:

shell_parse_argv

Class process

process:read_ready (...)

Check if input is available from process standard output. This function is used to support non-blocking input from the process. It takes the same parameters as process:read , and returns true if that read would succeed without blocking. Otherwise, it returns false (immediately). It accomplishes this by attempting the requested read in a background thread, and returning success when the data has actually been read. Due to buffer sizes used and other issues, the reader thread might hang waiting for input even when enough data is available, depending on operating system. On Linux, at least, it should never hang. Note that it is not necessary to use the same arguments for a subsequent process:read . For example, the entire file can be pre-read using read_ready('*a'), followed by reading one line at a time. Attempting to read more than a prior read_ready may cause the system to wait for further input.

Parameters:

  • ...: string |number See process:read for details. For the ‘*n' format, since it is difficult to tell how much input will be required, the thread will read until it finds a non-blank word.

Returns:

boolean True if reading using the given format(s) will succeed without blocking.

see also:

process:read

process:read_err_ready (...)

Check if input is available from process standard error. See the documentation for process:read_ready for details.

Parameters:

Returns:

boolean True if reading using the given format(s) will succeed without blocking.

see also:

process:read_ready

process:read (...)

Read data from a process' standard output. This function is a clone of the standard Lua file:read function. It defers actual I/O to the process:read_ready routine, which in turn lets a background thread do all of the reading. It will block until process:read_ready is true, and then read directly from the buffer filled by the thread.

Parameters:

  • ...: string |number

    If no parameters are given, read a single newline-terminated line from input, and strip the trailing newline. Otherwsie, for each parameter, until failure, a result is read and returned based on the parameter. If the parameter is a number, then that many bytes (or fewer) are read. Otherwise, the parameter must be a string containing one of the following:

    • ‘*l' – read a line in the same way as the empty argument list does.
    • ‘*n' – read a number from input; in this case, a number is returned instead of a string.
    • ‘*a' – read the entire remainder of the input. Note that if this is given as a format to process:read_ready , all standard output from the process will be read as soon as it is available.

Returns:

string |number |nil... For each parameter (or for the line read by the empty parameter list), the results of reading that format are returned. If an error occurred for any parameter, nil is returned for that parameter and no further parameters are processed.

see also:

process:read_ready

process:read_err (...)

Read data from a process' standard error. See the process:read function documentation for details.

Parameters:

  • ...: string |number See the read function documentation for details.

Returns:

string |number |nil... See the read function documentation for details.

see also:

process:read

process:lines ()

Return an iterator which reads lines from the process' standard output. On each iteration, this returns the result of process:read ().

Returns:

function The iterator.

see also:

process:read

process:lines_err ()

Return an iterator which reads lines from the process' standard error. On each iteration, this returns the result of process:read_err ().

Returns:

function The iterator.

see also:

process:read_err

process:write_ready ()

Check if writing to the process' standard input will block. Writing to a process' standard input is made non-blocking by running writes in a background thread.

Returns:

boolean True if a call to process:write() will not block.

see also:

process:write

process:write (...)

Write to a process' standard input. Writes all arguments to the process' standard input. It does this using a background writer thread that writes each argument before allowing the next write. In other words, the first write will not block, but subsequent writes will bock until the previous write has completed.

Parameters:

  • ...: string... All strings are written, in the order given.

Returns:

boolean Returns true on success. However, since the write has not truly completed until the background writer has finished, the only way to ensure that writing was complete and successful is to use process:write_ready or process:io_wait .

see also:

process:write_ready

process:close ()
Close the process' standard input channel. This function flushes any pending writes and closes the input channel. Many processes which take input from standard input need this to detect the end of input in order to continue processing.
process:io_wait ([check_in[, check_out[, check_err]]])

Check for process activity. Check to see if I/O is in progress or the process has died.

Parameters:

  • check_in: boolean Return a flag indicating if the background standard input writer is idle.
  • check_out: boolean Return a flag indicating if the background standard output reader is idle.
  • check_err: boolean Return a flag indicating if the background standard error reader is idle.

Returns:

  1. boolean True if the standard input thread is idle; only returned if requested
  2. boolean True if the standard output thread is idle; only returned if requested
  3. boolean True if the standard error thread is idle; only returned if requested
  4. boolean True if the process is no longer running.
process:pid ()

Return the glib process ID for the process. Using the process ID for anything other than printing debug messages is non-portable.

Returns:

number GLib process ID (which may or may not correspond to a system process ID)

process:status ()

Return the status of the running process.

Returns:

string |number If the process is running, the string running is returned. Otherwise, the numeric exit code from the process is returned.

process:check_exit_status ()

Check if the process return code was an error.

This is only available with GLib 2.34 or later.

Returns:

string |nil If the status returned by process:status should be interpreted as an error, a human-readable error message is returned. If the process has not yet finished, or the return code is considered successful, nil is returned.

process:wait ()

Wait for process termination and clean up. This function starts background reads for all data on the standard output and standard error channels, and flushes and closes the standard input channel. It then waits for the process to finish. Once finished, the result code from the process and any gathered standard output and standard error are returned.

Returns:

  1. number Result code from the process
  2. string If a standard output pipe was in use, this is the remaining data on the pipe.
  3. string If a standard error pipe was in use, this is the reaming data on the pipe.

File Utilities

file_get (name)

Return contents of a file as a string. This function is a wrapper for g_file_get_contents(). It is mostly equivalent to io.open(name):read('*a').

Parameters:

  • name: string Name of file to read

Returns:

  1. string |nil Contents of file, or nil if there was an error.
  2. string Error message if there was an error.
file_set (name, contents)

Set contents of a file to a string. This function is a wrapper for g_file_set_contents(). Rather than write directly to a file, it writes to a temporary first and then moves the result into place. In other words, it is not equivalent to io.open(name, 'w'):write(contents).

Parameters:

  • name: string Name of file to write
  • contents: string Contents to write

Returns:

boolean True if successful

Raises:

Returns false and error message string on error.

is_file (name)

Test if the given path points to a file. This function is a wrapper for g_file_test().

Parameters:

  • name: string The path name to test

Returns:

boolean true if name names a plain file

is_dir (name)

Test if the given path points to a directory. This function is a wrapper for g_file_test().

Parameters:

  • name: string The path name to test

Returns:

boolean true if name names a plain file

is_exec (name)

Test if the given path points to an executable file. This function is a wrapper for g_file_test(). Note that GLib uses heuristics on Windows, since there is no executable bit to test.

Parameters:

  • name: string The path name to test

Returns:

boolean true if name names an executable file.

exists (name)

Test if the given path points to a file or directory. This function is a wrapper for g_file_test(). Note that invalid symbolic links return false, even though they actually exist.

Parameters:

  • name: string The path name to test

Returns:

boolean true if name exists in the file system

umask ([mask])

Change default file and directory creation permissions mask. This is a wrapper for the system umask() function, since there is no equivalent in GLib.

Parameters:

  • mask: string |number The permissions mask. Permissions set in this mask are forced off in any newly created files and directories. Either a numeric permissions mask or a POSIX-sytle mode string (e.g. ‘og=w', which is the default if this parameter is unspecified) or the last 9 characters of long directory listing mode (e.g. ‘—-w–w-', which is also the default).

Returns:

number The previous mask.

mkstemp (tmpl[, perm])

Create a unique temporary file from a pattern. This function is a wrapper for g_mkstemp(). It creates a new, unique file by replacing the X characters in a template containing six consecutive X characters.

Parameters:

  • tmpl: string The template.
  • perm: string |number File creation permissions. Either a numeric permission mask or a POSIX-style mode string (e.g. ‘ug=rw') or the last 9 characters of long directory listing mode (e.g. ‘rwxr-xr-x')

Returns:

  1. file A file descriptor for the newly created file, open for reading and writing (w+b).
  2. string The name of the created file.

Raises:

Returns nil and error message string on error.

open_tmp ([tmpl])

Create a unique temporary file in the standard temporary directory. This function is a wrapper for g_file_open_tmp(). It creates a new, unique file by replacing the X characters in a template containing six consecutive X characters. The template may contain no directory separators.

Parameters:

  • tmpl: string The template. If unspecified, a default template will be used.

Returns:

  1. file A file descriptor for the newly created file, open for reading and writing (w+b).
  2. string The full path name of the created file.

Raises:

Returns nil and error message string on error.

mkdir_with_parents (name[, mode])

Create a directory and any required parent directories. This is a wrapper for g_mkdir_with_parents().

Parameters:

  • name: string Name of directory to create.
  • mode: string |number File permissions. Either a numeric creation mode or a POSIX-style mode string (e.g. ‘ug=rw') or the last 9 characters of long directory listing mode (e.g. ‘rwxr-xr-x'). If unspecified, ‘a=rx,u=w' is used (octal 755; ‘rwxr-xr-x')).

Returns:

boolean True

Raises:

Returns false and error message string on error.

mkdtemp (tmpl[, mode])

Create a unique tempoarary directory from a pattern. This is a wrapper for g_mkdtemp. It replaces 6 consecutive Xs in the pattern with a unique string and creates a directory by that name.

This is only available with GLib 2.30 or later.

Parameters:

  • tmpl: string The file name pattern
  • mode: string |number File permissions. Either a numeric creation mode or a POSIX-style mode string (e.g. ‘ug=rw') or the last 9 characters of long directory listing mode (e.g. ‘rwxr-xr-x').

Returns:

string The name of the created directory

Raises:

Returns nil and error message string on error.

dir_make_tmp ([tmpl])

Create a unique temporary directory in the standard temporary directory. This is a wrapper for g_dir_make_tmp(). It creates a new, unique directory in the standard temporary directory by replacing 6 consecutive Xs in the template.

This is only available with GLib 2.30 or later.

Parameters:

  • tmpl: string The template. If unspecified, a default template will be used.

Returns:

string The name of the created directory

Raises:

Returns nil and error message string on error.

dir (d)

Returns an iterator which lists entries in a directory. This function wraps g_dir_open() and friends.

Parameters:

  • d: string The directory to list

Returns:

function Iterator

Raises:

Returns nil and error message string on error.

rename (old, new)

Rename a file sytem entity. This is a wrapper for g_rename().

Parameters:

Returns:

boolean True

Raises:

Returns false and error message string on error.

mkdir (name[, mode])

Create a directory. This is a wrapper for g_mkdir().

Parameters:

  • name: string The name of the directory.
  • mode: string |number File permissions. Either a numeric creation mode or a POSIX-style mode string (e.g. ‘ug=rw') or the last 9 characters of long directory listing mode (e.g. ‘rwxr-xr-x'). The default is ‘a=rx,u=w' (octal 755, ‘rwxr-xr-x').

Returns:

boolean True

Raises:

Returns false and error message string on error.

stat (name[, fields])

Retrieve information on a file system entry. This is a wrapper for g_stat(). If a table is given to specify fields, only those fields are returned (nil if not present) as multiple results. Otherwise, a table is returned with all known fields and their values. If the field named ‘link' is requested, it is not an actual field, but an indicator to return information about a soft link rather than what it points to.

Parameters:

  • name: string The file system entry to query
  • fields: {string ,...}|string ,... The fields to query, in order.

Returns:

  1. table A table whose keys are field names and whose values are the value for that field, if either no specific values are requested or the only value requested is the psuedo-value ‘link'.
  2. number |string |nil The value of each field; multiple values may be returned. Unknown fields return nil.

Raises:

Returns nil and error message string on error.

remove (name)

Remove a file sytem entity. This is a wrapper for g_remove(). For recursive removal, use Lua:

function rm_r(f)
    local ok, msg, err, gmsg
    if not glib.is_symlink(f) and glib.is_dir(f) then
        local e
        for e in glib.dir(f) do
            ok, msg = rm_r(glib.build_filename(f, e))
            if not ok and not err then
                err = true
                gmsg = msg
            end
        end
    end
    ok, msg = glib.remove(f)
    if not ok and not err then
         err = true
         gmsg = msg
    end
    if err then
         return false, gmsg
    else
         return true
    end
end

Parameters:

  • name: string The entity to remove

Returns:

boolean True on success.

Raises:

Returns false and an error message string on failure. Note that the error message is probably invalid if the entity was not a directory.

chmod (name, perm)

Change filesystem entry permissions. This is a wrapper for g_chmod(). In addition, it will query the original file for information if a string-style permission is used.

Parameters:

  • name: string The filesystem entry to modify
  • perm: string |number Permissions to set.

Returns:

boolean True

Raises:

Returns false and error message string on error.

can_read (name)

Test if fileystem object can be read. This is a wrapper for g_access(). Note that this function does not necessarily check access control lists, so it may be better to just test open/read the file.

Parameters:

  • name: string Name of object to test

Returns:

  1. boolean true if name can be read.
  2. string message if name cannot be read.
  3. number error number if name cannot be read.
can_write (name)

Test if fileystem object can be written to. This is a wrapper for g_access(). Note that this function does not necessarily check access control lists, so it may be better to just test open/write the file.

Parameters:

  • name: string Name of object to test

Returns:

  1. boolean true if name can be written to.
  2. string message if name cannot be written to.
  3. number error number if name cannot be written to.
chdir (dir)

Change current working directory. This is a wrapper for g_chdir().

Parameters:

  • dir: string Name of directory to change into

Returns:

boolean True

Raises:

Returns false and error message string on error.

utime (name[, atime[, mtime]])

Change timestamp on filesystem object. This is a wrapper for g_utime().

Parameters:

  • name: string Name of entry to touch
  • atime: number |nil access time; mtime is used if not present. Note that atime may not be supported by the target file system entry; no error is returned even if that is the case.
  • mtime: number |nil modification time; current time is used if neither atime nor mtime present; left alone if atime present but mtime not present

Returns:

boolean True

Raises:

Returns false and error message string on error.

URI Functions

uri_reserved_chars_allowed_in_path
Allowed characters in a path. This is a wrapper for G_URI_RESERVED_CHARS_ALLOWED_IN_PATH.
uri_reserved_chars_allowed_in_path_element
Allowed characters in path elements. This is a wrapper for G_URI_RESERVED_CHARS_ALLOWED_IN_PATH_ELEMENT.
uri_reserved_chars_allowed_in_userinfo
Allowed characters in userinfo (RFC 3986). This is a wrapper for G_URI_RESERVED_CHARS_ALLOWED_IN_USERINFO.
uri_reserved_chars_generic_delimiters
Generic delimiter characters (RFC 3986). This is a wrapper for G_URI_RESERVED_CHARS_GENERIC_DELIMITERS.
uri_reserved_chars_subcomponent_delimiters
Subcomponent delimiter characters (RFC 3986). This is a wrapper for G_URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS.
uri_parse_scheme (uri)

Extract scheme from URI. This is a wrapper for g_uri_parse_scheme().

Parameters:

Returns:

string The scheme

Raises:

Returns nil on error.

uri_escape_string (s[, allow[, utf8]])

Escapes a string for use in a URI. This is a wrapper for g_uri_escape_string().

Parameters:

  • s: string The string to esacape; nuls are not allowed.
  • allow: string Reserved characters to leave unescaped anyway.
  • utf8: boolean Allow UTF-8 characters in result.

Returns:

string The escaped string.

uri_unescape_string (s[, illegal])

Unescapes an escaped string. This is a wrapper for g_uri_unescape_string().

Parameters:

  • s: string The string to unescape
  • illegal: string Characters which may not appear in the result; nul characters are automatically illegal.

Returns:

string The unescaped string.

Raises:

Returns nil on error.

uri_list_extract_uris (list)

Splits an URI list conforming to the text/uri-list MIME type (RFC 2483). This is a wrapper for g_uri_list_extract_uris().

Parameters:

Returns:

{string ,...}A table containing the URIs

filename_from_uri (uri)

Converts an ASCII-encoded URI to a local filename. This is a wrapper for g_filename_from_uri().

Parameters:

Returns:

  1. string The file name
  2. string |nil The host name, or nil if none

Raises:

Returns nil and error message string on error.

filename_to_uri (file[, host])

Converts an absolute filename to an escaped ASCII-encoded URI. This is a wrapper for g_filename_to_uri().

Parameters:

Returns:

string The URI

Raises:

Returns nil and error message string on error.

Hostname Utilities

hostname_to_ascii (hostname)

Convert a host name to its canonical ASCII form. This is a wrapper for g_hostname_to_ascii().

Parameters:

  • hostname: string The name to convert

Returns:

string The converted name

Raises:

Returns nil on error.

hostname_to_unicode (hostname)

Convert a host name to its canonical Unicode form. This is a wrapper for g_hostname_to_unicode().

Parameters:

  • hostname: string The name to convert

Returns:

string The converted name

Raises:

Returns nil on error.

hostname_is_non_ascii (hostname)

Check if a host name contains Unicode characters. This is a wrapper for g_hostname_is_non_ascii().

Parameters:

  • hostname: string The name to check

Returns:

boolean True if the host name needs to be converted to ASCII for non-IDN-aware contexts.

hostname_is_ascii_encoded (hostname)

Check if a host name contains ASCII-encoded Unicode characters. This is a wrapper for g_hostname_is_ascii_encoded().

Parameters:

  • hostname: string The name to check

Returns:

boolean True if the host name needs to be converted to Unicode for presentation and IDN-aware contexts.

hostname_is_ip_address (hostname)

Check if a string is an IPv4 or IPv6 numeric address. This is a wrapper for g_hostname_is_ip_address().

Parameters:

  • hostname: string The name to check

Returns:

boolean True if the host name is actually an IP address

Shell-related Utilities

shell_parse_argv (cmdline)

Parse a command line into an argument vector, but without variable and glob pattern expansion. This is a wrapper for g_shell_parse_argv().

Parameters:

  • cmdline: string The command line to parse

Returns:

{string ,...}A table containing the command-line arguments

Raises:

Returns nil and error message string on error.

shell_quote (s)

Quote a string so it is interpreted unmodified as a shell argument. This is a wrapper for g_shell_quote().

Parameters:

  • s: string The string to quote

Returns:

string The quoted string

shell_unquote (s)

Unquote a string quoted for use as a shell argument. This is a wrapper for g_shell_unquote().

Parameters:

  • s: string The string to unquote

Returns:

string The unquoted string

Raises:

Returns nil and error message string on error.

Perl-compatible Regular Expressions

regex_new (pattern[, cflags[, mflags]])

Compile a regular expression for use in matching functions. This is a wrapper for g_regex_new(). See in particular the Regular expression syntax section of the GLib documentation.

Parameters:

  • pattern: string The regular expression. Note that embedded NUL characters are supported.

  • cflags: {string ,...}

    Compile flags (note: some may be set by the library based on the pattern input):

    • caseless – Case-insensitive search
    • multiline – ^ and $ match newlines in search strings
    • dotall – . matches newlines
    • extended – unescaped whitespace and unescaped # .. newline ignored
    • anchored – pattern must match at start of string
    • dollar_endonly – $ does not match newline at end of string
    • ungreedy – Invert greediness of variable-length matches
    • raw – Strings are sequences of bytes rather than UTF-8
    • no_auto_capture – Plain () does not capture (use explicitly named captures)
    • optimize – Optimize the regular expression
    • dupnames – Do not enforce unique subpattern names
    • newline_cr – Newlines for $, ^, and . are \r (default: any).
    • newline_lf – Newlines for $, ^, and . are \n (default: any).
    • newline_crlf – Newlines for $, ^, and . are \rn (default: any).
  • mflags: {string ,...}

    Match flags:

    • anchored – pattern must match at start of string
    • notbol – ^ does not match the start of string (but \A does)
    • noteol – $ does not match the end of string (but \Z and \z do)
    • notempty – the match length must be greater than zero
    • partial – use partial (incremental) matching; incompatible with all
    • newline_cr – Newlines for $, ^, and . are \r.
    • newline_lf – Newlines for $, ^, and . are \n.
    • newline_crlf – Newlines for $, ^, and . are \rn.
    • newline_any – Newlines for $, ^, and . are any.
    • all – changes the behavior of matches from returning captures to returning all potential matches. That is, any variable-length matching operator will attempt to match at every possible length, rather than the most/least greedy depending on the ungreedy option an the ? greediness operator. This is incompatible with captures and partial matching.

Returns:

regex The compiled regular expression

Raises:

Returns nil and error message string on error.

regex_escape_string (s)

Escapes a string so it is a literal in a regular expression.

Parameters:

  • s: string The string to escape

Returns:

string The escaped string.

Class regex

regex:get_pattern ()

Get the pattern string used to create this regex.

Returns:

string The pattern string

regex:get_max_backref ()

Get the highest back reference in the pattern.

Returns:

number The number of the highest backreference, or 0 if there are none.

regex:get_has_cr_or_lf ()

Check if pattern contains explicit CR or LF references.

This is only available with GLib 2.34 or later.

Returns:

boolean true if the pattern contains explicit CR or LF references.

regex:get_max_lookbehind ()

Get the number of characters in the longest lookbehind assertion in the pattern.

This is only available with GLib 2.38 or later.

Returns:

number The number of characters in the longest lookbehind assertion.

regex:get_capture_count ()

Get the number of capturing subpatterns in the pattern.

Returns:

number The number of capturing subpatterns.

regex:get_string_number (name)

Get the number of the capturing subexpression with the given name.

Parameters:

  • name: string The subexpression name

Returns:

number The subexpression number, or -1 if name does not exist

regex:get_compile_flags ()

Get the names of all compile flags set when regex was created.

Returns:

{string ,...}The names of any flags set when regex was created.

regex:get_match_flags ()

Get the names of all matching flags set when regex was created.

Returns:

{string ,...}The names of any flags set when regex was created.

regex:find (s[, start[, mflags]])

Search for a match in a string.

Parameters:

  • s: string The string to search

  • start: number The start position.

  • mflags: {string ,...}

    Additional match flags:

    • anchored – pattern must match at start of string
    • notbol – ^ does not match the start of string (but \A does)
    • noteol – $ does not match the end of string (but \Z does)
    • notempty – the match length must be greater than zero
    • partial – use partial (incremental) matching; incompatible with all
    • newline_cr – Newlines for $, ^, and . are \r.
    • newline_lf – Newlines for $, ^, and . are \n.
    • newline_crlf – Newlines for $, ^, and . are \rn.
    • newline_any – Newlines for $, ^, and . are any.
    • all – changes the behavior of matches from returning captures to returning all potential matches. That is, any variable-length matching operator will attempt to match at every possible length, rather than the most/least greedy depending on the ungreedy option an the ? greediness operator. This is incompatible with captures and partial matching.

Returns:

  1. number |nil |boolean The location of the start of the first match, or nil if there are no matches, or false if there is only a partial match, in which case no further results are returned (the location of the match cannot be determined, and there are no captures).
  2. number The location of the last character of the first match
  3. string |boolean ,...On a successful match, all captures are returned as well. If a capture does not exist, false is returned for that capture. For all mode, these are actually all possible matches except the maximal match, which is described by the first two return values.

Raises:

Returns nil and error message string on error.

see also:

string.find

regex:tfind (s[, start[, mflags]])

Search for a match in a string. Unlike regex:find , captures are returned in a table rather than as individual return values.

Parameters:

  • s: string The string to search

  • start: number The start position.

  • mflags: {string ,...}

    Additional match flags:

    • anchored – pattern must match at start of string
    • notbol – ^ does not match the start of string (but \A does)
    • noteol – $ does not match the end of string (but \Z does)
    • notempty – the match length must be greater than zero
    • partial – use partial (incremental) matching; incompatible with all
    • newline_cr – Newlines for $, ^, and . are \r.
    • newline_lf – Newlines for $, ^, and . are \n.
    • newline_crlf – Newlines for $, ^, and . are \rn.
    • newline_any – Newlines for $, ^, and . are any.
    • all – changes the behavior of matches from returning captures to returning all potential matches. That is, any variable-length matching operator will attempt to match at every possible length, rather than the most/least greedy depending on the ungreedy option an the ? greediness operator. This is incompatible with captures and partial matching.

Returns:

  1. number |nil |boolean The location of the start of the first match, or nil if there are no matches, or false if there is only a partial match, in which case no further results are returned (the location of the match cannot be determined, and there are no captures).
  2. number The location of the last character of the first match
  3. {string |boolean ,...}On a successful match, all captures are returned as well. If a capture does not exist, false is returned for that capture. If there are no captures, an empty table is returned. For all mode, these are actually all possible matches except the maximal match, which is described by the first two return values.

Raises:

Returns nil and error message string on error.

see also:

string.find

regex:match (s[, start[, mflags]])

Search for a match in a string.

Parameters:

  • s: string The string to search

  • start: number The start position.

  • mflags: {string ,...}

    Additional match flags:

    • anchored – pattern must match at start of string
    • notbol – ^ does not match the start of string (but \A does)
    • noteol – $ does not match the end of string (but \Z does)
    • notempty – the match length must be greater than zero
    • partial – use partial (incremental) matching; incompatible with all
    • newline_cr – Newlines for $, ^, and . are \r.
    • newline_lf – Newlines for $, ^, and . are \n.
    • newline_crlf – Newlines for $, ^, and . are \rn.
    • newline_any – Newlines for $, ^, and . are any.
    • all – changes the behavior of matches from returning captures to returning all potential matches. That is, any variable-length matching operator will attempt to match at every possible length, rather than the most/least greedy depending on the ungreedy option an the ? greediness operator. This is incompatible with captures and partial matching.

Returns:

  1. string |nil |boolean The first capture, or the full match if there are no captures, or nil if there are no matches, or false if there is only a partial match (in which case there are no captures).
  2. string |boolean ,...On a successful match, all remaining captures are returned as well. If a capture does not exist, false is returned for that capture. For all mode, which has no captures, these are all possible matches but the maximal match, which is the first returned string.

Raises:

Returns nil and error message string on error.

see also:

string.match

regex:gmatch (s[, start[, mflags]])

Search for all matches in a string.

Parameters:

  • s: string The string to search

  • start: number The start position.

  • mflags: {string ,...} Additional match flags:

    • anchored – pattern must match at start of string
    • notbol – ^ does not match the start of string (but \A does)
    • noteol – $ does not match the end of string (but \Z does)
    • notempty – the match length must be greater than zero
    • partial – use partial (incremental) matching
    • newline_cr – Newlines for $, ^, and . are \r.
    • newline_lf – Newlines for $, ^, and . are \n.
    • newline_crlf – Newlines for $, ^, and . are \rn.
    • newline_any – Newlines for $, ^, and . are any.

    Note that a regex created using all will return an error.

Returns:

function An iterator function which, on each iteration, returns the same as regex:match would have for the next match in the string.

see also:

regex:gfind (s[, start[, mflags]])

Search for all matches in a string.

Parameters:

  • s: string The string to search

  • start: number The start position.

  • mflags: {string ,...} Additional match flags:

    • anchored – pattern must match at start of string
    • notbol – ^ does not match the start of string (but \A does)
    • noteol – $ does not match the end of string (but \Z does)
    • notempty – the match length must be greater than zero
    • partial – use partial (incremental) matching
    • newline_cr – Newlines for $, ^, and . are \r.
    • newline_lf – Newlines for $, ^, and . are \n.
    • newline_crlf – Newlines for $, ^, and . are \rn.
    • newline_any – Newlines for $, ^, and . are any.

    Note that a regex created using all will return an error.

Returns:

function An iterator function which, on each iteration, returns the same as regex:find would have for the next match in the string.

see also:

regex:find

regex:gtfind (s[, start[, mflags]])

Search for all matches in a string.

Parameters:

  • s: string The string to search

  • start: number The start position.

  • mflags: {string ,...} Additional match flags:

    • anchored – pattern must match at start of string
    • notbol – ^ does not match the start of string (but \A does)
    • noteol – $ does not match the end of string (but \Z does)
    • notempty – the match length must be greater than zero
    • partial – use partial (incremental) matching
    • newline_cr – Newlines for $, ^, and . are \r.
    • newline_lf – Newlines for $, ^, and . are \n.
    • newline_crlf – Newlines for $, ^, and . are \rn.
    • newline_any – Newlines for $, ^, and . are any.

    Note that a regex created using all will return an error.

Returns:

function An iterator function which, on each iteration, returns the same as regex:tfind would have for the next match in the string.

see also:

regex:tfind

regex:split (s[, start[, mflags[, max]]])

Split a string with a regular expression separator.

Parameters:

  • s: string The string to split

  • start: number The start position.

  • mflags: {string ,...} Additional match flags:

    • anchored – pattern must match at start of string
    • notbol – ^ does not match the start of string (but \A does)
    • noteol – $ does not match the end of string (but \Z does)
    • notempty – the match length must be greater than zero
    • newline_cr – Newlines for $, ^, and . are \r.
    • newline_lf – Newlines for $, ^, and . are \n.
    • newline_crlf – Newlines for $, ^, and . are \rn.
    • newline_any – Newlines for $, ^, and . are any.

    Note that a regex created using all or partial will return an error.

  • max: number The maximum number of elements to return. If unspecified or less than 1, all elements are returned.

Returns:

{string |boolean ,...}

The elements separated by the regular expression. Each element is separated by any capture strings from the separator, if present. If a capture does not exist, false is returned for that capture. If there are no captures, only the elements are returned. For example:

rx = glib.regex_new('\\|(.?)\\|')
spl = rx:split('abc||def|!|ghi')
 -- { 'abc', '', 'def', '!', 'ghi' }
regex:gsub (s, repl[, start[, n[, mflags]]])

Replace occurrences of regular expression in string.

Parameters:

  • s: string The string to modify. Note that zeroes are not supported in the final result string, whether they stem from s or repl.

  • repl: string |table |function The replacement. If this is a string, the string is the replacement text, which supports backslash-escapes for capture substitution and case conversion. If it is a table, the first capture (or entire match if there are no captures, or false if the capture exists but is not matched) is used as a key into the table; if the value is a string or number, it is the literal replacement text; otherwise, if the value is false or nil, no substitution is made. If it is a function, the function is called for every match, with all captures (or the entire match if there are no captures) as arguments (as with regex:match , captures which do not exist are passed as false); the return value is treated like the table entries. For literal interpretation of a string, call regex_escape_string on it first.

  • start: number The start position.

  • n: number |function The maximum number of replacements, if specified as a number greater than 0. If specified as a function, the function is called after determining the potential replacement text. Its parameters are the full match start position, the full match end position, and the potential replacement text (or false/nil if no replacement is to be made). The function must return two values: the first is the replacement operation: true if normal replacement is to be made, false if no replacement is to be made, and a string if an alternate replacement is to be made. The second is the conintuation flag: if absent, nil, or false, continue replacement, and if true, continue globally without checking n, and if a number, continue that many iterations maximum without checking n.

  • mflags: {string ,...} Additional match flags:

    • anchored – pattern must match at start of string
    • notbol – ^ does not match the start of string (but \A does)
    • noteol – $ does not match the end of string (but \Z does)
    • notempty – the match length must be greater than zero
    • newline_cr – Newlines for $, ^, and . are \r.
    • newline_lf – Newlines for $, ^, and . are \n.
    • newline_crlf – Newlines for $, ^, and . are \rn.
    • newline_any – Newlines for $, ^, and . are any.

    Note that a regex created using all or partial will return an error.

Returns:

  1. string The substituted string
  2. number The number of matches
  3. number The number of substitutions

Raises:

Returns nil and error message string on error.

see also:

regex_escape_string

Simple XML Subset Parser

The following functions use varargs, and are not supported:

g_markup_*printf_escaped(): emulate using string concat and renaming of escaper to shorter name:

e = glib.markup_escape_text
output = '<purchase>' ..
         '<store>' .. e(store) .. '</store>' ..
         '<item>' .. e(item) .. '</item>' ..
         '</purchase>'

g_markup_collect_attributes(): the only useful bit here that is for some reason not exposed independently is the boolean parser. Otherwise, it's best to emulate using lua:

-- usage:
attrs, msg = collect_attrs(attr_names, attr_vals,
                           {a='str', b='bool', c='?bool', ...})
if not attrs then print("error: " .. msg) end

-- only allocate/parse once
local bool_rx = glib.regex_new('^(false|f|no|n|0)|(true|t|yes|y|1)$', {'caseless'})
-- could pass in el_name for better error message
function collect_attrs(attr_names, attr_vals, req_parms)
  -- return attr=value table
  local attrs = {}
  -- put attrs i table, checking for duplicates
  local i, v
  for i, v in ipairs(attr_names) do
    if attrs[v] then return nil, "duplicate attribute " .. v end
    attrs[v] = attr_vals[i]
  end
  -- parse values, ensuring they are in req_parms as well
  local n
  for n, v in pairs(attrs) do
    local isreq = req_parms[n]
    if not isreq then return nil, "unknown attribute " .. n end
    if isreq:sub(1, 1) == '?' then isreq = isreq:sub(2) end
    if isreq == 'bool' then
      local f = bool_rx:match(v)
      if not f then return nil, "invalid boolean " .. n end
      attrs[n] = f == ''
    end
  end
  -- ensure that only optional values are missing
  for n, v in pairs(req_parms) do
    if v:sub(1, 1) ~= '?' and attrs[n] == nil then
      return nil, "missing attr " .. n
    end
  end
  return attrs
end
markup_escape_text (s)

Escape text so GMarkup XML parsing will return it to original.

Parameters:

  • s: string The string to escape

Returns:

string The escaped string

_gmarkup_start_element_ (ctx, name, attr_names, attr_values)

The function called when an opening tag of an element is seen.

Parameters:

  • ctx: markup_parse_context The context in which this was called
  • name: string The name of the element being started
  • attr_names: {string ,...} The names of the attributes in this tag, in order
  • attr_values: {string ,...} The values of the attributes in this tag, in the same order as the names.

Usage:

function counter()
  local count = 0
  return {
    start_element = function() count = count + 1 end,
    pop = function() return count end
  }
end
gmp = markup_parse_context_new {
   start_element = function(ctx, el, ...)
     if el == 'count' return counter() end
   end,
   end_element = function(ctx, n, pop)
     if pop then print(pop()) end
   end
}

Returns:

{string =value ,...}|nil

If present and a table, push the parser context and use the returned parser instead. The current parser will resume upon reaching the associated end element. See markup_parse_context_new for details.

  • start_element: a function like _gmarkup_start_element_ .
  • end_element: a function like _gmarkup_end_element_ .
  • text: a function like _gmarkup_text_ .
  • passthrough: a function like _gmarkup_passthrough_ .
  • error: a function like _gmarkup_error_ .
  • pop: a value to pass to the end_element handler when finished. It may be any value, but a function is probably most suitable. There is no guarantee that this value will ever be used, since it requires that no errors occur and that the end_element handler actually uses it.

Raises:

Returns error message string on error.

see also:

_gmarkup_end_element_ (ctx, name[, pop])

The function called when an ending tag of an element is seen.

Parameters:

  • ctx: markup_parse_context The context in which this was called
  • name: string The name of the element being started
  • pop: any If the context was previously pushed, and this is called for the terminating element of that context, this is the pop element which was pushed along with the parser.

Raises:

Returns error message string on error.

see also:

markup_parse_context_new

_gmarkup_text_ (ctx, text)

The function called when text within an element is seen.

Parameters:

Raises:

Returns error message string on error.

see also:

markup_parse_context_new

_gmarkup_passthrough_ (ctx, text)

The function called when unprocessed text is seen.

Parameters:

Raises:

Returns error message string on error.

see also:

markup_parse_context_new

_gmarkup_error_ (ctx, text)

The function called when an error occurs during parsing.

Parameters:

see also:

markup_parse_context_new

markup_parse_context_new (options)

Create GMarkup parser.

Parameters:

  • options: {string =value ,...}

    Context creation options:

    • start_element: a function like _gmarkup_start_element_ .
    • end_element: a function like _gmarkup_end_element_ .
    • text: a function like _gmarkup_text_ .
    • passthrough: a function like _gmarkup_passthrough_ .
    • error: a function like _gmarkup_error_ .
    • treat_cdata_as_text: If set and not false, return CDATA sections as text instead of passthrough.
    • prefix_error_position: If set and not false, prefix error messages returned by the above functions with line and column information.

see also:

Class markup_parse_context

markup_parse_context:end_parse ()

Finish parsing.

Returns:

boolean True

Raises:

Returns false and error message string on error.

markup_parse_context:get_position ()

Obtain current position in source text.

Returns:

  1. number The line number
  2. number The column number
markup_parse_context:get_element ()

Obtain the name of the current element being processed.

Returns:

string The element name.

markup_parse_context:get_element_stack ()

Obtain the complete path of element names to the current element being processed.

Returns:

{string ,...}The element names, starting with the most deeply nested.

markup_parse_context:parse (s)

Parse some text.

Parameters:

  • s: string The next chunk of text to process

Returns:

boolean True

Raises:

Returns false and error message string on error.

Key-value file parser

key_file_new ()

Create a new, empty key file.

Returns:

key_file The empty key file

Class key_file

key_file:set_list_separator (sep)

Sets character to separate values in lists.

Parameters:

  • sep: string The separator (only the first byte is used).
key_file:load_from_file (f[, dirs[, keep_com[, keep_trans]]])

Load a file.

Parameters:

  • f: string File name
  • dirs: boolean |{string ,...} If true, search relative to standard configuration file directories. If a table, search realtive to all directories in the table. Otherwise, the file name is absolute or relative to the current directory.
  • keep_com: boolean If true, keep comments so they are written by key_file:to_data .
  • keep_trans: boolean If true, keep all translations so they are written by key_file:to_data .

Returns:

  1. boolean True
  2. string The actual file name if a directory search was done.

Raises:

Returns false and error message string on error.

key_file:load_from_data (s[, keep_com[, keep_trans]])

Load data.

Parameters:

  • s: string The data
  • keep_com: boolean If true, keep comments so they are written by key_file:to_data .
  • keep_trans: boolean If true, keep all translations so they are written by key_file:to_data .

Returns:

boolean True

Raises:

Returns false and error message string on error.

key_file:to_data ()

Convert entire key file to a string.

Returns:

string The key file contents

Raises:

Returns nil and error message string on error.

key_file:save_to_file (name)

Writes out contents of key file. Uses same mechanism as file_set .

This is only available with GLib 2.40 or later.

Parameters:

Returns:

boolean True if successful

Raises:

Returns false and error message string on error.

key_file:get_start_group ()

Get the start group of the key file.

Returns:

string The name of the start group

key_file:get_groups ()

Get the names of all groups in the key file.

Returns:

{string ,...}A table containing the names of all the groups.

key_file:get_keys (group)

Get the names of all keys in a group.

Parameters:

  • group: string The name of a group to query

Returns:

{string ,...}A table containing the names of all keys in the *group

Raises:

Returns nil and error message string on error.

key_file:has_group (group)

Check if group exists.

Parameters:

  • group: string The group name

Returns:

boolean True if group exists in key file.

key_file:has_key (group, key)

Check if key exists.

Parameters:

Returns:

boolean True if key exists in key file.

Raises:

Returns false and error message string on error.

key_file:raw_get (group, key)

Obtain raw value of a key.

Parameters:

Returns:

string The value

Raises:

Returns nil and error message string on error.

key_file:get (group, key[, locale])

Obtain value of a key.

Parameters:

  • group: string The group name
  • key: string The key
  • locale: string If specified, get value translated into this locale, if available

Returns:

string The parsed UTF-8 value

Raises:

Returns nil and error message string on error.

key_file:get_boolean (group, key)

Obtain value of a boolean key.

Parameters:

Returns:

boolean The value

Raises:

Returns false and error message string on error.

key_file:get_number (group, key)

Obtain value of a numeric key.

Parameters:

Returns:

number The value

Raises:

Returns nil and error message string on error.

key_file:get_list (group, key[, locale])

Obtain value of a string list key. Note that while key_file:set_list escapes characters such as separators, this function does not handle such escapes correctly. It would be better to just use key_file:raw_get and parse the list out manually if escaped characters might be present.

Parameters:

  • group: string The group name
  • key: string The key
  • locale: string If specified, get value translated into this locale, if available

Returns:

{string ,...}The list of parsed UTF-8 values

Raises:

Returns nil and error message string on error.

key_file:get_boolean_list (group, key)

Obtain value of a boolean list key.

Parameters:

Returns:

{boolean ,...}The list of values

Raises:

Returns nil and error message string on error.

key_file:get_number_list (group, key)

Obtain value of a number list key.

Parameters:

Returns:

{number ,...}The list of values

Raises:

Returns nil and error message string on error.

key_file:get_comment ([group[, key]])

Obtain comment above a key or group.

Parameters:

  • group: string The group name; if unspecified, the first group is used, and key is ignored.
  • key: string The key name; if specified, obtain comment above the key; otherwise, obtain comment above group

Returns:

string |The comment string

Raises:

Returns nil and error message string on error.

key_file:raw_set (group, key, value)

Set raw value of a key.

Parameters:

key_file:set (group, key, value[, locale])

Set value of a key.

Parameters:

  • group: string The group name
  • key: string The key
  • value: string The value
  • locale: string |boolean If a string, set value translated into this locale. Otherwise, if true, set value translated into current locale.
key_file:set_boolean (group, key, value)

Set value of a boolean key.

Parameters:

  • group: string The group name
  • key: string The key
  • value: boolean The value
key_file:set_number (group, key, value)

Set value of a numeric key.

Parameters:

  • group: string The group name
  • key: string The key
  • value: number The value
key_file:set_list (group, key, value[, locale])

Set value of a string list key.

Parameters:

  • group: string The group name
  • key: string The key
  • value: {string ,...} The value
  • locale: string |boolean If a string, set value translated into this locale. Otherwise, if true, set value translated into current locale.
key_file:set_boolean_list (group, key, value)

Set value of a boolean list key.

Parameters:

  • group: string The group name
  • key: string The key
  • value: {boolean ,...} The value
key_file:set_number_list (group, key)

Set value of a number list key.

Parameters:

key_file:set_comment (comment[, group[, key]])

Set comment above a key or group.

Parameters:

  • comment: string The comment
  • group: string The group name; if unspecified, the first group is used, and key is ignored.
  • key: string The key name; if specified, obtain comment above the key; otherwise, obtain comment above group

Returns:

boolean True

Raises:

Returns false and error message string on error.

key_file:remove (group[, key])

Remove a group or key.

Parameters:

  • group: string The group
  • key: string The key. If specified, remove that key. Otherwise, remove the group group.

Returns:

boolean True

Raises:

Returns false and error message string on error.

key_file:remove_comment ([group[, key]])

Remove comment above a key or group.

Parameters:

  • group: string The group name; if unspecified, the first group is used, and key is ignored.
  • key: string The key name; if specified, obtain comment above the key; otherwise, obtain comment above group

Returns:

boolean True

Raises:

Returns false and error message string on error.

Bookmark file parser

bookmark_file_new ()

Create a new, empty bookmark file.

Returns:

bookmark_file The empty bookmark file.

Class bookmark_file

bookmark_file:load_from_file (f[, use_dirs])

Load a file.

Parameters:

  • f: string File name
  • use_dirs: boolean If true, search relative to standard configuration file directories.

Returns:

  1. boolean True
  2. string The actual file name if a directory search was done.

Raises:

Returns false and error message string on error.

bookmark_file:load_from_data (s)

Load data.

Parameters:

Returns:

boolean True

Raises:

Returns false and error message string on error.

bookmark_file:to_data ()

Convert bookmark file to a string.

Returns:

string The bookmark file contents

Raises:

Returns nil and error message string on error.

bookmark_file:to_file (f)

Write bookmark file to a file.

Parameters:

Returns:

boolean True

Raises:

Returns false and error message string on error.

bookmark_file:has_item (uri)

Check if bookmark file has given URI.

Parameters:

Returns:

boolean True if present

bookmark_file:has_group (uri, group)

Check if bookmark file has given URI in a given group.

Parameters:

  • uri: string The URI to find
  • group: string The group to find

Returns:

boolean True if present in group

Raises:

Returns false and error message string on error.

bookmark_file:has_application (uri, app)

Check if bookmark file has given URI registered by a given application.

Parameters:

Returns:

boolean True if registed by application

bookmark_file:__len ()

Get the number of bookmarks. This is the standard Lua # operator, applied to a bookmark file.

Returns:

number The number of bookmarks.

bookmark_file:uris ()

Get all URIs.

Returns:

{string ,...}All URIs.

bookmark_file:title (uri)

Get title for URI

Parameters:

Returns:

string Its title

Raises:

Returns nil and error message string on error.

bookmark_file:description (uri)

Get description for URI

Parameters:

Returns:

string Its description

Raises:

Returns nil and error message string on error.

bookmark_file:mime_type (uri)

Get MIME type for URI

Parameters:

Returns:

string Its MIME type

Raises:

Returns nil and error message string on error.

bookmark_file:is_private (uri)

Get private flag for URI

Parameters:

Returns:

boolean True if private flag set

Raises:

Returns false and error message string on error.

bookmark_file:icon (uri)

Get icon for URI.

Parameters:

Returns:

  1. string The icon URL
  2. string The icon's MIME type

Raises:

Returns nil and error message string on error.

bookmark_file:added (uri)

Get time URI was added.

Parameters:

Returns:

number The time stamp, as seconds from epoch

Raises:

Returns nil and error message string on error.

bookmark_file:modified (uri)

Get time URI was last modified.

Parameters:

Returns:

number The time stamp, as seconds from epoch

Raises:

Returns nil and error message string on error.

bookmark_file:visited (uri)

Get time URI was last visited.

Parameters:

Returns:

number The time stamp, as seconds from epoch

Raises:

Returns nil and error message string on error.

bookmark_file:groups (uri)

Get list of groups to which URI belongs.

Parameters:

Returns:

{string ,...}The list of groups

Raises:

Returns nil and error message string on error.

bookmark_file:applications (uri)

Get list of applications which registered this URI.

Parameters:

Returns:

{string ,...}The list of applications

Raises:

Returns nil and error message string on error.

bookmark_file:boomark_file:app_info (uri, app)

Obtain registration information for application which registered URI.

Parameters:

Returns:

  1. string The command to invoke app on uri
  2. number The number of times app registered uri
  3. number The last time app registered uri

Raises:

Returns nil and error message string on error.

bookmark_file:set_title ([uri], title)

Set title for URI

Parameters:

  • uri: string The URI. If nil, the title of the bookmark file is set.
  • title: string The new title
bookmark_file:set_description ([uri], desc)

Set description for URI

Parameters:

  • uri: string The URI. If nil, the title of the bookmark file is set.
  • desc: string The new description
bookmark_file:set_mime_type (uri, mime_type)

Set MIME type for URI

Parameters:

bookmark_file:set_is_private (uri, private)

Set private flag for URI

Parameters:

  • uri: string The URI
  • private: boolean The new flag
bookmark_file:set_icon (uri, icon, mime_type)

Set icon for URI.

Parameters:

bookmark_file:set_added (uri, time)

Set time URI was added.

Parameters:

  • uri: string The URI
  • time: number The time stamp, as seconds from epoch
bookmark_file:set_modified (uri, time)

Set time URI was modified.

Parameters:

  • uri: string The URI
  • time: number The time stamp, as seconds from epoch
bookmark_file:set_visited (uri, time)

Set time URI was visited.

Parameters:

  • uri: string The URI
  • time: number The time stamp, as seconds from epoch
bookmark_file:set_groups (uri)

Set list of groups to which URI belongs.

Parameters:

Returns:

{string ,...}The list of groups

bookmark_file:set_app_info (uri, app, exec[, rcount[, stamp]])

Set registration information for application which registered URI.

Parameters:

  • uri: string The URI
  • app: string Application name
  • exec: string The command to invoke app on uri (%f == file, %u == uri)
  • rcount: number The number of times app registered uri (absent, nil, or less than 0 to simply increment, or 0 to remove)
  • stamp: number The last time app registered uri (or -1, nil, or absent for current time)

Returns:

boolean True

Raises:

Returns false and error message string on error.

bookmark_file:add_group (uri, group)

Add a group to the list of groups URI belongs to.

Parameters:

bookmark_file:add_application (uri, app, exec)

Add an application to the list of applications that registered this URI.

Parameters:

  • uri: string The URI
  • app: string The application name
  • exec: string The command line to invoke application on URI (%f = file, %u = URI)
bookmark_file:remove_group (uri, group)

Remove a group from the list of groups URI belongs to.

Parameters:

Returns:

boolean True

Raises:

Returns false and error message string on error.

bookmark_file:remove_application (uri, app)

Remove an application from the list of applications that registered this URI.

Parameters:

Returns:

boolean True

Raises:

Returns false and error message string on error.

bookmark_file:remove (uri)

Remove URI.

Parameters:

Returns:

boolean True

Raises:

Returns false and error message string on error.

bookmark_file:move (uri, new)

Change URI, retaining group and application information.

Parameters:

Returns:

boolean True

Raises:

Returns false and error message string on error.

generated by LDoc 1.2

About

Yet another Lua-to-glib binding.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published