Lua functions

See: http://algernon.roboticoverlords.org or the REPL help for a list of functions that has been updated to Algernon 0.87.

These functions are specific to the combination of Lua and Algernon. There are also a number of functions available for regular Lua.

Algernon uses an implementation of Lua which currently supports Lua 5.1.

Basic Lua functions

// Return the version string for the server.
version() -> string

// Sleep the given number of seconds (can be a float).
sleep(number)

// Log the given strings as information. Takes a variable number of strings.
log(...)

// Log the given strings as a warning. Takes a variable number of strings.
warn(...)

// Log the given strings as an error. Takes a variable number of strings.
err(...)

Lua functions for handling requests

// Set the Content-Type for a page.
content(string)

// Return the requested HTTP method (GET, POST etc).
method() -> string

// Output text to the browser/client. Takes a variable number of strings.
print(...)

// Return the requested URL path.
urlpath() -> string

// Return the HTTP header in the request, for a given key, or an empty string.
header(string) -> string

// Set an HTTP header given a key and a value.
setheader(string, string)

// Return the HTTP headers, as a table.
headers() -> table

// Return the HTTP body in the request (will only read the body once, since it's streamed).
body() -> string

// Set a HTTP status code (like 200 or 404). Must come before other output.
status(number)

// Set a HTTP status code and output a message (optional).
error(number[, string])

// Return the directory where the script is running. If a filename (optional) is given, then the path to where the script is running, joined with a path separator and the given filename, is returned.
scriptdir([string]) -> string

// Return the directory where the server is running. If a filename (optional) is given, then the path to where the server is running, joined with a path separator and the given filename, is returned.
serverdir([string]) -> string

// Serve a file that exists in the same directory as the script.
serve(string)

// Return a table with keys and values as given in a posted form, or as given in the URL (`/some/page?x=7` makes the key `x` with the value `7` available).
formdata() -> table

// Redirect to a relative URL
redirect(string)

// Transmit what has been outputted so far, to the client.
flush()

Lua functions for formatted output

// Output Markdown to the browser/client. The given text is converted from Markdown to HTML. Takes a variable number of strings.
mprint(...)

// Output Amber to the browser/client. The given text is converted from Amber to HTML. Takes a variable number of strings.
aprint(...)

// Output GCSS to the browser/client. The given text is converted from GCSS to CSS. Takes a variable number of strings.
gprint(...)

// Output JSX to the browser/client. The given text is converted from JSX to JavaScript. Takes a variable number of strings.
jprint(...)

Tips:

  • Use JFile(filename) to use or store a JSON document in the same directory as the Lua script.
  • A JSON path is on the form x.mapkey.listname[2].mapkey, where [, ] and . have special meaning. It can be used for pinpointing a specific place within a JSON document. It's a bit like a simple version of XPath, but for JSON.
  • Use tostring(userdata) to fetch the JSON string from the JFile object.
// Use, or create, a JSON document/file.
JFile(filename) -> userdata

// Takes a JSON path. Returns a string value, or an empty string.
jfile:get(string) -> string

// Takes a JSON path (optional) and JSON data to be added to the list.
// The JSON path must point to a list, if given, unless the JSON file is empty.
// Returns true on success.
jfile:add([string, ]string) -> bool

// Take a JSON path and a string value. Changes the entry. Returns true on success.
jfile:set(string, string) -> bool

// Remove a key in a map. Takes a JSON path, returns true on success.
jfile:delkey(string) -> bool

// Convert a Lua table, where keys are strings and values are strings or numbers, to JSON.
// Takes an optional number of spaces to indent the JSON data.
toJSON(table[, number]) -> string

Lua functions for plugins

// Load a plugin given the path to an executable. Returns true on success. Will return the plugin help text if called on the Lua prompt.
Plugin(string)

// Returns the Lua code as returned by the Lua.Code function in the plugin, given a plugin path. May return an empty string.
PluginCode(string) -> string

// Takes a plugin path, function name and arguments. Returns an empty string if the function call fails, or the results as a JSON string if successful.
CallPlugin(string, string, ...) -> string

Lua functions for code libraries

These functions can be used in combination with the plugin functions for storing Lua code returned by plugins when serverconf.lua is loaded, then retrieve the Lua code later, when handling requests. The code is stored in the database.

// Create or uses a code library object. Optionally takes a data structure name as the first parameter.
CodeLib([string]) -> userdata

// Given a namespace and Lua code, add the given code to the namespace. Returns true on success.
codelib:add(string, string) -> bool

// Given a namespace and Lua code, set the given code as the only code in the namespace. Returns true on success.
codelib:set(string, string) -> bool

// Given a namespace, return Lua code, or an empty string.
codelib:get(string) -> string

// Import (eval) code from the given namespace into the current Lua state. Returns true on success.
codelib:import(string) -> bool

// Completely clear the code library. Returns true on success.
codelib:clear() -> bool

Lua functions for file uploads

// Creates a file upload object. Takes a form ID (from a POST request) as the first parameter.
// Takes an optional maximum upload size (in MiB) as the second parameter.
// Returns nil and an error string on failure, or userdata and an empty string on success.
UploadedFile(string[, number]) -> userdata, string

// Return the uploaded filename, as specified by the client
uploadedfile:filename() -> string

// Return the size of the data that has been recevied
uploadedfile:size() -> number

// Return the mime type of the uploaded file, as specified by the client
uploadedfile:mimetype() -> string

// Save the uploaded data locally. Takes an optional filename. Returns true on success.
uploadedfile:save([string]) -> bool

// Save the uploaded data as the client-provided filename, in the specified directory.
// Takes a relative or absolute path. Returns true on success.
uploadedfile:savein(string)  -> bool

Lua functions for the file cache

// Return information about the file cache.
CacheInfo() -> string

// Clear the file cache.
ClearCache()

Lua functions for data structures

Set
// Get or create a database-backed Set (takes a name, returns a set object)
Set(string) -> userdata

// Add an element to the set
set:add(string)

// Remove an element from the set
set:del(string)

// Check if a set contains a value
// Returns true only if the value exists and there were no errors.
set:has(string) -> bool

// Get all members of the set
set:getall() -> table

// Remove the set itself. Returns true on success.
set:remove() -> bool

// Clear the set
set:clear() -> bool
List
// Get or create a database-backed List (takes a name, returns a list object)
List(string) -> userdata

// Add an element to the list
list:add(string)

// Get all members of the list
list:getall() -> table

// Get the last element of the list
// The returned value can be empty
list:getlast() -> string

// Get the N last elements of the list
list:getlastn(number) -> table

// Remove the list itself. Returns true on success.
list:remove() -> bool

// Clear the list. Returns true on success.
list:clear() -> bool
HashMap
// Get or create a database-backed HashMap (takes a name, returns a hash map object)
HashMap(string) -> userdata

// For a given element id (for instance a user id), set a key
// (for instance "password") and a value.
// Returns true on success.
hash:set(string, string, string) -> bool

// For a given element id (for instance a user id), and a key
// (for instance "password"), return a value.
// Returns a value only if they key was found and if there were no errors.
hash:get(string, string) -> string

// For a given element id (for instance a user id), and a key
// (for instance "password"), check if the key exists in the hash map.
// Returns true only if it exists and there were no errors.
hash:has(string, string) -> bool

// For a given element id (for instance a user id), check if it exists.
// Returns true only if it exists and there were no errors.
hash:exists(string) -> bool

// Get all keys of the hash map
hash:getall() -> table

// Remove a key for an entry in a hash map
// (for instance the email field for a user)
// Returns true on success
hash:delkey(string, string) -> bool

// Remove an element (for instance a user)
// Returns true on success
hash:del(string) -> bool

// Remove the hash map itself. Returns true on success.
hash:remove() -> bool

// Clear the hash map. Returns true on success.
hash:clear() -> bool
KeyValue
// Get or create a database-backed KeyValue collection (takes a name, returns a key/value object)
KeyValue(string) -> userdata

// Set a key and value. Returns true on success.
kv:set(string, string) -> bool

// Takes a key, returns a value.
// Returns an empty string if the function fails.
kv:get(string) -> string

// Takes a key, returns the value+1.
// Creates a key/value and returns "1" if it did not already exist.
// Returns an empty string if the function fails.
kv:inc(string) -> string

// Remove a key. Returns true on success.
kv:del(string) -> bool

// Remove the KeyValue itself. Returns true on success.
kv:remove() -> bool

// Clear the KeyValue. Returns true on success.
kv:clear() -> bool

Lua functions for handling users and permissions

// Check if the current user has "user" rights
UserRights() -> bool

// Check if the given username exists
HasUser(string) -> bool

// Get the value from the given boolean field
// Takes a username and fieldname
BooleanField(string, string) -> bool

// Save a value as a boolean field
// Takes a username, fieldname and boolean value
SetBooleanField(string, string, bool)

// Check if a given username is confirmed
IsConfirmed(string) -> bool

// Check if a given username is logged in
IsLoggedIn(string) -> bool

// Check if the current user has "admin rights"
AdminRights() -> bool

// Check if a given username is an admin
IsAdmin(string) -> bool

// Get the username stored in a cookie, or an empty string
UsernameCookie() -> string

// Store the username in a cookie, returns true on success
SetUsernameCookie(string) -> bool

// Clear the login cookie
ClearCookie()

// Get a table containing all usernames
AllUsernames() -> table

// Get the email for a given username, or an empty string
Email(string) -> string

// Get the password hash for a given username, or an empty string
PasswordHash(string) -> string

// Get all unconfirmed usernames
AllUnconfirmedUsernames() -> table

// Get a confirmation code that can be given to a user,
// or an empty string. Takes a username.
ConfirmationCode(string) -> string

// Add a user to the list of unconfirmed users
// Takes a username and a confirmation code
AddUnconfirmed(string, string)

// Remove a user from the list of unconfirmed users
// Takes a username
RemoveUnconfirmed(string)

// Mark a user as confirmed
// Takes a username
MarkConfirmed(string)

// Removes a user
// Takes a username
RemoveUser(string)

// Make a user an admin
// Takes a username
SetAdminStatus(string)

// Make an admin user a regular user
// Takes a username
RemoveAdminStatus(string)

// Add a user
// Takes a username, password and email
AddUser(string, string, string)

// Set a user as logged in on the server (not cookie)
// Takes a username
SetLoggedIn(string)

// Set a user as logged out on the server (not cookie)
// Takes a username
SetLoggedOut(string)

// Log in a user, both on the server and with a cookie
// Takes a username
Login(string)

// Log in a user, both on the server and with a cookie
// Takes a username. Returns true if the cookie was set successfully.
CookieLogin(string) -> bool

// Log out a user, on the server (which is enough)
// Takes a username
Logout(string)

// Get the current username, from the cookie
Username() -> string

// Get the current cookie timeout
// Takes a username
CookieTimeout(string) -> number

// Set the current cookie timeout
// Takes a timeout number, measured in seconds
SetCookieTimeout(number)

// Get the current password hashing algorithm (bcrypt, bcrypt+ or sha256)
PasswordAlgo() -> string

// Set the current password hashing algorithm (bcrypt, bcrypt+ or sha256)
// ‘bcrypt+‘ accepts bcrypt or sha256 for old passwords, but will only use
// bcrypt for new passwords.
SetPasswordAlgo(string)

// Hash the password
// Takes a username and password (username can be used for salting sha256)
HashPassword(string, string) -> string

// Check if a given username and password is correct
// Takes a username and password
CorrectPassword(string, string) -> bool

// Checks if a confirmation code is already in use
// Takes a confirmation code
AlreadyHasConfirmationCode(string) -> bool

// Find a username based on a given confirmation code,
// or returns an empty string. Takes a confirmation code
FindUserByConfirmationCode(string) -> string

// Mark a user as confirmed
// Takes a username
Confirm(string)

// Mark a user as confirmed, returns true on success
// Takes a confirmation code
ConfirmUserByConfirmationCode(string) -> bool

// Set the minimum confirmation code length
// Takes the minimum number of characters
SetMinimumConfirmationCodeLength(number)

// Generates a unique confirmation code, or an empty string
GenerateUniqueConfirmationCode() -> string

Lua functions that are available for server configuration files

// Set the default address for the server on the form [host][:port].
// May be useful in Algernon application bundles (.alg or .zip files).
SetAddr(string)

// Reset the URL prefixes and make everything *public*.
ClearPermissions()

// Add an URL prefix that will have *admin* rights.
AddAdminPrefix(string)

// Add an URL prefix that will have *user* rights.
AddUserPrefix(string)

// Provide a lua function that will be used as the permission denied handler.
DenyHandler(function)

// Return a string with various server information.
ServerInfo() -> string

// Direct the logging to the given filename. If the filename is an empty
// string, direct logging to stderr. Returns true on success.
LogTo(string) -> bool

// Returns the version string for the server.
version() -> string

// Logs the given strings as INFO. Takes a variable number of strings.
log(...)

// Logs the given strings as WARN. Takes a variable number of strings.
warn(...)

// Logs the given string as ERROR. Takes a variable number of strings.
err(...)

// Provide a lua function that will be run once, when the server is ready to start serving.
OnReady(function)

// Use a Lua file for setting up HTTP handlers instead of using the directory structure.
ServerFile(string) -> bool

Functions that are only available for Lua server files

This function is only available when a Lua script is used instead of a server directory, or from Lua files that are specified with the ServerFile function in the server configuration.

// Given an URL path prefix (like "/") and a Lua function, set up an HTTP handler.
// The given Lua function should take no arguments, but can use all the Lua functions for handling requests, like `content` and `print`.
handle(string, function)

// Given an URL prefix (like "/") and a directory, serve the files and directories.
servedir(string, string)