Introduction
Welcome to the Iguana API reference section! The following built-in modules are available for use within your Iguana Translator scripts.
Select the Iguana version above and then browse or search for specific modules to see usage information and code examples. Enjoy.
ack
ack.generate
Example Usage of ack.generate(msg)
local Ack, Result = ack.generate(Data)
Usage
ack.generate(msg)
Generate a 'Fast-ACK' for the given message. Creates an ACK message using Iguana's Fast ACK internal acknowledgment message generator. (This is identical to the Fast ACK that can be specified in an LLP Listener source component.)
Note: This function is intended to be used in the script of an LLP Listener Source with ACKnowledgement Settings>ACK = "Translator".
Required Parameters
- msg: The HL7 message to be ACKed string.
Returns
- The generated ACK string.
- A Boolean indicating success or failure (true if data was copied from the message to the ACK - false otherwise) boolean.
For More Information
ack.send
Example Usage of ack.send(ack)
ack.send(Ack)
Usage
ack.send(ack)
Specify the ACK message to send (or nil), it can be created using ack.generate() or built from scratch. If given an empty string or nil, no ACK will be sent.
Note: > This function will only work in the script of an LLP Listener Source with ACKnowledgement Setting>ACK = "Translator".
Required Parameters
- ack: The ACK to send string.
For More Information
cache
cache.load
Example Usage of cache.load()
local cd = cache.load()
-- do not do this as the condition will always be true in production if not cache.load() then -- do something I do not want to do in production end
Usage
cache.load()
Load a value associated with the current sample message (returns nil when running in production).
This can be useful if you have data which is very slow to create, or perhaps not available on your development machine. Once the data is associated with a message (using cache.save
) it can be accessed at anytime in the editor using using cache.load()
.
Returns
- Either the node tree or string associated with the current sample message node tree or string.
- Or nil if none exists or if the script is running in production nil.
cache.save
Example Usage of cache.save(Data)
cache.save('Add you data string here') local cd = cache.load() --> returns "Add your data string here"
Usage
cache.save(Data)
Save a value associated with the current sample message (does nothing outside the editor).
This can be useful if you have data which is very slow to create, or perhaps not available on your development machine. Once the data is associated with a message it can be accessed at anytime int the editor using using cache.load()
.
Required Parameters
- Data: The node tree or string to save node tree or string.
chm
chm.fromXml
Example Usage of chm.fromXml{vmd=<value>, data=<value>}
local Data = chm.fromXml{vmd='example.vmd', data=XmlData}
Usage
chm.fromXml{vmd=<value>, data=<value>}
If you need to be able to convert HL7 to and from the official XML formats for HL7 version 2.X this function may be useful. This function will convert an XML message into a HL7 string. The style of conversion will depend on how the vmd is configured. This exposes Chameleon XML to HL7 conversion functionality. The reverse of this function is chm.toXml.
Required Parameters
- vmd: The name of the VMD file containing the configuration of the XML conversion string.
- data: The XML string to be converted to HL7 (this has to conform to one of the strict formats as documented in the manual.) string.
Returns
- A string populated with the HL7 message coming back from the conversion.
For More Information
- The chm module - Legacy parsing using Chameleon vmd files
- Interfaces for invoking legacy Chameleon functionality
- XML <--> HL7 Conversion with Chameleon
chm.parse
Example Usage of chm.parse{vmd=<value>, data=<value>}
local Out = chm.parse{vmd='example.vmd', data=Msg}
Usage
chm.parse{vmd=<value>, data=<value>}
Invokes a Chameleon style parse using a VMD file. The complete mapping from HL7 to tables is performed, including the execution of the VMD file's Python scripts.
Note: The API is intended to to be used for comparing the output of older Chameleon interfaces to equivalent Lua mapping code. This is useful for regression testing or reusing interfaces implemented with Chameleon.
Required Parameters
- vmd: The name of the VMD file containing the message definitions string.
- data: The message to be parsed (this is usually the message that is passed to the main function) string.
Returns
- A table node tree populated with the parsed data chm_table node tree.
For More Information
- The chm module - Legacy parsing using Chameleon vmd files
- Interfaces for invoking legacy Chameleon functionality
- Node types for Iguana node trees
chm.toXml
Example Usage of chm.toXml{vmd=<value>, data=<value>}
local Out = chm.toXml{vmd='example.vmd', data=Msg}
Usage
chm.toXml{vmd=<value>, data=<value>}
If you need to be able to convert HL7 to and from the official XML formats for HL7 version 2.X this function may be useful. This function will convert an HL7 message into a XML string. The style of conversion will depend on how the vmd is configured. This exposes Chameleon HL7 to XML conversion functionality. The reverse of this function is chm.fromXml.
Required Parameters
- vmd: The name of the VMD file containing the configuration of the XML conversion string.
- data: The HL7 message to be converted to XML (this is usually the message that is passed to the main function) string.
Returns
- A string populated with the XML coming back from the conversion.
For More Information
- The chm module - Legacy parsing using Chameleon vmd files
- Interfaces for invoking legacy Chameleon functionality
- XML <--> HL7 Conversion with Chameleon
chm.transform
Example Usage of chm.transform{vmd=<value>, data=<value>, ...}
local msg, msg_type, python_out = chm.transform{ vmd='legacy.vmd', data=Data, config='default' }
Usage
chm.transform{vmd=<value>, data=<value>, ...}
Performs a legacy (Chameleon style) VMD transformation. Perform a legacy VMD transformation.
Note: The API is intended to to be used for comparing the output of older Chameleon interfaces to equivalent Lua mapping code. This is useful for regression testing reusing legacy filters implemented with Chameleon.
Required Parameters
- vmd: The VMD to use string.
- data: The message to transform string.
- config: (scripted only) The configuration to use string.
- in_config: (graphical only) The inbound configuration string.
- out_config: (graphical only) The outbound configuration string.
Returns
- The transformed message string.
- The message name string.
- All Python output string.
For More Information
- The chm module - Legacy parsing using Chameleon vmd files
- Interfaces for invoking legacy Chameleon functionality
db
db.begin
Example Usage of db.begin{api=<value>, name=<value>, ...}
db.begin{ api=db.MY_SQL, name='test@localhost', user='root', password='secret' }
Usage
db.begin{api=<value>, name=<value>, ...}
Deprecated: use conn:begin{} instead: conn = db.connect{api=db.MY_SQL, name='test@localhost',user='root', password='secret'}
conn:begin{}
Begins a transaction on the database (if transactions are supported by the database engine). If a transaction is already in progress, the behaviour is database specific.
Probably the most commonly used database that does not support transactions is MySQL when it used with the MyISAM database engine (the newer InnoDB engine for MySQL has transaction support).
Note: If transactions are not supported, then db.begin{}
, db.commit{}
have no effect. This is not regarded as an error condition, so no error is raised in the Translator. When transactions are not supported, then each individual SQL statement is committed separately. For example: A call to and
db.rollback{}db.execute{}
that contains three SQL statements, will be run as three independent commands (one for each SQL statement).
Required Parameters
- api: Set to the database type (e.g. db.MY_SQL or db.SQL_SERVER) integer constant.
- name: Database name/address. For db.SQLITE, this is the database file name string.
- user: User name (neither required nor used for db.SQLITE) string.
- password: Password (neither required nor used for db.SQLITE) string.
Optional Parameters
- live: If true, the begin transaction will be executed in the editor (default live = true) boolean.
- use_unicode: If true, Unicode will be used when communicating with the database boolean.
- timeout: Maximum time in seconds allowed for the query (0 for infinite) integer.
Note: Timeout is supported only for ODBC based connections and defaults to 5 minutes.
For More Information
- The db_connection module - new database methods
- The db module - old style database functions
- Mapping To/From Databases
db.close
Example Usage of db.close{api=<value>, name=<value>, ...}
db.close{ api=db.MY_SQL, name='test@localhost', user='root', password='secret' }
Usage
db.close{api=<value>, name=<value>, ...}
Deprecated: use conn:close{} instead: conn = db.connect{api=db.MY_SQL, name='test@localhost',user='root', password='secret'}
conn:close{}
Close the connection identified by the given parameters, if it exists.
Required Parameters
- api: Set to the database type (e.g. db.MY_SQL or db.SQL_SERVER) integer constant.
- name: Database name/address. For db.SQLITE, this is the database file name string.
- user: User name (neither required nor used for db.SQLITE) string.
- password: Password (neither required nor used for db.SQLITE) string.
Optional Parameters
- live: If true, the close will be executed in the editor (default live = true) boolean.
- use_unicode: If true, Unicode will be used when communicating with the database boolean.
- timeout: Maximum time in seconds allowed for the query (0 for infinite) integer.
Note: Timeout is supported only for ODBC based connections and defaults to 5 minutes.
For More Information
- The db_connection module - new database methods
- The db module - old style database functions
- Mapping To/From Databases
db.commit
Example Usage of db.commit{api=<value>, name=<value>, ...}
db.commit{ api=db.MY_SQL, name='test@localhost', user='root', password='secret' }
Usage
db.commit{api=<value>, name=<value>, ...}
Deprecated: use conn:commit{} instead: conn = db.connect{api=db.MY_SQL, name='test@localhost',user='root', password='secret'}
conn:commit{}
Commits a transaction, if one has begun (if transactions are supported by the database engine).
Probably the most commonly used database that does not support transactions is MySQL when it used with the MyISAM database engine (the newer InnoDB engine for MySQL has transaction support).
Note: If transactions are not supported, then db.begin{}
, db.commit{}
have no effect. This is not regarded as an error condition, so no error is raised in the Translator. When transactions are not supported, then each individual SQL statement is committed separately. For example: A call to and
db.rollback{}db.execute{}
that contains three SQL statements, will be run as three independent commands (one for each SQL statement).
Required Parameters
- api: Set to the database type (e.g. db.MY_SQL or db.SQL_SERVER) integer constant.
- name: Database name/address. For db.SQLITE, this is the database file name string.
- user: User name (neither required nor used for db.SQLITE) string.
- password: Password (neither required nor used for db.SQLITE) string.
Optional Parameters
- live: If true, the commit will be executed in the editor (default live = true) boolean.
- use_unicode: If true, Unicode will be used when communicating with the database boolean.
- timeout: Maximum time in seconds allowed for the query (0 for infinite) integer.
Note: Timeout is supported only for ODBC based connections and defaults to 5 minutes.
For More Information
- The db_connection module - new database methods
- The db module - old style database functions
- Mapping To/From Databases
db.connect
Example Usage of db.connect{api=<value>, name=<value>, ...}
local Conn = db.connect{ api=db.MY_SQL, name='test@localhost', user='fred', password='secret'}
Usage
db.connect{api=<value>, name=<value>, ...}
Opens a database connection and returns a connection handle. By default the returned connection is live and allows database methods to run in the editor.
- If db.connect live = false then database operations do not execute in the editor.
- If live = true (the default) database operations will execute in the editor, based on the method default or specified live setting.
Required Parameters
- api: set to the database type (e.g. db.MY_SQL or db.SQL_SERVER) integer constant.
- name: database name/address. For db.SQLITE, this is the database file name string.
- user: user name (neither required nor used for db.SQLITE) string.
- password: password (neither required nor used for db.SQLITE) string.
Optional Parameters
- live: if true, the connection is opened in the editor (defaults to true) boolean
- use_unicode: if true, Unicode will be used when communicating with the database boolean.
- timeout: maximum time in seconds allowed for the query (0 for infinite). string.
Note: Timeout is supported only for ODBC based connections and defaults to 5 minutes.
For More Information
- The db_connection module - new database methods
- The db module - old style database functions
- Mapping To/From Databases
db.db_connection
db.db_connection.begin
Example Usage of conn:begin{[live=<value>]}
local conn = db.connect{ api=db.MY_SQL, name='test@localhost', user='root', password='secret' } conn:begin{}
Usage
conn:begin{[live=<value>]}
Begins a transaction on the database (if transactions are supported by the database engine). If a transaction is already in progress, the behaviour is database specific.
Probably the most commonly used database that does not support transactions is MySQL when it used with the MyISAM database engine (the newer InnoDB engine for MySQL has transaction support).
Note: If transactions are not supported, then conn:begin{}
, conn:commit{}
have no effect. This is not regarded as an error condition, so no error is raised in the Translator. When transactions are not supported, then each individual SQL statement is committed separately. For example: A call to and
conn:rollback{}conn:execute{}
that contains three SQL statements, will be run as three independent commands (one for each SQL statement).
Optional Parameters
- live: if true, the command (begin transaction) will be executed in the editor (default live = true) boolean.
For More Information
- The db_connection module - new database methods
- The db module - old style database functions
- Mapping To/From Databases
- Understanding Lua OO syntax: what the colon operator means
db.db_connection.check
Example Usage of conn:check()
if not Conn or not Conn:check() then if Conn then Conn:close() end --close off any stale connection Conn = db.connect{ api=db.MY_SQL, name='test@localhost', user='root', password='secret' } end
Usage
conn:check()
Checks whether database is accessible. The connection must be open and responsive for check() to return true. Inside the Translator, check() for a non-live connection will return false.
Returns
- whether database is accessible boolean.
For More Information
- The db_connection module - new database methods
- The db module - old style database functions
- Mapping To/From Databases
- Understanding Lua OO syntax: what the colon operator means
db.db_connection.close
Example Usage of conn:close()
local conn = db.connect{ api=db.MY_SQL, name='test@localhost', user='root', password='secret' } local res = conn:query{sql = 'SHOW TABLES'} conn:close()
Usage
conn:close()
Closes the connection, and causes errors to be thrown for any subsequent database operations using the connection handle.
For More Information
- The db_connection module - new database methods
- The db module - old style database functions
- Mapping To/From Databases
- Understanding Lua OO syntax: what the colon operator means
db.db_connection.commit
Example Usage of conn:commit{[live=<value>]}
local conn = db.connect{ api=db.MY_SQL, name='test@localhost', user='root', password='secret' } conn:begin{} conn:execute{ sql='INSERT INTO Patient VALUES("Fred", "Smith")' }conn:commit{}
Usage
conn:commit{[live=<value>]}
Commits a transaction, if one has begun (if transactions are supported by the database engine).
Probably the most commonly used database that does not support transactions is MySQL when it used with the MyISAM database engine (the newer InnoDB engine for MySQL has transaction support).
Note: If transactions are not supported, then conn:begin{}
, conn:commit{}
have no effect. This is not regarded as an error condition, so no error is raised in the Translator. When transactions are not supported, then each individual SQL statement is committed separately. For example: A call to and
conn:rollback{}conn:execute{}
that contains three SQL statements, will be run as three independent commands (one for each SQL statement).
Optional Parameters
- live: if true, the commit will be executed in the editor (default live = true) boolean.
For More Information
- The db_connection module - new database methods
- The db module - old style database functions
- Mapping To/From Databases
- Understanding Lua OO syntax: what the colon operator means
db.db_connection.execute
Example Usage of conn:execute{sql=<value> [, live=<value>]} or conn:execute(sql)
local conn = db.connect{api=db.MY_SQL, name='test@localhost', user='root', password='secret'}
conn:execute('INSERT INTO Patient (FirstName, LastName) VALUES("Fred", "Smith")')
-- Return an array containing multiple results sets, one for each query
-- Note: Some DBs do not support multiple queries in a single "sql" string
local Result = conn:execute{sql = 'SELECT * FROM Patient; SELECT * FROM Kin', live = true}
-- trap the database error thrown byconn:execute
-- Note: The "conn.execute" syntax is required to pass the "conn" object to pcall (conn:execute does not work)
-- try to insert a duplicate key = "Primary Key Violation" error
local TryDuplicateKey = 'INSERT INTO [dbo].[Patient] (Id,FirstName, LastName) VALUES (1, 'Fred', 'Smith')'
local Success, Error = pcall(conn.execute, conn, {sql = TryDuplicateKey, live = true}) -- "conn" as 1st param
local Success, Error = pcall(conn:execute, {sql = TryDuplicateKey, live = true}) -- this does not work
trace(Success) -- false in this case
trace(Error) -- view the pcall Error return as a table
local DbError = Error.message -- copy the DB error message string from Error
trace(DbError) -- view the DB error message
Usage
conn:execute{sql=<value> [, live=<value>]} or conn:execute(sql)
Executes an ad hoc SQL statement that can alter the database.
Both conn:execute()
and conn:query()
throw errors if a database error is encountered. The errors are regular Lua errors and will cause the execution of the script to halt, unless they are caught by Lua error handling using pcall
or xpcall
. The error thrown is a table with two fields:
- message: a string with the description of the error
- code: an integer error code returned by the database.
Currently, error codes from ODBC sources and MySQL databases are supported.
Required Parameters
- sql: a string containing the SQL statement string.
Optional Parameters
- live: if true, the statement will be executed in the editor (default live = false) boolean.
Returns
- For queries: the first result set result_set node tree.
- For queries: An array containing all the result sets table.
For More Information
- The db_connection module - new database methods
- The db module - old style database functions
- db conn execute{} - Writing to a Database
- Mapping To/From Databases
- Node types for Iguana node trees
- Understanding Lua OO syntax: what the colon operator means
db.db_connection.info
Example Usage of conn:info()
conn_info = conn:info()
Usage
conn:info()
Returns a table with the database connection parameters.
Returns
- A table with the database connection parameters table.
For More Information
- The db_connection module - new database methods
- The db module - old style database functions
- Mapping To/From Databases
- Understanding Lua OO syntax: what the colon operator means
db.db_connection.merge
Example Usage of conn:merge{data=<value> [, bulk_insert=<value>] [, ...]} or conn:merge(data)
conn:merge{ data=Out, bulk_insert=true, transaction=false }
Usage
conn:merge{data=<value> [, bulk_insert=<value>] [, ...]} or conn:merge(data)
Merges the database tables created by db.tables() into the database.
Required Parameters
- data: set to a node table tree created using db.tables node tree.
Optional Parameters
- bulk_insert: set to true to use bulk insert logic boolean.
- transaction: set to false to disable inserting/updating all rows as a transaction boolean.
- live: if true, the merge will be executed in the editor (default live = false) boolean.
For More Information
- The db_connection module - new database methods
- The db module - old style database functions
- Mapping To/From Databases
- Understanding Lua OO syntax: what the colon operator means
db.db_connection.query
Example Usage of conn:query{sql=<value> [, live=<value>]} or conn:query(sql)
local conn = db.connect{api=db.MY_SQL, name='test@localhost', user='root', password='secret'}
local Result = conn:query('SELECT * FROM Patient WHERE Flag = "F"')
-- Return an array containing multiple results sets, one for each query
-- Note: Some DBs do not support multiple queries in a single "sql" string
local Result = conn:query('SELECT * FROM Patient; SELECT * FROM Kin')
-- trap the database error thrown byconn:query
-- Note: The "conn.query" syntax is required to pass the "conn" object to pcall (conn:query does not work)
local Success, Error = pcall(conn.query, conn, {sql = 'Select * from Not_a_table'}) -- "conn" as 1st param
local Success, Error = pcall(conn:query, {sql = 'Select * from Not_a_table'}) -- this does not work
trace(Success) -- false in this case
trace(Error) -- view the pcall Error return as a table
local DbError = Error.message -- copy the DB error message string from Error
trace(DbError) -- view the DB error message
Usage
conn:query{sql=<value> [, live=<value>]} or conn:query(sql)
Executes an ad hoc SQL query against a database.
Insert or update statements are not allowed (for these, use the conn:execute
method).
Both conn:query()
and conn:execute()
throw errors if a database error is encountered. The errors are regular Lua errors and will cause the execution of the script to halt, unless they are caught by Lua error handling using pcall
or xpcall
. The error thrown is a table with two fields:
- message: a string with the description of the error
- code: an integer error code returned by the database.
Currently, error codes from ODBC sources and MySQL databases are supported.
Required Parameters
- sql: a string containing the SQL select statement
Optional Parameters
- live: if true, the statement will be executed in the editor (default live = true) boolean.
Returns
- The first result set result_set node tree.
- An array containing all the result sets table.
For More Information
- The db_connection module - new database methods
- The db module - old style database functions
- Mapping To/From Databases
- Node types for Iguana node trees
- Understanding Lua OO syntax: what the colon operator means
db.db_connection.quote
Example Usage of conn:quote(data)
local Sql = 'SELECT * FROM MyTable WHERE Name = '..conn:quote(MyString)
Usage
conn:quote(data)
Accepts a single string argument, and returns an escaped string surrounded by single quotes. Escaping is database specific, characters are escaped specifically to match each database API.
Required Parameters
- data: The string to escape string.
Returns
- An escaped string surrounded by single quotes string.
For More Information
- The db_connection module - new database methods
- The db module - old style database functions
- Mapping To/From Databases
- Understanding Lua OO syntax: what the colon operator means
db.db_connection.rollback
Example Usage of conn:rollback{[live=<value>]}
conn:rollback{}
Usage
conn:rollback{[live=<value>]}
Rollback a transaction, if one has begun (if transactions are supported by the database engine).
Probably the most commonly used database that does not support transactions is MySQL when it used with the MyISAM database engine (the newer InnoDB engine for MySQL has transaction support).
Note: If transactions are not supported, then conn:begin{}
, conn:commit{}
have no effect. This is not regarded as an error condition, so no error is raised in the Translator. When transactions are not supported, then each individual SQL statement is committed separately. For example: A call to and
conn:rollback{}conn:execute{}
that contains three SQL statements, will be run as three independent commands (one for each SQL statement).
Optional Parameters
- live: if true, the rollback will be executed in the editor (default live = true) boolean.
For More Information
- The db_connection module - new database methods
- The db module - old style database functions
- Mapping To/From Databases
- Understanding Lua OO syntax: what the colon operator means
db.execute
Example Usage of db.execute{api=<value>, name=<value>, ...}
db.execute{ api=db.MY_SQL, name='test@localhost', user='fred', password='secret', sql='INSERT INTO Patient (FirstName, LastName) VALUES("Fred", "Smith")' }
-- Return an array containing multiple results sets, one for each query
-- Note: Some DBs do not support multiple queries in a single "sql" string
local Result = db.execute{
api=db.MY_SQL, name='test@localhost',
user='fred', password='secret', live = true,
sql = 'SELECT * FROM Patient; SELECT * FROM Kin'
}
-- trap the database error thrown bydb.execute
-- try to insert a duplicate key = "Primary Key Violation" error
local Success, Error = pcall(
db.execute,{
api=db.MY_SQL, name='test@localhost',
user='fred', password='secret', live = true,
sql = 'INSERT INTO [dbo].[Patient] (Id,FirstName, LastName) VALUES (1, "Fred", "Smith")'
}
)
trace(Success) -- false in this case
trace(Error) -- view the pcall Error return as a table
local DbError = Error.message -- copy the DB error message string from Error
trace(DbError) -- view the DB error message
Usage
db.execute{api=<value>, name=<value>, ...}
Recommended best practice - use conn:execute{} instead: conn = db.connect{api=db.MY_SQL, name='test@localhost',user='root', password='secret'}
conn:execute{}
Executes an ad hoc SQL statement that can alter the database.
Both db.execute()
and db.query()
throw errors if a database error is encountered. The errors are regular Lua errors and will cause the execution of the script to halt, unless they are caught by Lua error handling using pcall
or xpcall
. The error thrown is a table with two fields:
- message: a string with the description of the error
- code: an integer error code returned by the database.
Currently, error codes from ODBC sources and MySQL databases are supported.
Required Parameters
- api: Set to the database type (e.g. db.MY_SQL or db.SQL_SERVER) integer constant.
- name: Database name/address. For db.SQLITE, this is the database file name string.
- user: User name (neither required nor used for db.SQLITE) string.
- password: Password (neither required nor used for db.SQLITE) string.
- sql: The SQL statement string.
Optional Parameters
- live: If true, the statement will be executed in the editor (default live = false) boolean.
- use_unicode: If true, Unicode will be used when communicating with the database boolean.
- timeout: Maximum time in seconds allowed for the query (0 for infinite) integer.
Note: Timeout is supported only for ODBC based connections and defaults to 5 minutes.
Returns
- For queries: the first result set result_set node tree.
- An array containing all the result sets table.
For More Information
- The db_connection module - new database methods
- The db module - old style database functions
- db conn execute{} - Writing to a Database (
db.execute
return values and error handling work in the same way) - Mapping To/From Databases
- Node types for Iguana node trees
db.merge
Example Usage of db.merge{api=<value>, name=<value>, ...}
db.merge{ api=db.MY_SQL, name='test@localhost', user='root', password='secret', data=Out, bulk_insert=true, transaction=false }
Usage
db.merge{api=<value>, name=<value>, ...}
Recommended best practice - use conn:merge{} instead: conn = db.connect{api=db.MY_SQL, name='test@localhost',user='root', password='secret'}
conn:merge{}
Merges the database tables created by db.tables() into the specified database.
Required Parameters
- api: Set to the database type (e.g. db.MY_SQL or db.SQL_SERVER) integer constant.
- name: Database name/address. For db.SQLITE, this is the database file name string.
- user: User name (neither required nor used for db.SQLITE) string.
- password: Password (neither required nor used for db.SQLITE) string.
- data: A set of tables created using db.tables table node tree.
Optional Parameters
- bulk_insert: Set to true to use bulk insert logic boolean.
- transaction: Set to false to disable inserting/updating all rows as a transaction boolean.
- live: If true, the merge will be executed in the editor (default live = false) boolean.
- use_unicode: If true, Unicode will be used when communicating with the database boolean.
- timeout: Maximum time in seconds allowed for the query (0 for infinite) integer.
Note: Timeout is supported only for ODBC based connections and defaults to 5 minutes.
For More Information
- The db_connection module - new database methods
- The db module - old style database functions
- Mapping To/From Databases
db.query
Example Usage of db.query{api=<value>, name=<value>, ...}
local Results = db.query{ api=db.MY_SQL, name='test@localhost', user='fred', password='secret', sql='SELECT * FROM Patient WHERE Flag = "F"' }
-- Return an array containing multiple results sets, one for each query
-- Note: Some DBs do not support multiple queries in a single "sql" string
local Results = db.query{
api=db.MY_SQL, name='test@localhost',
user='fred', password='secret'
sql = 'SELECT * FROM Patient; SELECT * FROM Kin'
}
-- trap the database error thrown bydb.query
local Success, Error = pcall(
db.query,{
api=db.MY_SQL, name='test@localhost',
user='fred', password='secret',
sql = 'Select * from Not_a_table'
}
)
trace(Success) -- false in this case
trace(Error) -- view the pcall Error return as a table
local DbError = Error.message -- copy the DB error message string from Error
trace(DbError) -- view the DB error message
Usage
db.query{api=<value>, name=<value>, ...}
Recommended best practice - use conn:query{} instead: conn = db.connect{api=db.MY_SQL, name='test@localhost',user='root', password='secret'}
conn:query{}
Executes an ad hoc SQL query against a database. Insert or update statements are not allowed (for these, use db.execute
).
Both db.execute()
and db.query()
throw errors if a database error is encountered. The errors are regular Lua errors and will cause the execution of the script to halt, unless they are caught by Lua error handling using pcall
or xpcall
. The error thrown is a table with two fields:
- message: a string with the description of the error
- code: an integer error code returned by the database.
Currently, error codes from ODBC sources and MySQL databases are supported.
Required Parameters
- api: Set to the database type (e.g. db.MY_SQL or db.SQL_SERVER) integer constant.
- name: Database name/address. For db.SQLITE, this is the database file name string.
- user: User name (neither required nor used for db.SQLITE) string.
- password: Password (neither required nor used for db.SQLITE) string.
- sql: The SQL select statement string.
Optional Parameters
- live: If true, the statement will be executed in the editor (default live = true) boolean.
- use_unicode: If true, Unicode will be used when communicating with the database boolean.
- timeout: Maximum time in seconds allowed for the query (0 for infinite) integer.
Note: Timeout is supported only for ODBC based connections and defaults to 5 minutes.
Returns
- The first result set result_set node tree.
- An array containing all the result sets table.
For More Information
- The db_connection module - new database methods
- The db module - old style database functions
- Mapping To/From Databases
- Node types for Iguana node trees
db.rollback
Example Usage of db.rollback{api=<value>, name=<value>, ...}
db.rollback{ api=db.MY_SQL, name='test@localhost', user='root', password='secret' }
Usage
db.rollback{api=<value>, name=<value>, ...}
Deprecated: use conn:rollback{} instead: conn = db.connect{api=db.MY_SQL, name='test@localhost',user='root', password='secret'}
conn:rollback{}
Rollback a transaction, if one has begun (if transactions are supported by the database engine).
Probably the most commonly used database that does not support transactions is MySQL when it used with the MyISAM database engine (the newer InnoDB engine for MySQL has transaction support).
Note: If transactions are not supported, then db.begin{}
, db.commit{}
have no effect. This is not regarded as an error condition, so no error is raised in the Translator. When transactions are not supported, then each individual SQL statement is committed separately. For example: A call to and
db.rollback{}db.execute{}
that contains three SQL statements, will be run as three independent commands (one for each SQL statement).
Required Parameters
- api: Set to the database type (e.g. db.MY_SQL or db.SQL_SERVER) integer constant.
- name: Database name/address. For db.SQLITE, this is the database file name string.
- user: User name (neither required nor used for db.SQLITE) string.
- password: Password (neither required nor used for db.SQLITE) string.
Optional Parameters
- live: If true, the rollback will be executed in the editor (default live = true) boolean.
- use_unicode: If true, Unicode will be used when communicating with the database boolean.
- timeout: Maximum time in seconds allowed for the query (0 for infinite) integer.
Note: Timeout is supported only for ODBC based connections and defaults to 5 minutes.
For More Information
- The db_connection module - new database methods
- The db module - old style database functions
- Mapping To/From Databases
db.tables
Example Usage of db.tables{vmd=<value>, name=<value>}
local Out = db.tables{vmd='tables.vmd', name='Message'}
Usage
db.tables{vmd=<value>, name=<value>}
Creates a set of empty record tables, which can be used with db.merge.
Required Parameters
- vmd: The name of the VMD file containing the table schema string.
- name: The name of a message in that schema string.
Returns
- The set of empty record tables table_collection node tree.
For More Information
- The db_connection module - new database methods
- The db module - old style database functions
- Mapping To/From Databases
- Node types for Iguana node trees
dbs
dbs.dbs_cache
dbs.dbs_cache.tables
Example Usage of obj:tables() or obj:tables(name)
local DbsSchema = dbs.init{filename='table.dbs'} function main(Data) local TableSet = DbsSchema:tables('ADT') end
local DbsSchema = dbs.init{definition='table Patient (Id string, FirstName string, LastName string, Gender string, key(Id));'} function main(Data) local TableSet = DbsSchema:tables() end
Usage
obj:tables() or obj:tables(name)
Creates a set of empty record tables, which can be used with db.merge.
Optional Parameters
- name: Name of specific table grouping string.
For More Information
dbs.init
Example Usage of dbs.init{filename='value'}
local DbsSchema = dbs.init{filename='table.dbs'} function main(Data) local TableSet = DbsSchema:tables('ADT') end
Usage
dbs.init{filename='value'}
Loads multiple groups of table layouts from a file or a string. The file is usually named with .dbs extension. For good execution performance, this function should be executed before main().
Optional Parameters
- definition: dbs schema definition as inline string.
- filename: Name of the dbs file containing schema definition string.
Returns
- Instance containing groups of table layouts
For More Information
debug
debug.debug
Usage
debug.debug()
Enters an interactive mode with the user, running each string that the user enters. Using simple commands and other debug facilities, the user can inspect global and local variables, change their values, evaluate expressions, and so on. A line containing only the word cont
finishes this function, so that the caller continues its execution.
Note: that commands for debug.debug
are not lexically nested within any function, and so have no direct access to local variables.
For More Information
- The debug module - debugging functions
- Online documentation for debug.debug
- Online documentation for The Debug Library
- Online documentation for Hooks
- Online documentation for Introspective Facilities
debug.getfenv
Example Usage of debug.getfenv(f)
-- compare function environment to global environment "_G" main() myFunc() end function myFunc() if (debug.getfenv(0) == _G) then print ('Match') end --> "Match" to global environment _G if (debug.getfenv(1) == _G) then print ('Match') end --> "Match" to environment for calling function if (debug.getfenv(main) == _G) then print ('Match') end --> "Match" to environment for main if (debug.getfenv(2) == _G) then print ('Match') end --> "Match" to environment for this function if (debug.getfenv(myFunc) == _G) then print ('Match') end --> "Match" to environment for myFunc (this function) end
-- change function environment and then compare to global environment main() myFunc(_G) end function myFunc(env) if (debug.getfenv(myFunc) == _G) then print ('Match') end --> "Match" to environment for myFunc (this function) -- change the environment for this function setfenv(myFunc,{my_debug={getfenv = debug.getfenv}, my_print = _G.print, myFunc = _G.myFunc}) -- compare to global environment (_G passed as parameter "env") now fails if (my_debug.getfenv(2) ~= env) then my_print ('No Match') end --> "No Match" to environment for this function if (my_debug.getfenv(myFunc) ~= env) then my_print ('No Match') end --> "No Match" to environment for myFunc (this function) end
Usage
debug.getfenv(f)
Returns the current environment in use by the function. f
must be a function, if it is not a Lua function the global environment is returned.
All global variables live as fields in ordinary Lua tables, called environment tables or simply environments.
Each function written in Lua (a Lua function) has its own reference to an environment, so that all global variables in that function will refer to that environment table. When a function is created, it inherits the environment from the function that created it (usually in Iguana this will be the global environment). To change or get the environment table of a Lua function, you call setfenv or getfenv.
Note: any functions written in C and exported to Lua (C functions) all share the common global environment (_G).
Required Parameters
- f: Function to return environment for function.
Returns
- Function environment table.
For More Information
- The debug module - debugging functions
- Online documentation for debug.getfenv
- Online documentation for Variables
- Online documentation for The Environment
- Advanced: sandboxing - running untrusted Lua code in a restricted Lua environment
debug.gethook
Usage
debug.gethook([thread])
Returns the current hook settings of the thread, as three values: the current hook function, the current hook mask, and the current hook count (as set by the debug.sethook
function).
The string mask returned may have the following characters, with the given meaning:
Mask | Action |
---|---|
"c" | the hook is called every time Lua calls a function. |
"r" | the hook is called every time Lua returns from a function. |
"l" | the hook is called every time Lua enters a new line of code. |
With a count
returned that is different from zero, the hook is called after every count
instructions.
Optional Parameters
- thread: Thread to use thread.
Returns
- The current hook function function.
- The current hook mask string.
- The current hook count integer.
For More Information
- The debug module - debugging functions
- Online documentation for debug.gethook
- Online documentation for Hooks.
debug.getinfo
Usage
debug.getinfo([thread,] function [, what])
Returns a table with information about a function. You can give the function directly, or you can give a number as the value of function
, which means the function running at level function
of the call stack of the given thread: level 0 is the current function (getinfo
itself); level 1 is the function that called getinfo
; and so on. If function
is a number larger than the number of active functions, then getinfo
returns nil.
The returned table can contain all the fields returned by lua_getinfo
, with the string what
describing which fields to fill in. The default for what
is to get all information available, except the table of valid lines. If present, the option 'f
' adds a field named func
with the function itself. If present, the option 'L
' adds a field named activelines
with the table of valid lines.
For instance, the expression debug.getinfo(1,"n").name
returns a table with a name for the current function, if a reasonable name can be found, and the expression debug.getinfo(print)
returns a table with all available information about the print
function.
Required Parameters
- function: Function to return information for function or integer.
Optional Parameters
- thread: Thread to use thread.
- what: Specify what information to get string.
Returns
- A table with information about the specified function table.
For More Information
debug.getlocal
Usage
debug.getlocal([thread,] level, local)
This function returns the name and the value of the local variable with index local
of the function at level level
of the stack. (The first parameter or local variable has index 1, and so on, until the last active local variable.) The function returns nil if there is no local variable with the given index, and raises an error when called with a level
out of range. (You can call debug.getinfo
to check whether the level is valid.)
Variable names starting with '(
' (open parentheses) represent internal variables (loop control variables, temporaries, and C function locals).
Required Parameters
- level: Stack level index for function integer.
- local: Index for variable in the function integer.
Optional Parameters
- thread: Thread to use thread.
Returns
- Name of local variable (or nil if not found) string.
- Value of local variable (only returned when variable found) any type.
For More Information
debug.getmetatable
Usage
debug.getmetatable(table)
Returns the metatable of the given table, if the table does not have a metatable it returns nil.
Note: If the table's metatable has a "__metatable" field then this value is returned instead.
Required Parameters
- table: Table to get metatable for table.
Returns
- Metatable if it exists, otherwise nil table or nil.
For More Information
- The debug module - debugging functions
- Online documentation for debug.getmetatable
- Online documentation for metatable
- Online documentation for Library-Defined Metamethods
- Online documentation for Lua Classes With Metatable
debug.getregistry
Usage
debug.getregistry()
Returns the Lua registry table.
Returns
- The Lua registry table table.
For More Information
- The debug module - debugging functions
- Online documentation for debug.getregistry
- Online documentation for The Registry
- Online documentation for Registry
debug.getupvalue
Usage
debug.getupvalue(func, up)
This function returns the name and the value of the upvalue with index up
of the function func
. The function returns nil if there is no upvalue with the given index.
While the registry implements global values, the upvalue mechanism implements an equivalent of C static variables, which are visible only inside a particular function. Every time you create a new C function in Lua, you can associate with it any number of upvalues; each upvalue can hold a single Lua value. Later, when the function is called, it has free access to any of its upvalues, using pseudo-indices.
We call this association of a C function with its upvalues a closure. Remember that, in Lua code, a closure is a function that uses local variables from an outer function. A C closure is a C approximation to a Lua closure. One interesting fact about closures is that you can create different closures using the same function code, but with different upvalues.
Required Parameters
- func: Function to return upvalue for function.
- up: Index to find upvalue integer.
Returns
- Name of the upvalue string.
- Value of the upvalue any type.
For More Information
- The debug module - debugging functions
- Online documentation for debug.getupvalue
- Online documentation for Upvalues
- Online documentation for Accessing Upvalues
debug.setfenv
Example Usage of debug.setfenv(f, table)
-- change function environment and then compare to global environment main() myFunc(_G) end function myFunc(env) if (debug.getfenv(myFunc) == _G) then print ('Match') end --> "Match" to environment for myFunc (this function) -- change the environment for this function setfenv(myFunc,{my_debug={getfenv = debug.getfenv}, my_print = _G.print, myFunc = _G.myFunc}) -- compare to global environment (_G passed as parameter "env") now fails if (my_debug.getfenv(2) ~= env) then my_print ('No Match') end --> "No Match" to environment for this function if (my_debug.getfenv(myFunc) ~= env) then my_print ('No Match') end --> "No Match" to environment for myFunc (this function) end
Usage
debug.setfenv(f, table)
Sets the environment to be used by the given function. f must be a Lua function. Returns the given function.
All global variables live as fields in ordinary Lua tables, called environment tables or simply environments.
Each function written in Lua (a Lua function) has its own reference to an environment, so that all global variables in that function will refer to that environment table. When a function is created, it inherits the environment from the function that created it (usually in Iguana this will be the global environment). To change or get the environment table of a Lua function, you call setfenv or getfenv.
Note: any functions written in C and exported to Lua (C functions) all share the common global environment (_G).
Required Parameters
- f: Function to set the environment for function.
- table: New environment table table.
Returns
- The given function function.
For More Information
- The debug module - debugging functions
- Online documentation for debug.setfenv
- Online documentation for Variables
- Online documentation for The Environment
- Advanced: sandboxing - running untrusted Lua code in a restricted Lua environment
debug.sethook
Usage
debug.sethook([thread,] hook, mask [, count])
Sets the given function as a hook. The string mask
and the number count
describe when the hook will be called. The string mask may have the following characters, with the given meaning:
Mask | Action |
---|---|
"c" | the hook is called every time Lua calls a function. |
"r" | the hook is called every time Lua returns from a function. |
"l" | the hook is called every time Lua enters a new line of code. |
With a count
different from zero, the hook is called after every count
instructions.
When called without arguments, debug.sethook
turns off the hook.
When the hook is called, its first parameter is a string describing the event that has triggered its call: "call"
, "return"
(or "tail return"
, when simulating a return from a tail call), "line"
, and "count"
. For line events, the hook also gets the new line number as its second parameter. Inside a hook, you can call getinfo
with level 2 to get more information about the running function (level 0 is the getinfo
function, and level 1 is the hook function), unless the event is "tail return"
. In this case, Lua is only simulating the return, and a call to getinfo
will return invalid data.
Required Parameters
- hook: Hook function to call function.
- mask: Mask indicating when to call the hook function string.
Optional Parameters
- thread: Thread to use thread.
- count: Call the hook function after count instructions number.
For More Information
- The debug module - debugging functions
- Online documentation for debug.sethook
- Online documentation for Hooks
debug.setlocal
Usage
debug.setlocal([thread,] level, local, value)
This function assigns the value "value"
to the local variable with index local
of the function at level "level"
of the stack. The function returns nil if there is no local variable with the given index, and raises an error when called with a level
out of range. (You can call getinfo
to check whether the level is valid.) Otherwise, it returns the name of the local variable.
Required Parameters
- level: Stack level index for function integer.
- local: Index for variable in the function integer.
- value: Value to assign to variable any type.
Optional Parameters
- thread: Thread to use thread.
Returns
- The value of the loal variable (or nil if the specified variable not found) any type or nil.
For More Information
debug.setmetatable
Usage
debug.setmetatable(table, metatable)
Sets the metatable for the given table. If metatable is nil it removes the metatable of the given table. If the original metatable has a "__metatable" field then an error is raised.
Note: You can only change the metatables of tables from Lua, metatables of other types can be changed from C.
Required Parameters
- table: Table to set metatable for table.
- metatable: Metatable to set to table or nil.
Returns
- Original table table.
For More Information
- The debug module - debugging functions
- Online documentation for debug.setmetatable
- Online documentation for metatable
- Online documentation for Library-Defined Metamethods
- Online documentation for Lua Classes With Metatable
debug.setupvalue
Usage
debug.setupvalue(func, up, value)
This function assigns the value value
to the upvalue with index up
of the function func
. The function returns nil if there is no upvalue with the given index. Otherwise, it returns the name of the upvalue.
While the registry implements global values, the upvalue mechanism implements an equivalent of C static variables, which are visible only inside a particular function. Every time you create a new C function in Lua, you can associate with it any number of upvalues; each upvalue can hold a single Lua value. Later, when the function is called, it has free access to any of its upvalues, using pseudo-indices.
We call this association of a C function with its upvalues a closure. Remember that, in Lua code, a closure is a function that uses local variables from an outer function. A C closure is a C approximation to a Lua closure. One interesting fact about closures is that you can create different closures using the same function code, but with different upvalues.
Required Parameters
- func: Function to set upvalue for function.
- up: Index to find upvalue integer.
- value: Value to assign to upvalue any type.
Returns
- The name of the upvalue (or nil if the specified upvalue is not found) string or nil.
For More Information
- The debug module - debugging functions
- Online documentation for debug.setupvalue
- Online documentation for Upvalues
- Online documentation for Accessing Upvalues
debug.traceback
Usage
debug.traceback([thread] [, message] [, level])
Returns a string with a traceback of the call stack. An optional message string is appended at the beginning of the traceback. An optional level number tells at which level to start the traceback (default is 1, the function calling traceback).
Optional Parameters
- thread: Thread to use thread.
- message: Message string to append string.
- level: Stack level index for function integer.
Returns
- The traceback of the stack call string.
For More Information
filter
filter.aes
filter.aes.dec
Example Usage of filter.aes.dec {data=<value>, key=<value>}
local Dec = filter.aes.dec{data=Data,key=Key}
Usage
filter.aes.dec {data=<value>, key=<value>}
Decrypts data encoded using AES encryption.
Required Parameters
- data: The string (or stream) to process string or stream.
- key: The shared encryption key string.
Returns
- A decrypted string (or stream) string or stream.
For More Information
filter.aes.enc
Example Usage of filter.aes.enc {data=<value>, key=<value>}
local Enc = filter.aes.enc{data=Data,key=Key}
Usage
filter.aes.enc {data=<value>, key=<value>}
Encrypt data using AES encryption. Input which is not a multiple of 16 bytes in length will be padded with ASCII NUL characters.
Required Parameters
- data: The string (or stream) to process. string or stream.
- key: The shared encryption key string.
Returns
- An encrypted string (or stream) string or stream.
For More Information
filter.base64
filter.base64.dec
Example Usage of filter.base64.dec(data)
local Enc = filter.base64.dec(data)
Usage
filter.base64.dec(data)
Decode Base64 encoded data.
Required Parameters
- data: The string (or stream) to decode string or stream.
Returns
- A decoded string (or stream) string or stream.
For More Information
filter.base64.enc
Example Usage of filter.base64.enc(data)
local Enc = filter.base64.enc(data)
Usage
filter.base64.enc(data)
Encode data as Base64.
Required Parameters
- data: The string (or stream) to encode string or stream.
Returns
- An encoded string (or stream) string or stream.
For More Information
filter.bzip2
filter.bzip2.deflate
Example Usage of filter.bzip2.deflate(data)
local zipped = filter.bzip2.deflate(data)
Usage
filter.bzip2.deflate(data)
Compress data with BZIP2.
Required Parameters
- data: The string (or stream) to compress string or stream.
Returns
- A compressed string (or stream) string or stream.
For More Information
filter.bzip2.inflate
Example Usage of filter.bzip2.inflate(data)
local unzipped = filter.bzip2.inflate(data)
Usage
filter.bzip2.inflate(data)
Decompress BZIP2 data.
Required Parameters
- data: The string (or stream) to decompress string or stream.
Returns
- A decompressed string (or stream) string or stream.
For More Information
filter.gzip
filter.gzip.deflate
Example Usage of filter.gzip.deflate(data)
local zipped = filter.gzip.deflate(data)
Usage
filter.gzip.deflate(data)
Compress data with GZIP.
Required Parameters
- data: The string (or stream) to compress string or stream.
Returns
- A compressed string (or stream string or stream).
For More Information
filter.gzip.inflate
Example Usage of filter.gzip.inflate(data)
local unzipped = filter.gzip.inflate(data)
Usage
filter.gzip.inflate(data)
Decompress GZIP data.
Required Parameters
- data: The string (or stream) to decompress string or stream.
Returns
- A decompressed string (or stream) string or stream.
For More Information
filter.hex
filter.hex.dec
Example Usage of filter.hex.dec(data)
local Enc = filter.hex.dec(data)
Usage
filter.hex.dec(data)
Decode Hex (Base16) encoded data.
Required Parameters
- data: The string (or stream) to decode string or stream.
Returns
- A decoded string (or stream) string or stream.
For More Information
filter.hex.enc
Example Usage of filter.hex.enc(data)
local Dec = filter.hex.enc(data)
Usage
filter.hex.enc(data)
Encode data as Hex (Base16).
Required Parameters
- data: The string (or stream) to encode string or stream.
Returns
- An encoded string (or stream) string or stream.
For More Information
filter.html
filter.html.enc
Example Usage of filter.html.enc(data)
local Enc = filter.html.enc(data)
Usage
filter.html.enc(data)
Encode text for HTML.
Required Parameters
- data: The string (or stream) to encode string or stream.
Returns
- An encoded string (or stream) string or stream.
For More Information
filter.uri
filter.uri.dec
Example Usage of filter.uri.dec (data)
local Dec = filter.uri.dec(data)
Usage
filter.uri.dec (data)
Decode URI encoded component text.
Required Parameters
- data: The string (or stream) to decode string or stream.
Returns
- A decoded string (or stream) string or stream.
For More Information
filter.uri.enc
Example Usage of filter.uri.enc(data)
local Enc = filter.uri.enc(data)
Usage
filter.uri.enc(data)
Encode URI component text.
Required Parameters
- data: The string (or stream) to encode string or stream.
Returns
- An encoded string (or stream) string or stream.
For More Information
filter.uuencoding
filter.uuencoding.dec
Example Usage of filter.uuencoding.dec(data)
local out, info = filter.uuencoding.dec(inp) stream.toFile('output.tmp', out) os.rename('output.tmp', info.filename)
Usage
filter.uuencoding.dec(data)
Decode a Unix to Unix transfer (uudecode).
Required Parameters
- data: The string (or stream) to decode string or stream.
Returns
- A decoded string (or stream) string or stream
- An object with the 'filename' and 'mode' of the decoded file (when using streams these fields are available after decoding) uudecode_info table.
For More Information
filter.uuencoding.enc
Example Usage of filter.uuencoding.enc(data, filename [, mode])
local inp = stream.fromFile(name) local out = filter.uuencoding.enc(inp, name)
Usage
filter.uuencoding.enc(data, filename [, mode])
Encode data for a Unix to Unix transfer (uuencode).
Required Parameters
- data: The string (or stream) to encode string or stream.
- filename: The file name to put in the output string.
Optional Parameters
- mode: The octal file mode (defaults to 644) integer.
For More Information
filter.zip
filter.zip.deflate
Example Usage of filter.zip.deflate(table)
local T = filter.zip.deflate(table)
Usage
filter.zip.deflate(table)
Compress ZIP data.
Required Parameters
- table: The table of files and directories and their contents. May be nested..
Returns
- A binary string containing the compressed zip data.
For More Information
filter.zip.inflate
Example Usage of filter.zip.inflate(data)
local T = filter.zip.inflate(data)
Usage
filter.zip.inflate(data)
Decompress ZIP data.
Required Parameters
- data: The string (or stream) to decompress string or stream.
Returns
- A lua table containing the decompressed files. The results are nested.
For More Information
global
global.assert
Example Usage of assert(v [, message])
flag, msg = myFunc() assert(flag) --> ERROR: assertion failed!
flag, msg = myFunc() assert(flag,'myFunc returned false') --> ERROR: myFunc returned false
Usage
assert(v [, message])
Issues an error when the value of its argument v
is false (i.e., nil or false); otherwise, returns all its arguments. message
is an error message; when absent, it defaults to "assertion failed!"
Required Parameters
- v: Argument to check for validity any type.
Optional Parameters
- message: Error message string.
Returns
- Multiple returns: All parameters passed in any type.
For More Information
global.collectgarbage
Usage
collectgarbage(opt [, arg])
This function is a generic interface to control the garbage collector. It performs different functions according to its first argument, opt
:
- "stop": stops the garbage collector.
- "restart": restarts the garbage collector.
- "collect": performs a full garbage-collection cycle.
- "count": returns the total memory in use by Lua (in Kbytes).
- "step": performs a garbage-collection step. The step "size" is controlled by
arg
(larger values mean more steps) in a non-specified way. If you want to control the step size you must experimentally tune the value ofarg
. Returns true if the step finished a collection cycle. - "setpause": sets
arg
as the new value for the pause of the collector. Returns the previous value for pause. - "setstepmul": sets
arg
as the new value for the step multiplier of the collector. Returns the previous value for step.
Note: use collectgarbage("count") instead of gcinfo.
Required Parameters
- opt: Function to perform string.
Optional Parameters
- arg: Argument used with some options string.
Returns
- Result returned for some options string or boolean.
For More Information
global.dofile
Usage
dofile(filename)
Opens the named file and executes its contents as a Lua chunk. When called without arguments, dofile
tries to execute the contents of the standard input (stdin
). This is not supported within Iguana. Returns all values returned by the chunk. In case of errors, dofile
propagates the error to its caller (that is, dofile
does not run in protected mode).
Required Parameters
- filename: Name of the file to execute string.
Returns
- Multiple returns: All values returned by the chunk any type.
For More Information
global.error
Example Usage of error(message [, level])
-- error is raised inline, where error() is called error('My error message') --> ERROR: My error message error('My error message',1) --> ERROR: My error message
-- error is raised at the calling function main() errorTest() --> ERROR: My error message end function errorTest() error('My error message',2) end
Usage
error(message [, level])
Terminates the last protected function called and returns message
as the error message. Function error
never returns.
Usually, error
adds some information about the error position at the beginning of the message. The level
argument specifies how to get the error position. With level 1 (the default), the error position is where the error
function was called. Level 2 points the error to where the function that called error
was called; and so on. Passing a level 0 avoids the addition of error position information to the message.
Note: using level = 2 (or higher) is an elegant way of making errors from included modules more visible (no need to switch to the module when debugging).
Required Parameters
- message: Error message any type.
- level: Level to raise the error integer.
For More Information
- Global functions - print, pcall, require etc
- Raising and catching errors
- Online documentation for error
global.gcinfo
Usage
Deprecated
Function gcinfo is deprecated in Lua 5.1; use collectgarbage("count") instead.
For More Information
global.getfenv
Example Usage of getfenv([f])
-- compare function environment to global environment "_G" main() myFunc() end function myFunc() if (getfenv(0) == _G) then print ('Match') end --> "Match" to global environment _G if (getfenv(1) == _G) then print ('Match') end --> "Match" to environment for calling function if (getfenv(main) == _G) then print ('Match') end --> "Match" to environment for main if (getfenv(2) == _G) then print ('Match') end --> "Match" to environment for this function if (getfenv(myFunc) == _G) then print ('Match') end --> "Match" to environment for myFunc (this function) end
-- change function environment and then compare to global environment main() myFunc(_G) end function myFunc(env) if (getfenv(myFunc) == _G) then print ('Match') end --> "Match" to environment for myFunc (this function) -- change the environment for this function setfenv(myFunc,{my_getfenv = _G.getfenv, my_print = _G.print, myFunc = _G.myFunc}) -- compare to global environment (_G passed as parameter "env") now fails if (my_getfenv(2) ~= env) then my_print ('No Match') end --> "No Match" to environment for this function if (my_getfenv(myFunc) ~= env) then my_print ('No Match') end --> "No Match" to environment for myFunc (this function) end
Usage
getfenv([f])
Returns the current environment in use by the function. f
can be a Lua function or a number that specifies the function at that stack level: Level 1 is the function calling getfenv
. If the given function is not a Lua function, or if f
is 0, getfenv
returns the global environment. The default for f
is 1.
All global variables live as fields in ordinary Lua tables, called environment tables or simply environments.
Each function written in Lua (a Lua function) has its own reference to an environment, so that all global variables in that function will refer to that environment table. When a function is created, it inherits the environment from the function that created it (usually in Iguana this will be the global environment). To change or get the environment table of a Lua function, you call setfenv or getfenv.
Note: any functions written in C and exported to Lua (C functions) all share the common global environment (_G).
Required Parameters
- f: Function to return environment for function or integer.
Returns
- Function environment table.
For More Information
- Global functions - print, pcall, require etc
- Online documentation for getfenv
- Online documentation for Variables
- Online documentation for The Environment
- Advanced: sandboxing - running untrusted Lua code in a restricted Lua environment
global.getmetatable
Usage
getmetatable(object)
Returns the metatable of the given table, if the table does not have a metatable it returns nil.
Note: If the table's metatable has a "__metatable" field then this value is returned instead.
Required Parameters
- object: Object to return metatable for table.
Returns
- Metatable if it exists, otherwise nil table or nil.
For More Information
- Global functions - print, pcall, require etc
- Online documentation for getmetatable
- Online documentation for metatable
- Online documentation for Library-Defined Metamethods
- Online documentation for Lua Classes With Metatable
global.ipairs
Example Usage of ipairs(t)
-- the index number 3 intentionally missing t={[1]=1,[2]=2,[4]=4}
-- ipairs(t) exits after t[3] (because t[3] does not exist)
-- values are returned in key order
for i,j in ipairs(t) do
trace(i,j)
-- do something
end
-- pairs(t) iterates through all values for k,v in pairs(t) do
trace(k,v)
-- do something
end
t[3]=3 -- add the third index
-- ipairs(t) now also iterates through all indexes (because the sequence is unbroken)
-- values are returned in key order
for i,j in ipairs(t) do
trace(i,j)
-- do something
end
Usage
ipairs(t)
Use ipairs()
to read the elements from a table in numeric key order.
The ipairs()
function returns three values: An iterator function, the table t
, and 0, so that the construction for i,v in ipairs(t) do body end
will iterate over the pairs (1,t[1]
), (2,t[2]
), ..., up to the first integer key absent from the table.
If your table has missing numeric key(s) then ipairs()
will only a return a subset of the data. To return all the values in a table you should use the pairs()
function.
Required Parameters
- t: Table to iterate string.
Returns
- Iterator function function.
- The table table.
- Zero 0.
For More Information
- Global functions - print, pcall, require etc
- Online documentation for ipairs
- Online documentation for pairs
global.load
Usage
load(func [, chunkname])
Loads a chunk using function func
to get its pieces. Each call to func
must return a string that concatenates with previous results. A return of an empty string, nil, or no value signals the end of the chunk.
If there are no errors, returns the compiled chunk as a function; otherwise, returns nil plus the error message. The environment of the returned function is the global environment.chunkname
is used as the chunk name for error messages and debug information. When absent, it defaults to "=(load)
".
Required Parameters
- func: Function to use to load chunk function.
Optional Parameters
- chunkname: Name of chunk to to load string.
Returns
- The compiled chunk as a function, otherwise nil function or nil.
- Error message (only on failure) string.
For More Information
global.loadfile
Usage
loadfile([filename])
Similar to load
, but gets the chunk from file filename
or from the standard input, if no file name is given.
Optional Parameters
- filename: File to load chunk from string.
Returns
- The compiled chunk as a function, otherwise nil function or nil.
- Error message (only on failure) string.
For More Information
global.loadstring
Usage
loadstring(string [, chunkname])
Similar to load
, but gets the chunk from the given string.
To load and run a given string, use the idiom assert(loadstring(s))()
When absent, chunkname
defaults to the given string.
Required Parameters
- string: String to load chunk from string.
Optional Parameters
- chunkname: Name of chunk string.
Returns
- The compiled chunk as a function, otherwise nil function or nil.
- Error message (only on failure) string.
For More Information
global.module
Usage
module(name [, ...])
Creates a module. If there is a table in package.loaded[name]
, this table is the module. Otherwise, if there is a global table t
with the given name, this table is the module. Otherwise creates a new table t
and sets it as the value of the global name
and the value of package.loaded[name]
. This function also initializes t._NAME
with the given name, t._M
with the module (t
itself), and t._PACKAGE
with the package name (the full module name minus last component; see below). Finally, module
sets t
as the new environment of the current function and the new value of package.loaded[name]
, so that require
returns t
.
If name
is a compound name (that is, one with components separated by dots), module
creates (or reuses, if they already exist) tables for each component. For instance, if name
is a.b.c
, then module
stores the module table in field c
of field b
of global a
.
This function can receive optional options after the module name, where each option is a function to be applied over the module.
Required Parameters
- name: Name of the module string.
Optional Parameters
- func: Multiple parameters: Function to be applied over the module function.
For More Information
- Global functions - print, pcall, require etc
- Our recommendations for module structure
- Online documentation for module
global.newproxy
Usage
newproxy(value)
The Lua C API and standard libraries may contain some undocumented, unsupported, and/or experimental features. They are likely unsupported for a good reason, and may disappear or change at any time - use them at your own risk.
newproxy is an unsupported and undocumented function in the Lua base library - use it at your own risk.
From Lua code, the setmetatable function may only be used on objects of table type. The newproxy function circumvents that limitation by creating a zero-size userdata and setting either a new, empty metatable on it or using the metatable of another newproxy instance. We are then free to modify the metatable from Lua. This is the only way to create a proxy object from Lua which honors certain metamethods, such as __len. Synopsis:
do
local a = newproxy(true) -- create proxy object with new metatable
assert(type(a) == 'userdata')
getmetatable(a).__len = function() return 5 end
assert(#a == 5)
local b = newproxy(a) -- create proxy object with same metatable as another proxy
assert(b ~= a)
assert(getmetatable(b) == getmetatable(a))
assert(#b == 5)
local c = newproxy(false) -- create proxy object with no metatable
assert(not getmetatable(c))
local is_collected = false
local o = newproxy(true)
getmetatable(o).__gc = function() is_collected = true end -- finalizer
o = nil; collectgarbage() -- clear all references to object and ensure finalizer called
assert(is_collected)
end
Required Parameters
- value: Instruction on how to set the metatable boolean or userdata.
Returns
- The new empty proxy object userdata.
For More Information
global.next
Usage
next(table [, index])
Allows a program to traverse all fields of a table. Its first argument is a table and its second argument is an index in this table. next
returns the next index of the table and its associated value. When called with nil as its second argument, next
returns an initial index and its associated value. When called with the last index, or with nil in an empty table, next
returns nil. If the second argument is absent, then it is interpreted as nil. In particular, you can use next(t)
to check whether a table is empty.
The order in which the indices are enumerated is not specified, even for numeric indices. (To traverse a table in numeric order, use a numerical for or the ipairs
function.)
The behavior of next
is undefined if, during the traversal, you assign any value to a non-existent field in the table. You may however modify existing fields. In particular, you may clear existing fields.
Required Parameters
- table: Table to be traversed table.
Optional Parameters
- index: Index position to start at any type.
Returns
- Next value in array any type.
For More Information
global.pairs
Example Usage of pairs(t)
-- the index number 3 is intentionally missing t={[1]=1,[2]=2,[4]=4}
-- pairs(t) iterates through all values
-- the order that values are returned is not specified
for k,v in pairs(t) do
trace(k,v)
-- do something
end
-- ipairs(t) exits after t[2] (because t[3] does not exist)
-- values are returned in key order
for i,j in ipairs(t) do
trace(i,j)
-- do something
end
Usage
pairs(t)
Use pairs()
to read all the elements in a table.
The pairs()
function returns three values: The next()
function, the table t, and nil, so that the construction for k,v in pairs(t) do body end
will iterate over all key value pairs of table t.
The order that the indices are enumerated/returned is not specified (even for numeric keys). If you need to traverse a table in numerical order you can use either the ipairs()
function or a numerical for statement.
Note: You must not add new field(s) to the table within the loop, if you do then the iteration may not work correctly (because the behaviour of the next()
function is undefined in these circumstances).
Required Parameters
- t: Table to iterate string.
Returns
- Next function function.
- The table table.
- Nil nil.
For More Information
- Global functions - print, pcall, require etc
- Online documentation for pairs
- Online documentation for next
- Online documentation for ipairs
global.pcall
Example Usage of pcall(f, arg1, ...)
local Status, Result = pcall(MainFunction, MainErrorMessage)
Usage
pcall(f, arg1, ...)
Calls function f
with the given arguments in protected mode. This means that any error inside f
is not propagated; instead, pcall
catches the error and returns a status code. Its first result is the status code (a boolean), which is true if the call succeeds without errors. In such case, pcall
also returns all results from the call, after this first result. In case of any error, pcall
returns false plus the error message.
Required Parameters
- f: Function to call function.
- arg: Multiple parameters: Argument to the function any type.
Returns
- Status code boolean.
- On success: multiple returns: The results from the function call any type OR on failure: error message string or table.
Note: Database error returns are tables with an error code and a message.
For More Information
- Global functions - print, pcall, require etc
- Online documentation for pcall
- Raising and catching errors
global.print
Example Usage of print(<value>, ...)
print('a','b','c') --> 'a','b','c'
print('a'..'b'..'c') --> 'abc'
Usage
print(<value>, ...)
Recommended best practices:
- For logging informational messages: use
iguana.logInfo
instead. - For debugging: use a
trace()
function instead.
Receives any number of arguments, converts them to strings, concatenates them - then prints that values out as a log entry (info type) in the log. It uses the tostring
function to convert the arguments to strings.
If you need to formatted output, use string.format
.
Note: the iguana.logInfo
function does exactly the same thing as print
.
Required Parameters
- value: Multiple parameters: Values to print any type.
For More Information
- Global functions - print, pcall, require etc
- Why not to use print() for debugging
- Using trace() to view data for debugging
- Online documentation for print
global.rawequal
Usage
rawequal(v1, v2)
Checks whether v1
is equal to v2
, without invoking any metamethod. Returns a boolean.
Required Parameters
- v1: First value any type.
- v2: Second value any type.
Returns
- Result (true or false) boolean.
For More Information
global.rawget
Usage
rawget(table, index)
Gets the real value of table[index]
, without invoking any metamethod. table
must be a table; index
may be any value.
Required Parameters
- index: Index for table any type.
- table: Name of table string.
Returns
- Value from the specified field string.
For More Information
global.rawset
Usage
rawset(table, index, value)
Sets the real value of table[index]
to value
, without invoking any metamethod. table
must be a table, index
any value different from nil, and value
any Lua value.
This function returns table
.
Required Parameters
- table: Value to use any type.
- index: Index to use any type.
- value: Target table name string.
Returns
- The updated table table.
For More Information
global.require
Example Usage of require(modname)
require('stream')
-- also works without braces require 'stream'
Usage
require(modname)
Loads the given module. It is equivalent to "include" in C\C++. Iguana's implementation of require adds the module to the project if it is not already included.
All you need to know: add "require statements" at the top of a module to include other modules.
For technical detail on how it works, read on.
The function starts by looking into the package.loaded
table to determine whether modname
is already loaded. If it is, then require
returns the value stored at package.loaded[modname]
. Otherwise, it tries to find a loader for the module.
To find a loader, require
is guided by the package.loaders
array. By changing this array, we can change how require
looks for a module. The following explanation is based on the default configuration for package.loaders
.
First require
queries package.preload[modname]
. If it has a value, this value (which should be a function) is the loader. Otherwise require
searches for a Lua loader using the path stored in package.path
. If that also fails, it searches for a C loader using the path stored in package.cpath
. If that also fails, it tries an all-in-one loader (see package.loaders
).
Once a loader is found, require
calls the loader with a single argument, modname
. If the loader returns any value, require
assigns the returned value to package.loaded[modname]
. If the loader returns no value and has not assigned any value to package.loaded[modname]
, then require
assigns true to this entry. In any case, require
returns the final value of package.loaded[modname]
.
If there is any error loading or running the module, or if it cannot find any loader for the module, then require
signals an error.
Required Parameters
- modname: Name of the module to load string.
Returns
- Final value of package.loaded[modname] boolean or table.
For More Information
- Global functions - print, pcall, require etc
- Working with shared modules
- Online documentation for require
global.select
Usage
select(index, ...)
If index
is a number, returns all arguments after argument number index
. Otherwise, index
must be the string "#"
, and select
returns the total number of extra arguments it received.
Required Parameters
- index: Start index integer.
Returns
- Multiple returns: Arguments starting with "index"string. OR a count of the arguments integer.
For More Information
global.setfenv
Example Usage of setfenv(f, table)
-- change function environment and then compare to global environment main() myFunc(_G) end function myFunc(env) if (getfenv(myFunc) == _G) then print ('Match') end --> "Match" to environment for myFunc (this function) -- change the environment for this function setfenv(myFunc,{my_getfenv = _G.getfenv, my_print = _G.print, myFunc = _G.myFunc}) -- compare to global environment (_G passed as parameter "env") now fails if (my_getfenv(2) ~= env) then my_print ('No Match') end --> "No Match" to environment for this function if (my_getfenv(myFunc) ~= env) then my_print ('No Match') end --> "No Match" to environment for myFunc (this function) end
Usage
setfenv(f, table)
Sets the environment to be used by the given function. f can be a Lua function or a number that specifies the function at that stack level: Level 1 is the function calling setfenv. setfenv returns the given function.
As a special case, when f is 0 setfenv changes the environment of the running thread. In this case, setfenv returns no values.
All global variables live as fields in ordinary Lua tables, called environment tables or simply environments.
Each function written in Lua (a Lua function) has its own reference to an environment, so that all global variables in that function will refer to that environment table. When a function is created, it inherits the environment from the function that created it (usually in Iguana this will be the global environment). To change or get the environment table of a Lua function, you call setfenv or getfenv.
Note: any functions written in C and exported to Lua (C functions) all share the common global environment (_G).
Required Parameters
- f: Function to set the environment for function or integer.
- table: New environment table table.
Returns
- The given function function.
For More Information
- Global functions - print, pcall, require etc
- Online documentation for setfenv
- Online documentation for Variables
- Online documentation for The Environment
- Advanced: sandboxing - running untrusted Lua code in a restricted Lua environment
global.setmetatable
Usage
setmetatable(table, metatable)
Sets the metatable for the given table. If metatable is nil it removes the metatable of the given table. If the original metatable has a "__metatable" field then an error is raised.
Note: You can only change the metatables of tables from Lua, metatables of other types can be changed from C.
Required Parameters
- table: Table to set metable for table.
- metatable: Metatable to set to table.
Returns
- Original table table.
For More Information
- Global functions - print, pcall, require etc
- Online documentation for setmetatable
- Online documentation for metatable.
- Online documentation for Library-Defined Metamethods
- Online documentation for Lua Classes With Metatable
global.tonumber
Usage
tonumber(e [, base])
Tries to convert its argument to a number. If the argument is already a number or a string convertible to a number, then tonumber
returns this number; otherwise, it returns nil.
An optional argument specifies the base to interpret the numeral. The base may be any integer between 2 and 36, inclusive. In bases above 10, the letter 'A
' (in either upper or lower case) represents 10, 'B
' represents 11, and so forth, with 'Z
' representing 35. In base 10 (the default), the number can have a decimal part, as well as an optional exponent part. In other bases, only unsigned integers are accepted.
Required Parameters
- e: Value to convert to number any type.
- base: Base to use for conversion integer or string.
Returns
- Result of conversion number.
For More Information
global.tostring
Usage
tostring(e)
Receives an argument of any type and converts it to a string in a reasonable format. For complete control of how numbers are converted, use string.format
.
If the metatable of e
has a "__tostring"
field, then tostring
calls the corresponding value with e
as argument, and uses the result of the call as its result.
Required Parameters
- e: Argument to convert to a string any type.
Returns
- Result of the conversion string.
For More Information
global.trace
Example Usage of trace(<value>, ...)
trace('a', 'b', 'c') --> 'a', 'b', and 'c' displayed in annotations
trace(Msg) --> can now view the Msg object in annotations
Usage
trace(<value>, ...)
This function is a tool to display annotations for the arguments it receives. It is useful for checking the value of variables at a certain point in your script's execution. When annotations are enabled, trace
produces an annotation when called with any number of arguments, or with no arguments, but it does not alter the input data nor does it return any result.
Note: Unlike print()
, the trace()
function does not produce log entries. If you would prefer to have a log entry produced when the script is run as a channel, then use the print()
or iguana.logInfo()
functions instead.
Required Parameters
- value: Multiple parameters: values to trace any type.
For More Information
global.type
Example Usage of type(v)
t = type(value)
Usage
type(v)
Returns the type of its only argument, coded as a string. The possible results of this function are "nil
"(a string, not the value nil), "number
", "string
", "boolean
", "table
", "function
", "thread
", and "userdata
".
The 'node tree' objects in Iguana are of the userdata type.
Required Parameters
- v: Value to check the type of any type.
Returns
- Type of argument string.
For More Information
global.unpack
Example Usage of unpack(list [, i [, j]])
t={'a','b','c'} unpack(t) --> 'a','b','c' unpack(t,1,2) --> 'a','b' return t[1], t[2] --> 'a','b'
Usage
unpack(list [, i [, j]])
Returns the elements from the given table. This function is equivalent to: return list[i], list[i+1], ..., list[j]
Except that the above code can be written only for a fixed number of elements. By default, i
is 1 and j
is the length of the list, as defined by the length operator (#).
Required Parameters
- list: Table name string.
Optional Parameters
- i: Start of range integer.
- j: End of range integer.
Returns
- Multiple returns: One for each item in the range any type.
For More Information
global.unwind_protect
Usage
unwind_protect(action, cleanup)
Execute action() and then cleanup(), even when action() fails due to an error, timeout or interupt. When cleanup() is called, it is passed the results from pcall(action), and given at least a minute to complete--you can extend this with iguana.setTimeout() but its effect will be local to cleanup().
Required Parameters
- action: Function to execute function.
- cleanup: Function execute when "action" fails function.
Returns
- The values returned from action() any type.
- Errors thrown by either action() or cleanup() will be thrown again by unwind_protect(); errors thrown from cleanup() will take precedence. any type.
global.xpcall
Example Usage of xpcall(f, err)
local Status, Result = xpcall(MainFunction, ErrorHandler)
Usage
xpcall(f, err)
This function is similar to pcall, except that you can set a new error handler.
xpcall calls function f in protected mode, using err as the error handler. Any error inside f is not propagated; instead, xpcall catches the error, calls the err function with the original error object, and returns a status code. Its first result is the status code (a boolean), which is true if the call succeeds without errors. In this case, xpcall also returns all results from the call, after this first result. In case of any error, xpcall returns false plus the result from err.
Required Parameters
- f: Function to call function.
- err: Error handler function.
Returns
- Status code boolean.
- On success: multiple returns: The results from the function call any type OR on failure: error message returned by error handler any type.
Note: Database error returns are tables with an error code and a message.
For More Information
help
help.example
Example Usage of help.example()
local h = help.example()
Usage
help.example()
Returns an example of a table that is compatible with the interactive help system.
Returns
- An example help data table table.
For More Information
help.get
Example Usage of help.get(input_function)
-- get the help data for this function help.get(help.get)
-- get the help data for a custom function help.get(customerModule.customerFunction)
Usage
help.get(input_function)
Get the help data associated with the input function.
Required Parameters
- input_function: The function that you wish to retrieve help data for function.
Returns
- A table containing the help data table. OR nil if no help was found nil.
For More Information
- Help functions for customized help
- Parsing information from a PDF file: Scroll down to the code for a simple help example.
- Store Utility Module: Scroll to the bottom of the page for three help examples.
help.reset
Example Usage of help.reset()
help.reset()
Usage
help.reset()
Clears all custom help data, and loads the base help for Iguana and Lua modules.
Note: help added with help.set will be removed.
For More Information
help.set
Example Usage of help.set{input_function=<value>, help_data=<value>}
help.set{input_function=myfunc, help_data=myhelp}
-- create help for a custom function local h=help.example() h.Title = 'customerModule.customerFunction' h.Desc = 'Example customer function - add custom description' h.Usage = 'Add custom usage' h.Parameters[1].parameter_name_1.Desc = 'Custom parameter description <u>function</u>.' -- set other values help.set{input_function=customerModule.customerFunction, help_data=h} -- confirm changes help.get(customerModule.customerFunction)
Usage
help.set{input_function=<value>, help_data=<value>}
Sets the help data used for interactive help, you can set the help for built-in and custom functions. This API allows you to add help for your own library code.
Note: Use help.example()
to get an example of a suitably formatted help table
Required Parameters
- input_function: The function the help data will be attached to function.
- help_data: A table containing the help data. table.
For More Information
- Help functions for customized help
- Parsing information from a PDF file: Scroll down to the code for a simple help example.
- Store Utility Module: Scroll to the bottom of the page for three help examples.
help.toHtml
Example Usage of help.toHtml(help_data)
-- get the help HTML for the example help data help.toHtml(help.example())
-- get the help HTML for a custom function help.toHtml(help.get(customerModule.customerFunction))
Usage
help.toHtml(help_data)
Renders the given help data as HTML.
Required Parameters
- help_data: The help data that you wish to render as HTML table.
Returns
- A string containing the HTML help, or an empty string if the help data given is invalid string.
For More Information
hl7
hl7.message
Example Usage of hl7.message{vmd=<value>, name=<value>}
-- If you hardcode the 'name' then the Msg can only be used with that message type (in this case 'PatientRegister')
local Msg = hl7.message{vmd='example.vmd', name='PatientRegister'} -- 'name' hardcoded is not Best Practise
-- Best Practise: Use the message type returned by hl7.parse{} (2nd return) to create an output message to map to
local Msg, Name = hl7.parse{vmd = 'demo.vmd', data = Data} -- 'Name' the HL7 message type
local Out = hl7.message{vmd = 'demo.vmd', name = Name} -- 'Name' used as 2nd parameter
Usage
hl7.message{vmd=<value>, name=<value>}
Create an empty HL7/EDI data tree to populate with data. Returns an empty message object whose sub-fields are the segments of the message, e.g., Msg.PID for the PID segment.
Best Practise: We recommend that you do not hard-code the message 'name' (second parameter). Instead you should use the name returned from hl7.parse{} (second return). This allows the message you create to be compatible with all message types that are defined in the VMD file you are using.
Required Parameters
- vmd: The name of a VMD schema file string.
- name: The name of a message definition in the specified VMD file string.
Returns
- An empty data tree representing an HL7/EDI message HL7 node tree.
For More Information
- The hl7 module - working with HL7 2.x messages
- Documentation for parsing HL7 with the translator
- Node types for Iguana node trees
hl7.parse
Example Usage of hl7.parse{vmd=<value>, data=<value>}
local Msg = hl7.parse{vmd='demo.vmd', data=Data}
Usage
hl7.parse{vmd=<value>, data=<value>}
Parses an HL7/EDI/X12 message. Returns three values: a read-only message tree, the name of the VMD message definition used to parse the message, and a list of warnings and errors.
Required Parameters
- vmd: The name of a VMD schema file string.
- data: A message to be parsed string.
Returns
- The parsed message as a read-only data tree HL7 node tree.
- The name of the message type string.
- A list of warnings and errors table.
For More Information
- The hl7 module - working with HL7 2.x messages
- Documentation for parsing HL7 with the translator
- Using the Warnings returned from hl7.parse{}
- Node types for Iguana node trees
iguana
iguana.appDir
Example Usage of iguana.appDir()
-- make a temporary directory under the install directory iguana.appDir() local mydir = iguana.workingDir()..[[temp_data\]] os.mkdir(mydir)
Usage
iguana.appDir()
Get the directory where the Iguana executable resides.
Returns
- The directory name string.
For More Information
iguana.channelConfig
Example Usage of iguana.channelConfig{guid=iguana.channelGuid()}
--Fetching by GUID
local Config = iguana.channelConfig{guid=iguana.channelGuid()}
Config = xml.parse{data=Config}
--Or by channel name
local Config = iguana.channelConfig{name=iguana.channelName()}
Usage
iguana.channelConfig{guid=iguana.channelGuid()}
Fetches the configuration for a channel specified by name or guid.
Optional Parameters
- guid: Guid of the channel configuration to fetch string
- name: Name of the channel configuraiton to fetch string.
For More Information
iguana.channelGuid
Example Usage of iguana.channelGuid()
local Guid = iguana.channelGuid()
Usage
iguana.channelGuid()
Get the guid of the channel this translator instance belongs to.
Returns
- The guid of the channel string.
For More Information
iguana.channelName
Example Usage of iguana.channelName()
local name = iguana.channelName()
Usage
iguana.channelName()
Get the name of the channel running the script.
Returns
- the current channel name string.
For More Information
iguana.id
Example Usage of iguana.id()
local licenceID = iguana.id()
Usage
iguana.id()
Get the 'IguanaID' of the Iguana server as used for licensing.
Returns
- The ID string.
For More Information
iguana.isTest
Example Usage of iguana.isTest()
if iguana.isTest() then -- do stuff that I do not want to run live end
if not iguana.isTest() then -- do stuff that I do not want to run in the editor (test mode) end
Usage
iguana.isTest()
Determine if this script is running in the editor (test mode). Returns true when your script is running in the Translator editor (test mode), when it is running in a live channel it returns false.
This function can be very handy when you want to avoid running code while editing. For instance, you may not actually want to wait out a call to util.sleep() while you edit your code.
Returns
- True if this script is running in the editor false otherwise boolean.
For More Information
- Modify the behaviour of the code when running in test and production
- Templating System
- The iguana module - interacting with Iguana's run-time system
iguana.logDebug
Example Usage of iguana.logDebug(text [, message_id])
iguana.logDebug(text)
iguana.logDebug(text, iguana.messageId())
-- Working with queued messages (Filter, To Translator, and LLP Listener using "Translator ACK")
local text = 'This is a Debug log entry'
-- link to the current message ID
iguana.logDebug(text)
iguana.logDebug(text, iguana.messageId()) -- identical result to the line above
-- include the message ID in the log entry
iguana.logDebug(text..iguana.messageId())
-- save linked messages in a database
Conn:execute{sql = "INSERT IguanaMessage ('MsgId', 'LogMsg') VALUES ("..iguana.messageId()..","..text..")}"
-- Working with unqueued messages (From Translator and From HTTPS)
local text = 'This is a Debug log entry'
-- cannot link to an unqueued message
iguana.logDebug(text) -- creates a log entry, that is not linked to a message
iguana.logDebug(text, iguana.messageId()) -- this does not work
-- log the message first to create a message ID, then link to it
local MessageId = queue.push(text)
iguana.logDebug(text, MessageId())
-- include the message ID in the log entry
iguana.logDebug(text..iguana.messageId()) -- this does not work
iguana.logDebug(text..MessageId)
-- save linked messages in a database
Conn:execute{sql = "INSERT IguanaMessage ('MsgId', 'LogMsg') VALUES ("..MessageId..","..text..")}"
Usage
iguana.logDebug(text [, message_id])
Add a Debug log entry with the given text. Use it to create your own Debug entries in the Iguana log.
Note: when the logging level for the channel is set to debug then iguana.logDebug()
will create log entries, otherwise it will not do anything.
By default Iguana uses its internally generated "Message IDs" to link log entries together, the message ID is created when the message is queued/logged. This ID is actually a string containing today's date followed by seven digits "YYYYMMDD-NNNNNNN". The message_id parameter can be used to modify the default linking behaviour: You can use the ID from a different message, or even use a "fictitious" ID to group messages.
When Iguana is processing a message from the queue, it automatically links the log entry to the that message. This occurs in Filter scripts, To Translator scripts, and LLP acknowledgment scripts (LLP Listener components using "Translator ACK"). You can use the message_id parameter to link to a different (or fictitious) message.
When Iguana is processing unqueued messages (From Translator and From HTTPS), then log entries cannot be linked automatically, because the message ID does not exist. You can use the message_id parameter to link to a specific (or fictitious) message.
Use iguana.messageId()
or queue.push()
to obtain a message ID.
Note: If you are working with an unqueued message you can use queue.push()
to push the message to the queue and generate a message ID.
Required Parameters
- text: The text to log string.
Optional Parameters
- message_id: The message ID of the message this log entry should be related to, in the format "YYYYMMDD-NNNNNNN" string.
For More Information
iguana.logError
Example Usage of iguana.logError(text [, message_id])
iguana.logError(text)
iguana.logError(text, iguana.messageId())
-- Working with queued messages (Filter, To Translator, and LLP Listener using "Translator ACK")
local text = 'This is an Error log entry'
-- link to the current message ID
iguana.logError(text)
iguana.logError(text, iguana.messageId()) -- identical result to the line above
-- include the message ID in the log entry
iguana.logError(text..iguana.messageId())
-- save linked messages in a database
Conn:execute{sql = "INSERT IguanaMessage ('MsgId', 'LogMsg') VALUES ("..iguana.messageId()..","..text..")}"
-- Working with unqueued messages (From Translator and From HTTPS)
local text = 'This is an Error log entry'
-- cannot link to an unqueued message
iguana.logError(text) -- creates a log entry, that is not linked to a message
iguana.logError(text, iguana.messageId()) -- this does not work
-- log the message first to create a message ID, then link to it
local MessageId = queue.push(text)
iguana.logError(text, MessageId())
-- include the message ID in the log entry
iguana.logError(text..iguana.messageId()) -- this does not work
iguana.logError(text..MessageId)
-- save linked messages in a database
Conn:execute{sql = "INSERT IguanaMessage ('MsgId', 'LogMsg') VALUES ("..MessageId..","..text..")}"
Usage
iguana.logError(text [, message_id])
Add a Error log entry with the given text. Use it to create your own Error entries in the Iguana log.
By default Iguana uses its internally generated "Message IDs" to link log entries together, the message ID is created when the message is queued/logged. This ID is actually a string containing today's date followed by seven digits "YYYYMMDD-NNNNNNN". The message_id parameter can be used to modify the default linking behaviour: You can use the ID from a different message, or even use a "fictitious" ID to group messages.
When Iguana is processing a message from the queue, it automatically links the log entry to the that message. This occurs in Filter scripts, To Translator scripts, and LLP acknowledgment scripts (LLP Listener components using "Translator ACK"). You can use the message_id parameter to link to a different (or fictitious) message.
When Iguana is processing unqueued messages (From Translator and From HTTPS), then log entries cannot be linked automatically, because the message ID does not exist. You can use the message_id parameter to link to a specific (or fictitious) message.
Use iguana.messageId()
or queue.push()
to obtain a message ID.
Note: If you are working with an unqueued message you can use queue.push()
to push the message to the queue and generate a message ID.
Required Parameters
- text: The text to log string.
Optional Parameters
- message_id: The message ID of the message this log entry should be related to, in the format "YYYYMMDD-NNNNNNN" string.
For More Information
iguana.logInfo
Example Usage of iguana.logInfo(text [, message_id])
-- Working with queued messages (Filter, To Translator, and LLP Listener using "Translator ACK")
local text = 'This is an Informational log entry'
-- link to the current message ID
iguana.logInfo(text)
iguana.logInfo(text, iguana.messageId()) -- identical result to the line above
-- include the message ID in the log entry
iguana.logInfo(text..iguana.messageId())
-- save linked messages in a database
Conn:execute{sql = "INSERT IguanaMessage ('MsgId', 'LogMsg') VALUES ("..iguana.messageId()..","..text..")}"
-- Working with unqueued messages (From Translator and From HTTPS)
local text = 'This is an Informational log entry'
-- cannot link to an unqueued message
iguana.logInfo(text) -- creates a log entry, that is not linked to a message
iguana.logInfo(text, iguana.messageId()) -- this does not work
-- log the message first to create a message ID, then link to it
local MessageId = queue.push(text)
iguana.logInfo(text, MessageId())
-- include the message ID in the log entry
iguana.logInfo(text..iguana.messageId()) -- this does not work
iguana.logInfo(text..MessageId)
-- save linked messages in a database
Conn:execute{sql = "INSERT IguanaMessage ('MsgId', 'LogMsg') VALUES ("..MessageId..","..text..")}"
Usage
iguana.logInfo(text [, message_id])
Add an Informational log entry with the given text. Use it to create your own Informational entries in the Iguana log.
Note: iguana.logInfo()
and print()
are very similar, as they both write informational messages to the logs (but print()
does not take the message_id
parameter).
By default Iguana uses its internally generated "Message IDs" to link log entries together, the message ID is created when the message is queued/logged. This ID is actually a string containing today's date followed by seven digits "YYYYMMDD-NNNNNNN". The message_id parameter can be used to modify the default linking behaviour: You can use the ID from a different message, or even use a "fictitious" ID to group messages.
When Iguana is processing a message from the queue, it automatically links the log entry to the that message. This occurs in Filter scripts, To Translator scripts, and LLP acknowledgment scripts (LLP Listener components using "Translator ACK"). You can use the message_id parameter to link to a different (or fictitious) message.
When Iguana is processing unqueued messages (From Translator and From HTTPS), then log entries cannot be linked automatically, because the message ID does not exist. You can use the message_id parameter to link to a specific (or fictitious) message.
Use iguana.messageId()
or queue.push()
to obtain a message ID.
Note: If you are working with an unqueued message you can use queue.push()
to push the message to the queue and generate a message ID.
Required Parameters
- text: The text to log string.
Optional Parameters
- message_id: The message ID of the message this log entry should be related to, in the format "YYYYMMDD-NNNNNNN" string.
For More Information
iguana.logWarning
Example Usage of iguana.logWarning(text [, message_id])
-- Working with queued messages (Filter, To Translator, and LLP Listener using "Translator ACK")
local text = 'This is a Warning log entry'
-- link to the current message ID
iguana.logWarning(text)
iguana.logWarning(text, iguana.messageId()) -- identical result to the line above
-- include the message ID in the log entry
iguana.logWarning(text..iguana.messageId())
-- save linked messages in a database
Conn:execute{sql = "INSERT IguanaMessage ('MsgId', 'LogMsg') VALUES ("..iguana.messageId()..","..text..")}"
-- Working with unqueued messages (From Translator and From HTTPS)
local text = 'This is a Warning log entry'
-- cannot link to an unqueued message
iguana.logWarning(text) -- creates a log entry, that is not linked to a message
iguana.logWarning(text, iguana.messageId()) -- this does not work
-- log the message first to create a message ID, then link to it
local MessageId = queue.push(text)
iguana.logWarning(text, MessageId())
-- include the message ID in the log entry
iguana.logWarning(text..iguana.messageId()) -- this does not work
iguana.logWarning(text..MessageId)
-- save linked messages in a database
Conn:execute{sql = "INSERT IguanaMessage ('MsgId', 'LogMsg') VALUES ("..MessageId..","..text..")}"
Usage
iguana.logWarning(text [, message_id])
Add a Warning log entry with the given text. Use it to create your own Warning entries in the Iguana log.
By default Iguana uses its internally generated "Message IDs" to link log entries together, the message ID is created when the message is queued/logged. This ID is actually a string containing today's date followed by seven digits "YYYYMMDD-NNNNNNN". The message_id parameter can be used to modify the default linking behaviour: You can use the ID from a different message, or even use a "fictitious" ID to group messages.
When Iguana is processing a message from the queue, it automatically links the log entry to the that message. This occurs in Filter scripts, To Translator scripts, and LLP acknowledgment scripts (LLP Listener components using "Translator ACK"). You can use the message_id parameter to link to a different (or fictitious) message.
When Iguana is processing unqueued messages (From Translator and From HTTPS), then log entries cannot be linked automatically, because the message ID does not exist. You can use the message_id parameter to link to a specific (or fictitious) message.
Use iguana.messageId()
or queue.push()
to obtain a message ID.
Note: If you are working with an unqueued message you can use queue.push()
to push the message to the queue and generate a message ID.
Required Parameters
- text: The text to log string.
Optional Parameters
- message_id: The message ID of the message this log entry should be related to, in the format "YYYYMMDD-NNNNNNN" string.
For More Information
iguana.messageId
Example Usage of iguana.messageId()
iguana.messageId()
iguana.logDebug(text, iguana.messageId())
Usage
iguana.messageId()
Get the message ID of the current message being processed. This is a unique message ID from Iguana's internal logging system, this ID is created when a message is queued/logged. The message ID is returned as a string containing today's date followed by seven digits "YYYYMMDD-NNNNNNN".
The message ID is very useful for grouping related messages, see the iguana.logInfo
help for more information.
Note: It should not be confused with other message IDs like HL7 message control IDs for instance.
Returns
- A unique Message ID string in the format "YYYYMMDD-NNNNNNN" string. OR nil if the message has not been placed in the queue nil.
For More Information
- The iguana module - interacting with Iguana's run-time system
- Understanding the Iguana Message Queue
iguana.project
iguana.project.files
Example Usage of iguana.project.files()
require('dateparse') function main(Data) local files = iguana.project.files() local mainPath = files['main.lua'] local dateparsePath = files['shared/dateparse.lua'] local hl7VmdPath = files['other/hl7.vmd'] end
Usage
iguana.project.files()
Retrieve a table of the files available to the project. The names of files (platform-independent) are used as keys for the table, and the corresponding values contain the file path for each file in the project (platform-dependent), relative to the Iguana install directory.
Returns
- A table of the files available to the project table.
iguana.project.guid
Example Usage of iguana.project.guid()
local guid = iguana.project.guid()
Usage
iguana.project.guid()
Get the guid of the project. This is a unique identifier for the project.
Returns
- The guid of the project string.
iguana.project.root
Example Usage of iguana.project.root()
print('The project is located in ' .. iguana.workingDir() .. iguana.project.root())
Usage
iguana.project.root()
Get the root directory of the project. The path returned is relative to the Iguana install directory.
Returns
- The root directory of the project string.
iguana.setChannelStatus
Example Usage of iguana.setChannelStatus{[color=<value>] [, text=<value>]}
iguana.setChannelStatus{ color='yellow', text='Connection lost; retrying...' }
Usage
iguana.setChannelStatus{[color=<value>] [, text=<value>]}
Set the status icon and text for the current channel.
For complicated scripts, you may want to provide more feedback than simple log entries. This function can change the status light on the dashboard and add text to the channel's tool-tip.
Color is restricted to yellow and green. Green is the normal, everything's fine color, which typically appears when your channel is running. If your script needs to wait a while to retry an operation, you may want to set its status light to yellow. Don't forget to change the color back to green when you are done; unless your channel stops, it will stay yellow.
You can omit the color or the text, but not both. Color defaults to green, and text defaults to an empty string.
Note: text can be anything you like, but it cannot be HTML.
Optional Parameters
- color: The desired icon color (yellow or green) string
- text: The status text to display string.
For More Information
iguana.setTimeout
Example Usage of iguana.setTimeout(seconds)
iguana.setTimeout(120)
Usage
iguana.setTimeout(seconds)
Set a new timeout for the current script. The timeout has no effect while in the editor.
Normally scripts are allowed 5 minutes to run. When they take too long, Iguana assumes that is due to a programming error or a blocking operation and stops the channel. If you know how long an operation will take you can set the timeout to avoid this. The timeout does not apply to individual actions: e.g., a database operation may take more time than allowed by iguana.setTimeout(), but the script will be stopped as soon as the database operation completes.
Required Parameters
- seconds: Timeout in seconds integer.
For More Information
iguana.status
Example Usage of local Xml = iguana.status()
local Xml = iguana.status() local S = xml.parse{data=Xml}
Usage
local Xml = iguana.status()
Like the web API /monitor_query this function gives an XML summary of Iguana's runtime state. This function is quite handy since it's simpler to call than the equivalent web api call.
Returns
- A string containing the XML summary of the channel status.
For More Information
iguana.stopOnError
Example Usage of iguana.stopOnError(stop)
iguana.stopOnError(false)
Usage
iguana.stopOnError(stop)
Enables/disables stopping the channel when errors occur.
Normally when an error occurs in your script Iguana will log the error and stop the channel - unless you catch it with pcall(). This function can be used to change that behaviour, causing Iguana to continue processing other messages after logging the error.
Required Parameters
- stop: If false, errors will not stop the channel boolean.
For More Information
iguana.version
Example Usage of iguana.version()
-- Enforce a policy whereby interfaces must be reviewed whenever -- the version of Iguana installed is changed. local versionInfo = iguana.version() if tostring(versionInfo) ~= '5.5.1' then error('This script has only been verified for usage with Iguana version 5.5.1. ' .. 'Please review the interface before attempting to run the channel again.') end
Usage
iguana.version()
Returns a table containing the version information for Iguana.
The table contains three fields, which make up the version info as a whole: the major number, the minor number, and the build number.
Returns
- Iguana version information table.
For More Information
iguana.webInfo
Example Usage of local T = iguana.webInfo()
local T = iguana.webInfo()
Usage
local T = iguana.webInfo()
This function returns a Lua table with information on Iguana's web server and HTTP channel server configuration. It is handy for writing scripts that access the web API of a local Iguana instance since it means you can find the right ports etc. to call automatically.
Returns
- A Lua table containing the data.
iguana.workingDir
Example Usage of iguana.workingDir()
local wd = iguana.workingDir()
-- read the Iguana configuration file local config = iguana.workingDir()..'IguanaConfiguration.xml' local f = io.open(config, 'r') f:read('*a') f:close()
Usage
iguana.workingDir()
Get the current working directory where the configuration files are located.
Returns
- The directory name string.
For More Information
io
io.close
Example Usage of io.close([file])
-- close "myFile"
io.close(myFile)
-- close the default output file io.close()
Usage
io.close([file])
Closes a file
. If a file
is not specified, it closes the default output file.
Note that files are automatically closed when their handles are garbage collected, but that takes an unpredictable amount of time to happen. It is usually best to call close() explicitly.
Equivalent to file:close()
.
Required Parameters
- file: Handle of the file to close object.
Returns
- True if file is closed, false is never returned as an error is raised instead boolean.
For More Information
- The io module - file operations
- File and FTP interfaces with Iguana.
- Online documentation for io.close.
io.filehandle
io.filehandle.close
Example Usage of file:close([file])
-- close "myFile"
myFile:close()
Usage
file:close([file])
Closes file
.
Note: that files are automatically closed when their handles are garbage collected, but that takes an unpredictable amount of time to happen. It is usually best to call close() explicitly.
Returns
- True if file is closed, false is never returned as an error is raised instead boolean.
For More Information
- The io.filehandle module - methods for the file object
- File and FTP interfaces with Iguana.
- Online documentation for file:close.
- Understanding Lua OO syntax: what the colon operator means
io.filehandle.flush
Example Usage of file:flush()
local status = myFile:flush()
Usage
file:flush()
Causes any data written to file
to be saved to disk.
Note: data written to a file may be cached for performance, the flush
command saves it to disk.
Returns
- True if file is written, false is never returned as an error is raised instead boolean.
For More Information
- The io.filehandle module - methods for the file object
- Online documentation for file:flush.
- Understanding Lua OO syntax: what the colon operator means
io.filehandle.lines
Example Usage of file:lines()
local iterator = myFile:lines()
-- read the Iguana configuration file
local configFile = io.open('IguanaConfiguration.xml')
for line in configFile:lines() do
trace(line)
-- add processing here
end
configFile:close()
Usage
file:lines()
Returns an iterator function that, each time it is called, returns a new line from the file. Therefore, the construction for line in file:lines() do body end
will iterate over all lines of the file. When the iterator function detects the end of file, it returns nil (to finish the loop) and automatically closes the file.
(Unlike io.lines
, this function does not close the file when the loop ends.)
Returns
- The next line of data from the file, or nil when eof reached string or nil.
For More Information
- The io.filehandle module - methods for the file object
- Online documentation for file:lines.
- Understanding Lua OO syntax: what the colon operator means
io.filehandle.read
Example Usage of file:read(format)
local result = myFile:read('*a')
Usage
file:read(format)
Reads file
, according to the given format, which specify what to read. For each format, the function returns a string (or a number) with the characters read, or nil if it cannot read data with the specified format. When called without formats, it uses a default format that reads the entire next line (see below).
The available formats are:
Format | Description |
---|---|
"*n" | reads a number: this is the only format that returns a number instead of a string. |
"*a" | reads the whole file, starting at the current position. On end of file, it returns the empty string. |
"*l" | reads the next line (skipping the end of line), returning nil on end of file. This is the default format. |
number | reads a string with up to this number of characters, returning nil on end of file. If number is zero, it reads nothing and returns an empty string, or nil on end of file. |
Required Parameters
- value: Format string.
Returns
- A string (or a number) with the characters read, or nil if it cannot read data using the specified format string, number or nil.
For More Information
- The io.filehandle module - methods for the file object
- File and FTP interfaces with Iguana.
- Online documentation for file:read.
- Understanding Lua OO syntax: what the colon operator means
io.filehandle.seek
Example Usage of file:seek([whence] [, offset])
myFile:seek("end",-100)
Usage
file:seek([whence] [, offset])
Sets and gets the file position, measured from the beginning of the file, to the position given by offset
plus a base specified by the string whence
, as follows:
Offset | Description |
---|---|
"set" | base is position 0 (beginning of the file). |
"cur" | base is current position. |
"end" | base is end of file. |
In case of success, function seek
returns the final file position, measured in bytes from the beginning of the file. If this function fails, it returns nil, plus a string describing the error.
The default value for whence
is "cur"
, and for offset
is 0. Therefore, the call file:seek()
returns the current file position, without changing it; the call file:seek("set")
sets the position to the beginning of the file (and returns 0); and the call file:seek("end")
sets the position to the end of the file, and returns its size.
Required Parameters
- offset: Offset from the base.
- whence: Base for the position.
Returns
- The final file position, measured in bytes from the beginning of the file. If this function fails, it returns nil, plus a string describing the error.
For More Information
- The io.filehandle module - methods for the file object
- File and FTP interfaces with Iguana.
- Online documentation for file:seek.
- Understanding Lua OO syntax: what the colon operator means
io.filehandle.setvbuf
Example Usage of file:setvbuf(mode [, size])
myFile:setvbuf("line",80)
Usage
file:setvbuf(mode [, size])
Sets the buffering mode for an output file. There are three available modes:
Offset | Description |
---|---|
"no" | no buffering: the result of any output operation appears immediately. |
"full" | full buffering: output operation is performed only when the buffer is full (or when you explicitly flush the file (see file:flush )). |
"line" | line buffering: output is buffered until a newline is output or there is any input from some special files (such as a terminal device). |
For the last two cases, size
specifies the size of the buffer, in bytes. The default is an appropriate size.
Required Parameters
- mode: Buffering mode.
- size: Size of buffer.
For More Information
- The io.filehandle module - methods for the file object
- File and FTP interfaces with Iguana.
- Online documentation for file:setvbuf.
- Understanding Lua OO syntax: what the colon operator means
io.filehandle.write
Example Usage of file:write(<value> [, <value>] [, <value>] [, ...])
local status = file:write('Write some ', strings and numbers', 1, 2, 3, 'to a file')
Usage
file:write(<value> [, <value>] [, <value>] [, ...])
Writes the value of each of its arguments to file
. The arguments must be strings or numbers. To write other values, use tostring or string.format before write.
Required Parameters
- value: Multiple parameters: Values to write to the file string or integer.
Returns
- True if file is written, false is never returned as an error is raised instead boolean.
For More Information
- The io.filehandle module - methods for the file object
- File and FTP interfaces with the translator.
- Online documentation for file:write.
- Understanding Lua OO syntax: what the colon operator means
io.flush
Example Usage of io.flush()
local status = io.flush()
Usage
io.flush()
Saves any written data to file
, equivalent to file:flush
over the default output file.
Returns
- True if file is written, false is never returned as an error is raised instead boolean.
For More Information
io.input
Example Usage of io.input([file])
-- use a file handle to set the default local result = io.input(myFile)
-- open the named file and set it to default local result = io.input("myFile")
Usage
io.input([file])
When called with a file name, it opens the named file (in text mode), and sets its handle as the default input file. When called with a file handle, it simply sets this file handle as the default input file. When called without parameters, it returns the current default input file.
In case of errors this function raises the error, instead of returning an error code.
Optional Parameters
- file: Name of the new default file or a file handle string or file handle object.
Returns
- A new file handle to the default input file, or, in case of errors, nil file handle object or nil.
For More Information
- The io module - file operations
- File and FTP interfaces with Iguana.
- Online documentation for io.input.
io.lines
Example Usage of io.lines([filename])
local iterator = io.lines([filename])
-- read the Iguana configuration file local config = io.lines('IguanaConfiguration.xml') for line in config do trace(line) -- add processing here end
Usage
io.lines([filename])
Opens the given file name in read mode and returns an iterator function that, each time it is called, returns a new line from the file. Therefore, the construction for line in io.lines(filename) do body end
will iterate over all lines of the file. When the iterator function detects the end of file, it returns nil (to finish the loop) and automatically closes the file.
The call io.lines()
(with no file name) is equivalent to io.input():lines()
; that is, it iterates over the lines of the default input file. In this case it does not close the file when the loop ends.
Optional Parameters
- filename: Name of the file to open string.
Returns
- The next line of data from the file, or nil when eof reached string or nil.
For More Information
io.open
Example Usage of io.open(filename [, mode])
local f, error = io.open('myFile')
local f=io.open('myFile.txt','w+') f:write('Write a string and then a number',23) f:close() local f=io.open('myFile.txt','r')
f:read()
Usage
io.open(filename [, mode])
This function opens a file, in the mode specified in the string mode
. It returns a new file handle, or, in case of errors, nil plus an error message.
The mode
string can be any of the following:
Format | Description |
---|---|
"r" | read mode (the default). |
"w" | write mode. |
"a" | append mode. |
"r+" | update mode, all previous data is preserved. |
"w+" | update mode, all previous data is erased. |
"a+" | append update mode, previous data is preserved, writing is only allowed at the end of file. |
The mode
string can also have a 'b
' at the end, which is needed in some systems to open the file in binary mode. This string is exactly what is used in the standard C function fopen
.
Required Parameters
- file: Name of the file to opened string.
Optional Parameters
- mode: Mode to open the file string.
Returns
- A new file handle, or, in case of errors, nil file handle object or nil.
- An error message if an error occurs string.
For More Information
- The io module - file operations
- File and FTP interfaces with Iguana.
- Online documentation for io.open.
io.output
Example Usage of io.output([file])
-- use a file handle to set the default local result = io.output(myFile)
-- open the named file and set it to default local result = io.output("myFile")
Usage
io.output([file])
When called with a file name, it opens the named file (in text mode), and sets its handle as the default output file. When called with a file handle, it simply sets this file handle as the default output file. When called without parameters, it returns the current default output file.
In case of errors this function raises the error, instead of returning an error code.
Optional Parameters
- file: Name of the new output file string or nil.
Returns
- A new file handle to the default output file, or, in case of errors, nil file handle object or nil.
For More Information
- The io module - file operations
- File and FTP interfaces with Iguana.
- Online documentation for io.output.
io.popen
Example Usage of io.popen(prog [, mode])
local h = io.popen('myProgram') local result = h:read()
Usage
io.popen(prog [, mode])
Starts program prog
in a separated process and returns a file handle that you can use to read data from this program (if mode
is "r"
, the default) or to write data to this program (if mode
is "w"
).
This function is system dependent and is not available on all platforms.
Required Parameters
- prog: Program to run string.
Optional Parameters
- mode: Mode to run the program string.
Returns
- A file handle that you can use to read/write data from this program.
For More Information
- Using
io.popen()
. - Using Iguana to Import Backed Up Logs: The code has three simple examples of
io.popen()
. - Streaming and Filtering Data: The code uses
io.popen()
in a more sophisticated manner . - The io module - file operations
- Online documentation for io.popen.
io.read
Example Usage of io.read(format)
local result = io.read('*a')
Usage
io.read(format)
Reads the default input file, according to the given format, which specify what to read. For each format, the function returns a string (or a number) with the characters read, or nil if it cannot read data with the specified format. When called without formats, it uses a default format that reads the entire next line (see below).
The available formats are:
Format | Description |
---|---|
"*n" | reads a number: this is the only format that returns a number instead of a string. |
"*a" | reads the whole file, starting at the current position. On end of file, it returns the empty string. |
"*l" | reads the next line (skipping the end of line), returning nil on end of file. This is the default format. |
number | reads a string with up to this number of characters, returning nil on end of file. If number is zero, it reads nothing and returns an empty string, or nil on end of file. |
Equivalent to io.input():read
.
Required Parameters
- value: Format string.
Returns
- A string (or a number) with the characters read, or nil if it cannot read data using the specified format string, number or nil.
For More Information
- The io module - file operations
- File and FTP interfaces with Iguana.
- Online documentation for io.read.
io.type
Example Usage of io.type(obj)
local status = io,type()
Usage
io.type(obj)
Checks whether obj
is a valid file handle. Returns the string "file"
if obj
is an open file handle, "closed file"
if obj
is a closed file handle, or nil if obj
is not a file handle.
Required Parameters
- obj: Object to be checked object.
Returns
- String indicating file status, or nil if "obj" is not a file string or nil.
For More Information
- The io module - file operations
- File and FTP interfaces with Iguana.
- Online documentation for io.type.
io.write
Example Usage of io.write(<value> [, <value>] [, <value>] [, ...])
local status = io.write('Write some ', strings and numbers', 1, 2, 3, 'to a file')
io.output('myFile') io.input('myFile') io.write('Write a string and then a number',23) io.flush() io.read()
Usage
io.write(<value> [, <value>] [, <value>] [, ...])
Writes the value of each of its arguments to the file. The arguments must be strings or numbers. To write other values, use tostring or string.format before write. Equivalent to io.output():write
.
Required Parameters
- value: Multiple parameters: Values to write to the file string or integer.
Returns
- True if file is written, false is never returned as an error is raised instead boolean.
For More Information
- The io module - file operations
- File and FTP interfaces with the translator.
- Online documentation for io.write.
json
json.createObject
Example Usage of json.createObject()
local obj = json.createObject{data=Data}
-- show that createObject() just returns a "disguised" Lua table local obj = json.createObject() -- annotation = json_empty_object trace(type(obj)) -- object type = table
Usage
json.createObject()
Creates an empty JSON object. This is useful for distinguishing between an empty object and an empty Lua table.
Note: you might expect that this function would return a node tree - it does not, it returns a Lua table labelled/annotated as "json_empty_object". The label is only for convenience/documentation purposes - you can just use tables for JSON objects (see examples).
Returns
- An empty JSON object table.
For More Information
- The json module - working with JSON
- Using JSON in the translator
- Serializing as JSON
- Node types for Iguana node trees
json.parse
Example Usage of json.parse{data=<value>} or json.parse(<value>)
local Msg = json.parse{data=Data}
Usage
json.parse{data=<value>} or json.parse(<value>)
Parses a message in JSON format into its components and creates a table containing these components.
Required Parameters
- data: A string containing the JSON to be parsed string.
Returns
- A Lua table containing the parsed data table.
For More Information
- The json module - working with JSON
- Using JSON in the translator
- Serializing as JSON
- Node types for Iguana node trees
json.serialize
Example Usage of json.serialize{data=<value> [, compact=true|false, alphasort=true|false]}
local Json = json.serialize{data=Data}
Usage
json.serialize{data=<value> [, compact=true|false, alphasort=true|false]}
Serializes a Lua table as a JSON formatted string.
Required Parameters
- data: A table from which JSON will be generated table.
Optional Parameters
- compact: If true, output will not be pretty-printed boolean.
- alphasort: Sort table keys alphabetically if true, default is false boolean.
Returns
- The Lua table serialized as JSON string.
For More Information
math
math.abs
Usage
math.abs(x)
Calculates the absolute value of a number.
Required Parameters
- x: The number to calculate the absolute value from number.
Returns
- The absolute value of
x
number.
For More Information
math.acos
Usage
math.acos(x)
Calculates the arc cosine (in radians) of a number.
Required Parameters
- x: The number to generate the arc cosine from number.
Returns
- The arc cosine of
x
number.
For More Information
math.asin
Usage
math.asin(x)
Calculates an arc sine.
Required Parameters
- x: The number to calculate the arc sine from number.
Returns
- The arc sine of
x
(in radians) number.
For More Information
math.atan
Usage
math.atan(x)
Calculates an arc tangent (in radians) of a number.
Required Parameters
- x: The number to calculate the arc tangent from number.
Returns
- The arc tangent of
x
number.
For More Information
math.atan2
Usage
math.atan2(y, x)
Calculates an arc tangent(in radians) of y/x
, but uses the signs of both parameters to find the quadrant of the result. It also correctly handles the case when the second parameter (x
) is zero.
Required Parameters
- y: The first number used to calculate the arc tangent number.
- x: The second number used to calculate the arc tangent number.
Returns
- The arc tangent of
y/x
(in radians) number.
For More Information
math.ceil
Usage
math.ceil(x)
Calculates the smallest integer larger than or equal to a number.
Required Parameters
- x: The number to calculate the ceiling from number.
Returns
- The smallest integer larger than or equal to
x
number.
For More Information
math.cos
Usage
math.cos(x)
Calculates the cosine of an angle (in radians).
Required Parameters
- x: The angle to calculate the cosine from number.
Returns
- The cosine of
x
number.
For More Information
math.cosh
Usage
math.cosh(x)
Calculates an hyperbolic cosine.
Required Parameters
- x: The number to calculate the hyperbolic cosine from number.
Returns
- The hyperbolic cosine of
x
number.
For More Information
math.deg
Usage
math.deg(x)
Converts an angle from radians to degrees.
Required Parameters
- x: The angle (in radians) to convert to degrees number.
Returns
- The angle
x
in degrees (converted from radians) number.
For More Information
math.exp
Usage
math.exp(x)
Calculates an exponential value.
Required Parameters
- x: The number to calculate the exponent from number.
Returns
- Exponential value of ex number.
For More Information
math.floor
Usage
math.floor(x)
Calculates the largest integer smaller than or equal to a number.
Required Parameters
- x: The number to calculate the floor from number.
Returns
- The largest integer smaller than or equal to
x
number.
For More Information
math.fmod
Usage
math.fmod(x, y)
Calculates a remainder of the division of two numbers and rounds the quotient towards zero.
Note: math.mod was renamed to math.fmod in Lua 5.1
Required Parameters
- x: The first number used to calculate the remainder number.
- y: The second number used to calculate the remainder number.
Returns
- The remainder of the division of
x
byy
number.
For More Information
math.frexp
Usage
math.frexp(x)
Calculates m
and e
such that x = m2e, e
is an integer and the absolute value of m
is in the range [0.5, 1) (or zero when x
is zero).
Required Parameters
- x: The number to calculate from number.
Returns
- The number
m
to be multiplied by 2e (i.e., m2e) number. - A number
e
to be used as the power of 2 (i.e., m2e) number.
For More Information
math.ldexp
Usage
math.ldexp(m, e)
Multiplies a number m
by an integer power of two, i.e., m2e (where e
is an integer).
Required Parameters
- m: The number to calculate the exponent from number.
- e: The integer to use as the exponent integer.
Returns
- The calculated value of m2e number.
For More Information
math.log
Usage
math.log(x)
Calculates a natural logarithm.
Required Parameters
- x: The number to calculate the logarithm from number.
Returns
- The natural logarithm of
x
number.
For More Information
math.log10
Usage
math.log10(x)
Calculates a base-10 logarithm.
Required Parameters
- x: The number to calculate the base-10 logarithm from number.
Returns
- The base-10 logarithm of
x
number.
For More Information
math.max
Usage
math.max(x, ...)
Calculates the maximum value among its arguments.
Required Parameters
- x: Multiple parameters: the numbers to calculate the maximum from number.
Returns
- The maximum value number.
For More Information
math.min
Usage
math.min(x, ...)
Calculates the minimum value among its arguments.
Required Parameters
- x: Multiple parameters: the numbers to calculate the minimum from number.
Returns
- The minimum value number.
For More Information
math.modf
Usage
math.modf(x)
Calculates the integral and the fractional parts of a number.
Required Parameters
- x: The number to calculate the integral and the fractional parts from number.
Returns
- The integral part of
x
integer. - The fractional part of
x
number.
For More Information
math.pow
Usage
math.pow(x, y)
Raises a number to a power. (You can also use the expression x^y
to compute this value.)
Required Parameters
- x: The number to be raised to a power number.
- y: The number to be used as the power number.
Returns
- The calculated value of xy number.
For More Information
math.rad
Usage
math.rad(x)
Converts an angle from degrees to radians.
Required Parameters
- x: The angle (in degrees) to convert to radians number.
Returns
- The angle
x
in radians (converted from degrees) number.
For More Information
math.random
Usage
math.random([m [, n]])
This function is an interface to the simple pseudo-random generator function rand
provided by ANSI C. (No guarantees can be given for its statistical properties.)
When called without arguments, returns a uniform pseudo-random real number in the range [0,1). When called with an integer number m
, math.random
returns a uniform pseudo-random integer in the range [1, m). When called with two integer numbers m
and n
, math.random
returns a uniform pseudo-random integer in the range [m, n).
Optional Parameters
- m: An integer representing the end of the range (or the start of range if the 2nd param "m" is supplied) integer.
- n: An integer representing the end of the range integer.
Returns
- A pseudo-random number number.
For More Information
math.randomseed
Usage
math.randomseed(x)
Sets the "seed" for the pseudo-random generator: equal seeds produce equal sequences of numbers.
Required Parameters
- x: The number to use as the "seed" for the pseudo-random generator number.
For More Information
math.sin
Usage
math.sin(x)
Calculates the sine of an angle (in radians).
Required Parameters
- x: The angle (in radians) to calculate the sine from number.
Returns
- The sine of
x
number.
For More Information
math.sinh
Usage
math.sinh(x)
Calculates a hyperbolic sine.
Required Parameters
- x: The number to calculate the hyperbolic sine from number.
Returns
- The hyperbolic sine of
x
number.
For More Information
math.sqrt
Usage
math.sqrt(x)
Calculates the square root of a number. (You can also use the expression x^0.5
to compute this value.)
Required Parameters
- x: The number to calculate the square root from number.
Returns
- The square root of
x
number.
For More Information
math.tan
Usage
math.tan(x)
Calculates a tangent of an angle (in radians).
Required Parameters
- x: The angle to calculate the tangent from number.
Returns
- The tangent of
x
number.
For More Information
math.tanh
Usage
math.tanh(x)
Calculates an hyperbolic tangent.
Required Parameters
- x: The number to calculate the hyperbolic tangent from number.
Returns
- The hyperbolic tangent of
x
number.
For More Information
net
net.ftp
net.ftp.delete
Example Usage of FtpConn:delete{remote_path=<value> [, debug=<value>]}
local FtpConn = net.ftp.init{server='example', username='user', password='password'} -- recommended usage: FtpConn:delete{remote_path='afile.txt'} -- which is shorthand for: net.ftp.delete(FtpConn, {remote_path='afile.txt'})
-- delete a file
FtpConn:delete{remote_path='/fox_out/test.txt'}
-- use the 'live' parameter to delete a file in the editor
-- cache the connection parameters, set live = true
local FtpConn = net.ftp.init{server='foxton_ftp', username='test_ftp',password='secret', live=true}
-- delete the file
FtpConn:delete{remote_path='/fox_out/test.txt'}
Usage
FtpConn:delete{remote_path=<value> [, debug=<value>]}
Deletes a file (or files) from the specified ftp server.
Required Parameters
- id: Connection id returned from net.ftp.init table.
Note: This is only required for the functional syntax (it is implicit in the OO/colon syntax) - remote_path: The name of the file(s) to be deleted on the remote server string.
Note: The file name may include a path and/or an extension, and you can use wildcards for multiple files (but none of these are required)
Optional Parameters
- debug: When true return verbose debug information, errors thrown will also contain debug information (defaults to false) boolean.
Returns
- True if successful false is never returned, errors are thrown instead boolean
- Debug information (if requested) string.
For More Information
- Using File and FTP Interfaces
- The net API reference: File transfer and email using the FTP, FTPS, HTTP, SFTP and SMTP message protocols
- Wikipedia: File Transfer Protocols (ftp)
- Understanding Lua OO syntax: what the colon operator means
net.ftp.get
Example Usage of FtpConn:get{remote_path=<value> [, local_path=<value>] [, ...]}
local FtpConn = net.ftp.init{server='example', username='user', password='password'}
-- recommended usage:
FtpConn:get{remote_path='afile.txt'}
-- which is shorthand for:
net.ftp.get(FtpConn, {remote_path='afile.txt'})
--How to download text and binary files
-- cache the connection parameters
local FtpConn = net.ftp.init{server='foxton_ftp', username='test_ftp',password='secret'}
-- get (download) a text file (opens/closes an ASCII connection)
FtpConn:get{remote_path='/fox_out/test.png',local_path='temp/test.txt'}
-- get (download) a binary (picture) file (opens/closes a binary connection)
FtpConn:get{remote_path='/fox_out/test.png',local_path='temp/test.png'}
Usage
FtpConn:get{remote_path=<value> [, local_path=<value>] [, ...]}
Get a single file from the remote server.
The local_path is relative to the Iguana install directory. So the absolute path for 'temp/myfile.txt' is something like 'c:/program files/interfaceware/iguana/temp/myfile.txt (Windows), or '/Users/julianmuir/Downloads/temp/myfile.txt' (Mac, Linux, Unix). You can also specify an absolute path.
Note: The file type is detected and the correct transfer mode, 'ascii' (text) or 'binary', is chosen automatically.
Required Parameters
- id: Connection id returned from net.ftp.init table.
Note: This is only required for the functional syntax (it is implicit in the OO/colon syntax) - remote_path: The name of the file to be downloaded from the remote server string.
Note: The name may include a path and/or an extension (but neither of these are required)
Optional Parameters
- local_path: Save the file using this name instead of returning it as a string string.
Note: The name may include a path and/or an extension (but neither of these are required) - overwrite: Allow local_path to be overwritten if it already exists boolean.
- debug: When true return verbose debug information, errors thrown will also contain debug information (defaults to false) boolean.
Returns
- The contents of the file (or true if local_path is used false is never returned, errors are thrown instead) string or boolean
- Debug information (if requested) string.
For More Information
- Using File and FTP Interfaces
- The net API reference: File transfer and email using the FTP, FTPS, HTTP, SFTP and SMTP message protocols
- Wikipedia: File Transfer Protocols (ftp)
- Understanding Lua OO syntax: what the colon operator means
net.ftp.init
Example Usage of net.ftp.init{server=<value>, username=<value>, ...}
local FtpConn = net.ftp.init{server='example', username='user', password='password'}
-- cache the connection parameters
local FtpConn = net.ftp.init{server='foxton_ftp', username='test_ftp',password='secret'}
-- get (download) a text file (opens/closes an ASCII connection)
FtpConn:get{remote_path='/Users/foxton_ftp/test.png',local_path='temp/test.txt'}
-- get (download) a binary (picture) file (opens/closes a binary connection)
FtpConn:get{remote_path='/Users/foxton_ftp/test.png',local_path='temp/test.png'}
-- active connection on default IP & default port
local FtpConn = net.ftp.init{server='foxton_ftp', username='test_ftp',password='secret',active='-'}
-- active connection on default IP & default port
-- restrict to using IPV4 addressing (no_eprt=true), no_eprt can be added to any of the following commands
local FtpConn = net.ftp.init{server='foxton_ftp', username='test_ftp',password='secret',active='-', no_eprt=true}
-- active connection on default IP & port specified
local FtpConn = net.ftp.init{server='foxton_ftp', username='test_ftp',password='secret',active=':32000'}
-- active connection on default IP & with local machine name specified
local FtpConn = net.ftp.init{server='foxton_ftp', username='test_ftp',password='secret',active='foxton-pc1'}
-- active connection on default IP & with local machine name & port specified
local FtpConn = net.ftp.init{server='foxton_ftp', username='test_ftp',password='secret',active='foxton-pc1:32000'}
-- active connection on default IP & with local machine IP specified
local FtpConn = net.ftp.init{server='foxton_ftp', username='test_ftp',password='secret',active='10.211.55.12'}
-- active connection on default IP & with local machine IP and port range specified
local ftpConn = net.ftp.init{server='foxton_ftp', username='test_ftp',password='secret',active='10.211.55.12:32000-33000'}
Usage
net.ftp.init{server=<value>, username=<value>, ...}
Initializes a new FTP connection. The connection defaults to passive mode, you can also create an active connection (using the 'active' parameter). Other options include specifying IPV4 only (using 'no_eprt' or 'no_epsv'), etc.
When a command is run the file type is detected and the correct transfer mode, 'ascii' (text) or 'binary', is chosen automatically.
Note: The 'init' command only caches the connection parameters, it does not open a connection. The actual connections are managed automatically, a connection is opened and closed each time an ftp command is issued (get, put etc). Because of this there never a need to 'close' an FTP connection.
If you need help with the advanced ftp options please contact support at support@interfaceware.com.
Required Parameters
- server: The server to connect to string.
- username: The remote user to login as string.
Optional Parameters
- password: The password to authenticate with string.
- port: The port to use (defaults to 21) integer.
- timeout: Timeout for operations (defaults to 15 seconds) integer.
- live: Enable write operations (put, rename, delete) while in the editor boolean.
- active: Open a local port for active FTP mode, and send a PORT command with the given local IP/hostname (or network interface on Unix). Use '-' for the default local IP address and a random port. A particular port or range of ports to use can be added after the IP/hostname, e.g. ':32000', '192.168.1.2:32000' or 'eth0:32000-33000'. Note that '-:32000' is not valid; omit the hyphen when specifying a port for the default IP. string.
- no_eprt: Active mode: do not try EPRT or LPRT before trying PORT boolean.
- no_epsv: Passive mode: do not try EPSV before PASV, just use PASV boolean.
- skip_pasv_ip: Passive mode: ignore the IP address sent by the server; instead open the new port on the same machine boolean.
- use_pret: Send a non-standard PRET command before PASV or EPSV boolean.
- alt_auth: Command to send when USER/PASS authentication fails string.
- acct: Account data to send when asked by some atypical servers string.
- on_ready: An array of commands to be issued after setting the transfer mode, before any actual transfers are started table.
- use_ssl: Enable explicit SSL mode (optional, not enabled by default). Valid options: 'all' (always enable), 'try' (optional), 'control' (control connection) string.
- certificate_file: The name of your certificate file string.
- certificate_type: Your certificate's type: PEM (default) or DER string.
- private_key_file: The name of your private key file string.
- private_key_pass: The password to access your private key string.
- private_key_type: Your private key's type: PEM (default), DER, or ENG string.
- ssl_engine: The engine to use with 'key_type' ENG string.
- verify_peer: Verify peer certificate (default true) boolean.
- verify_host: Verify host certificate matches URL (default true) boolean.
- ca_file: The certificate(s) file to use for peer verification string.
- issuer_cert: The PEM certificate file to validate the issuer of the peer's certificate during peer validation string.
- crl_file: The name of the certificate revocation list to use during peer validation string.
- ssl_version: Use a particular SSL version. Normally ssl-v3 is tried first, then tls-v1; ssl-v2 is never used automatically string.
Returns
- a connection object table.
For More Information
- Using File and FTP Interfaces
- The net API reference: File transfer and email using the FTP, FTPS, HTTP, SFTP and SMTP message protocols
- Wikipedia: File Transfer Protocols (ftp)
net.ftp.list
Example Usage of FtpConn:list{remote_path=<value> [, debug=<value>]}
local FtpConn = net.ftp.init{server='example', username='user', password='password'} -- recommended usage: FtpConn:list{remote_path='/'} -- which is shorthand for: net.ftp.list(FtpConn, {remote_path='/'})
FtpConn:list{remote_path=''} -- users home directory
FtpConn:list{remote_path='/'} -- ftp root directory
FtpConn:list{remote_path='/fox_out/'} -- user specified data directory
Usage
FtpConn:list{remote_path=<value> [, debug=<value>]}
List the contents of a remote path.
Required Parameters
- id: Connection id returned from net.ftp.init table.
Note: This is only required for the functional syntax (it is implicit in the OO/colon syntax) - remote_path: The directory path on the remote server to list the contents for string.
Optional Parameters
- debug: When true return verbose debug information, errors thrown will also contain debug information (defaults to false) boolean.
Returns
- An array of {filename, is_retrievable} values table
- Debug information (if requested) string.
For More Information
- How to use the ftp list command
- Using File and FTP Interfaces
- The net API reference: File transfer and email using the FTP, FTPS, HTTP, SFTP and SMTP message protocols
- Wikipedia: File Transfer Protocols (ftp)
- Understanding Lua OO syntax: what the colon operator means
net.ftp.put
Example Usage of FtpConn:put{remote_path=<value> [, data=<value>] [, ...]}
local FtpConn = net.ftp.init{server='example', username='user', password='password'} -- recommended usage: FtpConn:put{remote_path='afile.txt', data=Data} -- which is shorthand for: net.ftp.put(FtpConn, {remote_path='afile.txt', data=Data})
--How to upload text and binary files
-- cache the connection parameters
local FtpConn = net.ftp.init{server='foxton_ftp', username='test_ftp',password='secret'}
-- put (upload) a text file (opens/closes an ASCII connection)
FtpConn:put{remote_path='/fox_in/test.png',local_path='temp/test.txt'}
-- put (upload) a binary (picture) file (opens/closes a binary connection)
FtpConn:put{remote_path='/fox_in/test.png',local_path='temp/test.png'}
Usage
FtpConn:put{remote_path=<value> [, data=<value>] [, ...]}
Put a single file on the specified server.
The local_path is relative to the Iguana install directory. So the absolute path for 'temp/myfile.txt' is something like 'c:/program files/interfaceware/iguana/temp/myfile.txt (Windows), or '/Users/julianmuir/Downloads/temp/myfile.txt' (Mac, Linux, Unix). You can also specify an absolute path.
Note: The file type is detected and the correct transfer mode, 'ascii' (text) or 'binary', is chosen automatically.
Required Parameters
- id: Connection id returned from net.ftp.init table.
Note: This is only required for the functional syntax (it is implicit in the OO/colon syntax) - remote_path: The name to be used for the uploaded file on the remote server string.
Note: The file name may include a path and/or an extension (but neither of these are required)
Optional Parameters
- data: Data to upload string.
- local_path: The name of a local file to be uploaded to the remote server. If specified, the 'data' parameter is ignored string.
Note: The file name may include a path and/or an extension (but neither of these are required) - overwrite: Allow remote_path to be overwritten if it already exists boolean.
- tmp_postfix: If not nil the file will first be uploaded as remote_path..tmp_postfix, and then renamed remote_path. Useful to ensure remote processes do not read a partially uploaded file string.
- debug: When true return verbose debug information, errors thrown will also contain debug information (defaults to false) boolean.
Returns
- True if successful false is never returned, errors are thrown instead boolean
- Debug information (if requested) string.
For More Information
- Using File and FTP Interfaces
- The net API reference: File transfer and email using the FTP, FTPS, HTTP, SFTP and SMTP message protocols
- Wikipedia: File Transfer Protocols (ftp)
- Understanding Lua OO syntax: what the colon operator means
net.ftp.rename
Example Usage of FtpConn:rename{remote_path=<value>, new_remote_path=<value>, ...}
local FtpConn = net.ftp.init{server='example', username='user', password='password'} -- recommended usage: FtpConn:rename{remote_path='old_name.txt', new_remote_path='new_name.txt'} -- which is shorthand for: net.ftp.rename(FtpConn, {remote_path='old_name.txt', new_remote_path='new_name.txt'})
-- move a file to a 'processed' directory
FtpConn:rename{
remote_path='/fox_out/test.txt',
new_remote_path='/fox_processed/test'..os.date()..'.txt'
}
-- use the 'live' parameter to rename a file in the editor
-- cache the connection parameters, set live = true
local FtpConn = net.ftp.init{server='foxton_ftp', username='test_ftp',password='secret', live=true}
-- rename the file
FtpConn:rename{remote_path='/fox_out/test.txt', new_remote_path='/fox_processed/test_old'.txt'}
Usage
FtpConn:rename{remote_path=<value>, new_remote_path=<value>, ...}
Renames a single file or directory on the remote server.
Required Parameters
- id: Connection id returned from net.ftp.init table.
Note: This is only required for the functional syntax (it is implicit in the OO/colon syntax) - remote_path: The old name of the file or directory to be renamed on the remote server string.
Note: The name may include a path and/or an extension (but neither of these are required) - new_remote_path: The new name of the file or directory to be renamed on the remote server string.
Note: The name may include a path and/or an extension (but neither of these are required)
Optional Parameters
- debug: When true return verbose debug information, errors thrown will also contain debug information (defaults to false) boolean.
Returns
- True if successful false is never returned, errors are thrown instead boolean
- Debug information (if requested) string.
For More Information
- Using File and FTP Interfaces
- The net API reference: File transfer and email using the FTP, FTPS, HTTP, SFTP and SMTP message protocols
- Wikipedia: File Transfer Protocols (ftp)
- Understanding Lua OO syntax: what the colon operator means
net.ftps
net.ftps.delete
Example Usage of FtpsConn:delete{remote_path=<value> [, debug=<value>]}
local FtpsConn = net.ftps.init{server='example', username='user', password='password'} -- recommended usage: FtpsConn:delete{remote_path='afile.txt'} -- which is shorthand for: net.ftps.delete(FtpsConn, {remote_path='afile.txt'})
-- delete a file
FtpsConn:delete{remote_path='/fox_out/test.txt'}
-- use the 'live' parameter to delete a file in the editor
-- cache the connection parameters, set live = true
local FtpsConn = net.ftps.init{server='foxton_ftps', username='test_ftps',password='secret', live=true}
-- delete the file
FtpsConn:delete{remote_path='/fox_out/test.txt'}
Usage
FtpsConn:delete{remote_path=<value> [, debug=<value>]}
Deletes a file from the specified ftp server.
Required Parameters
- id: Connection id returned from net.ftps.init table.
Note: This is only required for the functional syntax (it is implicit in the OO/colon syntax) - remote_path: The name of the file(s) to be deleted on the remote server string.
Note: The file name may include a path and/or an extension, and you can use wildcards for multiple files (but none of these are required)
Optional Parameters
- debug: When true return verbose debug information, errors thrown will also contain debug information (defaults to false) boolean.
Returns
- True if successful false is never returned, errors are thrown instead boolean
- Debug information (if requested) string.
For More Information
- Using File and FTP Interfaces
- The net API reference: File transfer and email using the FTP, FTPS, HTTP, SFTP and SMTP message protocols
- Wikipedia: File Transfer Protocols (ftp)
- Understanding Lua OO syntax: what the colon operator means
net.ftps.get
Example Usage of FtpsConn:get{remote_path=<value> [, local_path=<value>] [, ...]}
local FtpsConn = net.ftps.init{server='example', username='user', password='password'}
-- recommended usage:
FtpsConn:get{remote_path='afile.txt'}
-- which is shorthand for:
net.ftps.get(FtpsConn, {remote_path='afile.txt'})
--How to download text and binary files
-- cache the connection parameters
local FtpsConn = net.ftps.init{server='foxton_ftps', username='test_ftps',password='secret'}
-- get (download) a text file (opens/closes an ASCII connection)
FtpsConn:get{remote_path='/fox_out/test.png',local_path='temp/test.txt'}
-- get (download) a binary (picture) file (opens/closes a binary connection)
FtpsConn:get{remote_path='/fox_out/test.png',local_path='temp/test.png'}
Usage
FtpsConn:get{remote_path=<value> [, local_path=<value>] [, ...]}
Get a single file from the remote server.
The local_path is relative to the Iguana install directory. So the absolute path for 'temp/myfile.txt' is something like 'c:/program files/interfaceware/iguana/temp/myfile.txt (Windows), or '/Users/julianmuir/Downloads/temp/myfile.txt' (Mac/Linux). You can also specify an absolute path.
Note: The file type is detected and the correct transfer mode, 'ascii' (text) or 'binary', is chosen automatically.
Required Parameters
- id: Connection id returned from net.ftps.init table.
Note: This is only required for the functional syntax (it is implicit in the OO/colon syntax) - remote_path: The name of the file to be downloaded from the remote server string.
Note: The name may include a path and/or an extension (but neither of these are required)
Optional Parameters
- local_path: Save the file using this name instead of returning it as a string string.
Note: The name may include a path and/or an extension (but neither of these are required) - overwrite: Allow local_path to be overwritten if it already exists boolean.
- debug: When true return verbose debug information, errors thrown will also contain debug information (defaults to false) boolean.
Returns
- The contents of the file (or true if local_path is used false is never returned, errors are thrown instead) string or boolean
- Debug information (if requested) string.
For More Information
- Using File and FTP Interfaces
- The net API reference: File transfer and email using the FTP, FTPS, HTTP, SFTP and SMTP message protocols
- Wikipedia: File Transfer Protocols (ftp)
- Understanding Lua OO syntax: what the colon operator means
net.ftps.init
Example Usage of net.ftps.init{server=<value>, username=<value>, ...}
local FtpsConn = net.ftps.init{server='example', username='user', password='password'}
-- cache the connection parameters
local FtpsConn = net.ftps.init{server='foxton_ftps', username='test_ftps',password='secret'}
-- get (download) a text file (opens/closes an ASCII connection)
FtpsConn:get{remote_path='/Users/foxton_ftps/test.png',local_path='temp/test.txt'}
-- get (download) a binary (picture) file (opens/closes a binary connection)
FtpsConn:get{remote_path='/Users/foxton_ftps/test.png',local_path='temp/test.png'}
-- active connection on default IP & default port
local FtpsConn = net.ftps.init{server='foxton_ftps', username='test_ftps',password='secret',active='-'}
-- active connection on default IP & default port
-- restrict to using IPV4 addressing (no_eprt=true), no_eprt can be added to any of the following commands
local FtpsConn = net.ftps.init{server='foxton_ftps', username='test_ftps',password='secret',active='-', no_eprt=true}
-- active connection on default IP & port specified
local FtpsConn = net.ftps.init{server='foxton_ftps', username='test_ftps',password='secret',active=':32000'}
-- active connection on default IP & with local machine name specified
local FtpsConn = net.ftps.init{server='foxton_ftps', username='test_ftps',password='secret',active='foxton-pc1'}
-- active connection on default IP & with local machine name & port specified
local FtpsConn = net.ftps.init{server='foxton_ftps', username='test_ftps',password='secret',active='foxton-pc1:32000'}
-- active connection on default IP & with local machine IP specified
local FtpsConn = net.ftps.init{server='foxton_ftps', username='test_ftps',password='secret',active='10.211.55.12'}
-- active connection on default IP & with local machine IP and port range specified
local FtpsConn = net.ftps.init{server='foxton_ftps', username='test_ftps',password='secret',active='10.211.55.12:32000-33000'}
Usage
net.ftps.init{server=<value>, username=<value>, ...}
Initializes a new FTPS connection (FTP over SSL/TLS). The connection defaults to passive mode, you can also create an active connection (using the 'active' parameter). Other options include specifying IPV4 only (using 'no_eprt' or 'no_epsv'), etc.
When a command is run the file type is detected and the correct transfer mode, 'ascii' (text) or 'binary', is chosen automatically.
Note: The 'init' command only caches the connection parameters, it does not open a connection. The actual connections are managed automatically, a connection is opened and closed each time an ftp command is issued (get, put etc). Because of this there never a need to 'close' an FTPS connection.
If you need help with the advanced ftp options please contact support at support@interfaceware.com.
Required Parameters
- server: The server to connect to string.
- username: The remote user to login as string.
Optional Parameters
- password: The password to authenticate with string.
- port: The port to use (defaults to 22) integer.
- timeout: Timeout for operations (defaults to 15 seconds) integer.
- live: Enable write operations (put, rename, delete) while in the editor boolean.
- active: Open a local port for active FTP mode, and send a PORT command with the given local IP/hostname (or network interface on Unix). Use '-' for the default local IP address and a random port. A particular port or range of ports to use can be added after the IP/hostname, e.g. ':32000', '192.168.1.2:32000' or 'eth0:32000-33000'. Note that '-:32000' is not valid; omit the hyphen when specifying a port for the default IP. string.
- no_eprt: Active mode: do not try EPRT or LPRT before trying PORT boolean.
- no_epsv: Passive mode: do not try EPSV before PASV, just use PASV boolean.
- skip_pasv_ip: Passive mode: ignore the IP address sent by the server; instead open the new port on the same machine boolean.
- use_pret: Send a non-standard PRET command before PASV or EPSV boolean.
- alt_auth: Command to send when USER/PASS authentication fails string.
- acct: Account data to send when asked by some atypical servers string.
- on_ready: An array of commands to be issued after setting the transfer mode, before any actual transfers are started table.
- certificate_file: The name of your certificate file string.
- certificate_type: Your certificate's type: PEM (default) or DER string.
- private_key_file: The name of your private key file string.
- private_key_pass: The password to access your private key string.
- private_key_type: Your private key's type: PEM (default), DER, or ENG string.
- ssl_engine: The engine to use with 'key_type' ENG string.
- verify_peer: Verify peer certificate (default true) boolean.
- verify_host: Verify host certificate matches URL (default true) boolean.
- ca_file: The certificate(s) file to use for peer verification string.
- issuer_cert: The PEM certificate file to validate the issuer of the peer's certificate during peer validation string.
- crl_file: The name of the certificate revocation list to use during peer validation string.
- ssl_version: Use a particular SSL version. Normally ssl-v3 is tried first, then tls-v1; ssl-v2 is never used automatically string.
- ssl_auth: Use 'ssl' to try AUTH SSL before AUTH TLS, or 'tls' to try AUTH TLS first then AUTH SSL string.
- force_ssl: Normally 'yes', but can be changed to 'control' to require SSL on the control connection, or 'no' to allow insecure (non-SSL) connections entirely string.
- use_ccc: Clear control channel: shutdown SSL/TLS on the control connection after authentication. If set to 'active' we will initiate the shutdown; use 'passive' to allow the server to start the shutdown string.
Returns
- A connection object table.
For More Information
- Using File and FTP Interfaces
- The net API reference: File transfer and email using the FTP, FTPS, HTTP, SFTP and SMTP message protocols
- Wikipedia: File Transfer Protocols (ftp)
net.ftps.list
Example Usage of FtpsConn:list{remote_path=<value> [, debug=<value>]}
local FtpsConn = net.ftps.init{server='example', username='user', password='password'} -- recommended usage: FtpsConn:list{remote_path='/'} -- which is shorthand for: net.ftps.list(FtpsConn, {remote_path='/'})
FtpConn:list{remote_path=''} -- users home directory
FtpConn:list{remote_path='/'} -- ftp root directory
FtpConn:list{remote_path='/fox_out/'} -- user specified data directory
Usage
FtpsConn:list{remote_path=<value> [, debug=<value>]}
List the contents of a remote path.
Required Parameters
- id: Connection id returned from net.ftps.init table.
Note: This is only required for the functional syntax (it is implicit in the OO/colon syntax) - remote_path: The directory path on the remote server to list the contents for string.
Optional Parameters
- debug: When true return verbose debug information, errors thrown will also contain debug information (defaults to false) boolean.
Returns
- An array of {filename, is_retrievable} values table.
- Debug information (if requested) string.
For More Information
- How to use the ftp list command
- Using File and FTP Interfaces
- The net API reference: File transfer and email using the FTP, FTPS, HTTP, SFTP and SMTP message protocols
- Wikipedia: File Transfer Protocols (ftp)
- Understanding Lua OO syntax: what the colon operator means
net.ftps.put
Example Usage of FtpsConn:put{remote_path=<value> [, data=<value>] [, ...]}
local FtpsConn = net.ftps.init{server='example', username='user', password='password'} -- recommended usage: FtpsConn:put{remote_path='afile.txt', data=Data} -- which is shorthand for: net.ftps.put(FtpsConn, {remote_path='afile.txt', data=Data})
--How to upload text and binary files
-- cache the connection parameters
local FtpsConn = net.ftps.init{server='foxton_ftps', username='test_ftps',password='secret'}
-- put (upload) a text file (opens/closes an ASCII connection)
FtpsConn:put{remote_path='/fox_in/test.png',local_path='temp/test.txt'}
-- put (upload) a binary (picture) file (opens/closes a binary connection)
FtpsConn:put{remote_path='/fox_in/test.png',local_path='temp/test.png'}
Usage
FtpsConn:put{remote_path=<value> [, data=<value>] [, ...]}
Put a single file on the specified server.
The local_path is relative to the Iguana install directory. So the absolute path for 'temp/myfile.txt' is something like 'c:/program files/interfaceware/iguana/temp/myfile.txt (Windows), or '/Users/julianmuir/Downloads/temp/myfile.txt' (Mac/Linux). You can also specify an absolute path.
Note: The file type is detected and the correct transfer mode, 'ascii' (text) or 'binary', is chosen automatically.
Required Parameters
- id: Connection id returned from net.ftps.init table.
Note: This is only required for the functional syntax (it is implicit in the OO/colon syntax) - remote_path: The name to be used for the uploaded file on the remote server string.
Note: The file name may include a path and/or an extension (but neither of these are required)
Optional Parameters
- data: Data to upload string.
- local_path: The name of a local file to be uploaded to the remote server. If specified, the 'data' parameter is ignored string.
Note: The file name may include a path and/or an extension (but neither of these are required) - overwrite: Allow remote_path to be overwritten if it already exists boolean.
- tmp_postfix: If not nil the file will first be uploaded as remote_path..tmp_postfix, and then renamed remote_path. Useful to ensure remote processes do not read a partially uploaded file string.
- debug: When true return verbose debug information, errors thrown will also contain debug information (defaults to false) boolean.
Returns
- True if successful false is never returned, errors are thrown instead boolean
- Debug information (if requested) string.
For More Information
- Using File and FTP Interfaces
- The net API reference: File transfer and email using the FTP, FTPS, HTTP, SFTP and SMTP message protocols
- Wikipedia: File Transfer Protocols (ftp)
- Understanding Lua OO syntax: what the colon operator means
net.ftps.rename
Example Usage of FtpsConn:rename{remote_path=<value>, new_remote_path=<value>, ...}
local FtpsConn = net.ftps.init{server='example', username='user', password='password'} -- recommended usage: FtpsConn:rename{remote_path='old_name.txt', new_remote_path='new_name.txt'} -- which is shorthand for: net.ftps.rename(FtpsConn, {remote_path='old_name.txt', new_remote_path='new_name.txt'})
-- move a file to a 'processed' directory
FtpsConn:rename{
remote_path='/fox_out/test.txt',
new_remote_path='/fox_processed/test'..os.date()..'.txt'
}
-- use the 'live' parameter to rename a file in the editor
-- cache the connection parameters, set live = true
local FtpsConn = net.ftps.init{server='foxton_ftps', username='test_ftps',password='secret', live=true}
-- rename the file
FtpsConn:rename{remote_path='/fox_out/test.txt', new_remote_path='/fox_processed/test_old'.txt'}
Usage
FtpsConn:rename{remote_path=<value>, new_remote_path=<value>, ...}
Renames a single file or directory on the server.
Required Parameters
- id: Connection id returned from net.ftps.init table.
Note: This is only required for the functional syntax (it is implicit in the OO/colon syntax) - remote_path: The old name of the file or directory to be renamed on the remote server string.
Note: The name may include a path and/or an extension (but neither of these are required) - new_remote_path: The new name of the file or directory to be renamed on the remote server string.
Note: The name may include a path and/or an extension (but neither of these are required)
Optional Parameters
- debug: When true return verbose debug information, errors thrown will also contain debug information (defaults to false) boolean.
Returns
- True if successful false is never returned, errors are thrown instead boolean
- Debug information (if requested) string.
For More Information
- Using File and FTP Interfaces
- The net API reference: File transfer and email using the FTP, FTPS, HTTP, SFTP and SMTP message protocols
- Wikipedia: File Transfer Protocols (ftp)
- Understanding Lua OO syntax: what the colon operator means
net.http
net.http.connectionInfo
Example Usage of net.http.connectionInfo()
-- recommended usage: returns "127.0.0.1" as a test IP address in the editor (choose your own test IP) local info = net.http.connectionInfo() or {RemoteAddr='127.0.0.1'}
Usage
net.http.connectionInfo()
Get connection information such as the IP address of the incoming HTTP connection. Only valid in the context of a From HTTP source.
Returns
- When the channel is running returns a table of the form {RemoteAddr='IpAddress'} - nil if used within the editor table or nil.
For More Information
net.http.delete
Example Usage of net.http.delete{url=<value> [, timeout=<value>] [, ...]} or net.http.delete(<value>)
local Results = net.http.delete{url='http://www.interfaceware.com/not-real-example'}
Usage
net.http.delete{url=<value> [, timeout=<value>] [, ...]} or net.http.delete(<value>)
Removes a resource from an HTTP site using the DELETE method.
Required Parameters
- url: The URL to delete string.
Optional Parameters
- timeout: Timeout for the operation. Default is 15 seconds integer.
- headers: A key/value table of HTTP header values (e.g. {['Set-Cookie']='Val'}), or an array of strings (e.g. {'Set-Cookie: Val1','Set-Cookie: Val2'}) table.
- response_headers_format: Specifies the output format of the response headers: 'default' - a table of key/value pairs from the last response after redirects, where the value is the last value for the given header key; 'raw' - a table containing every line of every header, including redirects; or 'multiple' - a table of key/value pairs of the form {HeaderKey = {Values={Val1,LastVal},Value=LastVal}} where the values are from the last response after redirects table.
- method: The method to use (defaults to DELETE) string.
- auth: The 'auth' table, when used, contains these parameters:
- username : the username to send to the HTTP server.
- password : the password to send to the HTTP server.
- method : optional: the authorization method(s) to allow. See below.
- follow : optional: continue authorization attempts after redirect.This defaults to false to avoid compromising security.
The authentication method defaults to 'basic', but can be changed to:'digest', 'digest-ie', 'gss-negotiate', 'ntlm', 'any' (allow any method),'anysafe' (not 'basic'), or a combination (e.g., {'digest','digest-ie'}).
When more than one method is allowed, the server will be asked which it supports before authentication is attempted.
table - ssl: The 'ssl' table, when used, may contain these parameters:
- cert : the name of your certificate file.
- cert_type : your certificate's type: PEM (default) or DER.
- key : the name of your private key file.
- key_pass : the password to access your private key.
- key_type : your private key's type: PEM (default), DER, or ENG.
- ssl_engine : the engine to use with 'key_type' ENG.
- verify_peer : verify peer certificate (default true).
- verify_host : verify host certificate matches URL (default true).
- ca_file : the certificate(s) file to use for peer verification.
- issuer_cert : the PEM certificate file to validate the issuer of the peer's certificate during peer validation.
- crl_file : the name of the certificate revocation list to use during peer validation.
- ssl_version : use a particular SSL version. Normally ssl-v3 is tried first, then tls-v1; ssl-v2 is never used automatically.;
- debug: When true return verbose debug information - errors thrown will also contain debug information (defaults to false) boolean.
- live: When true, requests are sent while in the editor boolean.
Returns
- Response data string.
- Response code string.
- Response headers table.
For More Information
net.http.get
Example Usage of net.http.get{url=<value> [, timeout=<value>] [, ...]} or net.http.get(<value>)
local Results = net.http.get{url='http://www.interfaceware.com', parameters={key='value'}}
Usage
net.http.get{url=<value> [, timeout=<value>] [, ...]} or net.http.get(<value>)
Fetches data from an HTTP address using the GET method.
Required Parameters
- url: The URL to fetch data from string.
Optional Parameters
- timeout: Timeout for the operation. Default is 15 seconds integer.
- parameters: A table of parameters to be passed to the server, and is appended to existing parameters in 'url'. E.g., {q='a name'} would be passed as "?q=a%20name" string.
- headers: A key/value table of HTTP header values (e.g. {['Set-Cookie']='Val'}), or an array of strings (e.g. {'Set-Cookie: Val1','Set-Cookie: Val2'}) table.
- response_headers_format: Specifies the output format of the response headers: 'default' - a table of key/value pairs from the last response after redirects, where the value is the last value for the given header key; 'raw' - a table containing every line of every header, including redirects; or 'multiple' - a table of key/value pairs of the form {HeaderKey = {Values={Val1,LastVal},Value=LastVal}} where the values are from the last response after redirects table.
- method: The method to use (defaults to GET) string.
- auth: The 'auth' table, when used, contains these parameters:
- username : the username to send to the HTTP server.
- password : the password to send to the HTTP server.
- method : optional: the authorization method(s) to allow. See below.
- follow : optional: continue authorization attempts after redirect.This defaults to false to avoid compromising security.
The authentication method defaults to 'basic', but can be changed to:'digest', 'digest-ie', 'gss-negotiate', 'ntlm', 'any' (allow any method),'anysafe' (not 'basic'), or a combination (e.g., {'digest','digest-ie'}).
When more than one method is allowed, the server will be asked which it supports before authentication is attempted.
table - ssl: The 'ssl' table, when used, may contain these parameters:
- cert : the name of your certificate file.
- cert_type : your certificate's type: PEM (default) or DER.
- key : the name of your private key file.
- key_pass : the password to access your private key.
- key_type : your private key's type: PEM (default), DER, or ENG.
- ssl_engine : the engine to use with 'key_type' ENG.
- verify_peer : verify peer certificate (default true).
- verify_host : verify host certificate matches URL (default true).
- ca_file : the certificate(s) file to use for peer verification.
- issuer_cert : the PEM certificate file to validate the issuer of the peer's certificate during peer validation.
- crl_file : the name of the certificate revocation list to use during peer validation.
- ssl_version : use a particular SSL version. Normally ssl-v3 is tried first, then tls-v1; ssl-v2 is never used automatically.;
- live: When true, requests are sent while in the editor boolean.
- debug: When true return verbose debug information - errors thrown will also contain debug information (defaults to false) boolean.
Returns
- Response data string.
- Response code string.
- Response headers table.
For More Information
- The net interface modules - file transfer and email using the FTP, FTPS, HTTP, SFTP and SMTP message protocols
- Connecting to Highrise CRM using Web Services
- Calling a web service
- HTTP basic authentication
net.http.parseRequest
Example Usage of net.http.parseRequest{data=<value> [, headers_format=<value>]} or net.http.parseRequest(<value>)
net.http.parse{data=MyWebRequest}
Usage
net.http.parseRequest{data=<value> [, headers_format=<value>]} or net.http.parseRequest(<value>)
Parses a string representing a web request.
Required Parameters
- data: Web request to parse string.
Optional Parameters
- headers_format: Specifies the output format of the headers: 'default' - a table of key/value pairs where the value is the last value for the given header key; 'raw' - a table containing every line of every header; or 'multiple' - a table of key/value pairs of the form {HeaderKey = {Values={Val1,LastVal},Value=LastVal}} table.
Returns
- A table with the following entries: 'body' - the body of the request; 'cookies' - a table of cookie values; 'get_params' - a table of GET variables; 'headers' - a table containing the request headers; 'location' - the location of the request (e.g., '/services'); 'method' - the method of the request (e.g., 'GET'); 'params' - a table containing both GET and POST variables; 'post_params' - a table of POST variables, if the request was a POST with form encoded data table.
For More Information
- The net interface modules - file transfer and email using the FTP, FTPS, HTTP, SFTP and SMTP message protocols
- Simple web service example
net.http.post
Example Usage of net.http.post{url=<value> [, timeout=<value>] [, ...]} or net.http.post(<value>)
local Results = net.http.post{url='http://www.interfaceware.com', parameters={key='value'}}
Usage
net.http.post{url=<value> [, timeout=<value>] [, ...]} or net.http.post(<value>)
Fetches data from an HTTP address using the POST method.
Required Parameters
- url: The URL to fetch data from string.
Optional Parameters
- timeout: Timeout for the operation. Default is 15 seconds integer.
- parameters: A table of POST parameters to be passed to the server. E.g., {q='a name'} would be passed as "q=a%20name" string.
- get_parameters: A table of GET parameters to be passed to the server, and is appended to existing parameters in 'url'. E.g., {q='a name'} would be passed as "?q=a%20name" string.
- headers: A key/value table of HTTP header values (e.g. {['Set-Cookie']='Val'}), or an array of strings (e.g. {'Set-Cookie: Val1','Set-Cookie: Val2'}). By default, {['Content-Type']='application/x-www-form-urlencoded'} is assumed string.
- response_headers_format: Specifies the output format of the response headers: 'default' - a table of key/value pairs from the last response after redirects, where the value is the last value for the given header key; 'raw' - a table containing every line of every header, including redirects; or 'multiple' - a table of key/value pairs of the form {HeaderKey = {Values={Val1,LastVal},Value=LastVal}} where the values are from the last response after redirects table.
- method: The method to use (defaults to POST) string.
- body: Data to be sent to the server. Note that this content should be appropriate for the given headers. No escaping is done. When specified, overrides 'parameters' string.
- auth: The 'auth' table, when used, contains these parameters:
- username : the username to send to the HTTP server.
- password : the password to send to the HTTP server.
- method : optional: the authorization method(s) to allow. See below.
- follow : optional: continue authorization attempts after redirect.This defaults to false to avoid compromising security.
The authentication method defaults to 'basic', but can be changed to:'digest', 'digest-ie', 'gss-negotiate', 'ntlm', 'any' (allow any method),'anysafe' (not 'basic'), or a combination (e.g., {'digest','digest-ie'}).
When more than one method is allowed, the server will be asked which it supports before authentication is attempted.
table - ssl: The 'ssl' table, when used, may contain these parameters:
- cert : the name of your certificate file.
- cert_type : your certificate's type: PEM (default) or DER.
- key : the name of your private key file.
- key_pass : the password to access your private key.
- key_type : your private key's type: PEM (default), DER, or ENG.
- ssl_engine : the engine to use with 'key_type' ENG.
- verify_peer : verify peer certificate (default true).
- verify_host : verify host certificate matches URL (default true).
- ca_file : the certificate(s) file to use for peer verification.
- issuer_cert : the PEM certificate file to validate the issuer of the peer's certificate during peer validation.
- crl_file : the name of the certificate revocation list to use during peer validation.
- ssl_version : use a particular SSL version. Normally ssl-v3 is tried first, then tls-v1; ssl-v2 is never used automatically.
- debug: When true return verbose debug information - errors thrown will also contain debug information (defaults to false) boolean.
- live: When true, requests are sent while in the editor boolean.
Returns
- Response data string.
- Response code string.
- Response headers table.
For More Information
- The net interface modules - file transfer and email using the FTP, FTPS, HTTP, SFTP and SMTP message protocols
- Connecting to Highrise CRM using Web Services
net.http.put
Example Usage of net.http.put{url=<value> [, timeout=<value>] [, ...]}
local Results = net.http.put{url='http://www.interfaceware.com/not-real-example', data='I need a consult!'}
Usage
net.http.put{url=<value> [, timeout=<value>] [, ...]}
Uploads data to an HTTP address using the PUT method.
Required Parameters
- url: The URL to upload data to string.
- data: The data to upload (when 'reader' isn't used) string.
- reader: The function to call to get more data to upload string.
Optional Parameters
- timeout: Timeout for the operation. Default is 15 seconds integer.
- size: The amount of data to expect from 'reader' integer.
- headers: A key/value table of HTTP header values (e.g. {['Set-Cookie']='Val'}), or an array of strings (e.g. {'Set-Cookie: Val1','Set-Cookie: Val2'}) table.
Note: A few common HTTP headers set to reasonable defaults may be included along with all requests:- {['Expect']=''} is always set for HTTP PUT requests. This results in the correct behaviour in most cases. Some servers (e.g., Microsoft IIS) almost always return a 100-Continue for PUT requests, leading to very slow responses. In this case, it is advised to set {['Expect']='100-Continue'}.
- {['Transfer-Encoding']='chunked'} is used when a 'reader' is given without specifying the 'size' to expect.
- response_headers_format: Specifies the output format of the response headers: 'default' - a table of key/value pairs from the last response after redirects, where the value is the last value for the given header key; 'raw' - a table containing every line of every header, including redirects; or 'multiple' - a table of key/value pairs of the form {HeaderKey = {Values={Val1,LastVal},Value=LastVal}} where the values are from the last response after redirects table.
- method: The method to use (defaults to PUT) string.
- auth: The 'auth' table, when used, contains these parameters:
- username : the username to send to the HTTP server.
- password : the password to send to the HTTP server.
- method : optional: the authorization method(s) to allow. See below.
- follow : optional: continue authorization attempts after redirect.This defaults to false to avoid compromising security.
The authentication method defaults to 'basic', but can be changed to:'digest', 'digest-ie', 'gss-negotiate', 'ntlm', 'any' (allow any method),'anysafe' (not 'basic'), or a combination (e.g., {'digest','digest-ie'}).
When more than one method is allowed, the server will be asked which it supports before authentication is attempted.
table - ssl: The 'ssl' table, when used, may contain these parameters:
- cert : the name of your certificate file.
- cert_type : your certificate's type: PEM (default) or DER.
- key : the name of your private key file.
- key_pass : the password to access your private key.
- key_type : your private key's type: PEM (default), DER, or ENG.
- ssl_engine : the engine to use with 'key_type' ENG.
- verify_peer : verify peer certificate (default true).
- verify_host : verify host certificate matches URL (default true).
- ca_file : the certificate(s) file to use for peer verification.
- issuer_cert : the PEM certificate file to validate the issuer of the peer's certificate during peer validation.
- crl_file : the name of the certificate revocation list to use during peer validation.
- ssl_version : use a particular SSL version. Normally ssl-v3 is tried first, then tls-v1; ssl-v2 is never used automatically.;
- debug: When true return verbose debug information - errors thrown will also contain debug information (defaults to false) boolean.
- live: When true, requests are sent while in the editor boolean.
Returns
- Response data string.
- Response code string.
- Response headers string.
For More Information
- The net interface modules - file transfer and email using the FTP, FTPS, HTTP, SFTP and SMTP message protocols
- Workaround when posting large messages using net.http
net.http.respond
Example Usage of net.http.respond{body=<value> [, code=<value>] [, ...]} or net.http.respond(<value>)
net.http.respond{body='hello world'}
Usage
net.http.respond{body=<value> [, code=<value>] [, ...]} or net.http.respond(<value>)
Sends a response back to the sender of the request. Only valid in the context of a From HTTP source.
Required Parameters
- body: Body of response to send string.
Optional Parameters
- code: HTTP response code to send. Defaults to 200 integer.
- headers: A key/value table of HTTP header values (e.g. {['Set-Cookie']='Val'}), or an array of strings (e.g. {'Set-Cookie: Val1','Set-Cookie: Val2'}) table.
- entity_type: Type of response. Defaults to 'text/html' string.
- use_gzip: Use gzip compression (if request supports it). Defaults to true boolean.
- persist: Include a header in the response to persist the connection (if request supports it). Defaults to true boolean.
- debug_result: Return the response sent as a string for debug purposes. Defaults to true boolean.
Returns
- The result data or empty string (depending on debug_result parameter) string.
For More Information
- The net interface modules - file transfer and email using the FTP, FTPS, HTTP, SFTP and SMTP message protocols
- Simple web service example
- Using HTTPS to send messages between Iguana Servers
net.sftp
net.sftp.delete
Example Usage of SftpConn:delete{remote_path=<value> [, debug=<value>]}
local SftpConn = net.sftp.init{server='example', username='user', password='password'} -- recommended usage: SftpConn:delete{remote_path='afile.txt'} -- which is shorthand for: net.sftp.delete(SftpConn, {remote_path='afile.txt'})
-- delete a file
SftpConn:delete{remote_path='/fox_out/test.txt'}
-- use the 'live' parameter to delete a file in the editor
-- cache the connection parameters, set live = true
local SftpConn = net.sftp.init{server='foxton_sftp', username='test_sftp',password='secret', live=true}
-- delete the file
SftpConn:delete{remote_path='/fox_out/test.txt'}
Usage
SftpConn:delete{remote_path=<value> [, debug=<value>]}
Deletes a file (or files) from the specified ftp server.
Required Parameters
- id: Connection id returned from net.sftp.init table.
Note: This is only required for the functional syntax (it is implicit in the OO/colon syntax) - remote_path: The name of the file(s) to be deleted on the remote server string.
Note: The file name may include a path and/or an extension, and you can use wildcards for multiple files (but none of these are required)
Optional Parameters
- debug: When true return verbose debug information, errors thrown will also contain debug information (defaults to false) boolean.
Returns
- True if successful false is never returned, errors are thrown instead boolean.
- Debug information (if requested) string.
For More Information
- Using File and FTP Interfaces
- The net API reference: File transfer and email using the FTP, FTPS, HTTP, SFTP and SMTP message protocols
- Wikipedia: File Transfer Protocols (ftp)
- Wikipedia: SSH File Transfer Protocol
- Understanding Lua OO syntax: what the colon operator means
net.sftp.get
Example Usage of SftpConn:get{remote_path=<value> [, local_path=<value>] [, ...]}
local s SftpConn = net.sftp.init{server='example', username='user', password='password'}
-- recommended usage:
SftpConn:get{remote_path='afile.txt'}
-- which is shorthand for:
net.sftp.get(SftpConn, {remote_path='afile.txt'})
--How to download text and binary files
-- cache the connection parameters
local SftpConn = net.sftp.init{server='foxton_sftp', username='test_sftp',password='secret'}
-- get (download) a text file (opens/closes an ASCII connection) SftpConn:get{remote_path='/fox_out/test.png',local_path='temp/test.txt'} -- get (download) a binary (picture) file (opens/closes a binary connection)
SftpConn:get{remote_path='/fox_out/test.png',local_path='temp/test.png'}
Usage
SftpConn:get{remote_path=<value> [, local_path=<value>] [, ...]}
Get a single file from the remote server.
The local_path is relative to the Iguana install directory. So the absolute path for 'temp/myfile.txt' is something like 'c:/program files/interfaceware/iguana/temp/myfile.txt (Windows), or '/Users/julianmuir/Downloads/temp/myfile.txt' (Mac/Linux). You can also specify an absolute path.
Required Parameters
- id: Connection id returned from net.sftp.init table.
Note: This is only required for the functional syntax (it is implicit in the OO/colon syntax) - remote_path: The name of the file to be downloaded from the remote server string.
Note: The name may include a path and/or an extension (but neither of these are required)
Optional Parameters
- local_path: Save the file using this name instead of returning it as a string string.
Note: The name may include a path and/or an extension (but neither of these are required) - overwrite: Allow local_path to be overwritten if it already exists boolean.
- debug: When true return verbose debug information, errors thrown will also contain debug information (defaults to false) boolean.
Returns
- The contents of the file (or true if local_path is used false is never returned, errors are thrown instead) string or boolean.
- Debug information (if requested) string.
For More Information
- Using File and FTP Interfaces
- The net API reference: File transfer and email using the FTP, FTPS, HTTP, SFTP and SMTP message protocols
- Wikipedia: File Transfer Protocols (ftp)
- Understanding Lua OO syntax: what the colon operator means
net.sftp.init
Example Usage of net.sftp.init{server=<value>, username=<value>, ...}
local SftpConn = net.sftp.init{server='example', username='user', password='password'}
-- cache the connection parameters
local SftpConn = net.sftp.init{server='foxton_sftp', username='test_sftp',password='secret'}
-- get (download) a text file (opens/closes an ASCII connection) SftpConn:get{remote_path='/Users/foxton_sftp/test.png',local_path='temp/test.txt'} -- get (download) a binary (picture) file (opens/closes a binary connection)
SftpConn:get{remote_path='/Users/foxton_sftp/test.png',local_path='temp/test.png'}
Usage
net.sftp.init{server=<value>, username=<value>, ...}
Initializes a new SFTP connection (Secure FTP).
SFTP, the 'SSH File Transfer Protocol', is not related to FTP even though it also transfers files and has a similar command set. SFTP is a program that uses Secure Shell (SSH) to transfer files, and unlike standard FTP, it encrypts both commands and data. The differences from FTP are evident by the reduced number connection options and hence less paramaters for sftp.init{}
.
Note: The 'init' command only caches the connection parameters, it does not open a connection. The actual connections are managed automatically, a connection is opened and closed each time an ftp command is issued (get, put etc). Because of this there never a need to 'close' an SFTP connection.
If you need help with the advanced sftp options please contact support at support@interfaceware.com.
Required Parameters
- server: The server to connect to string.
- username: The remote user to login as string.
Optional Parameters
- password: The password to authenticate with string.
- port: The port to use (defaults to 22) integer.
- timeout: Timeout for operations (defaults to 15 seconds) integer.
- live: Enable write operations (put, rename, delete) while in the editor boolean.
- public_key_file: The name of your public key file string.
- private_key_file: The name of your private key file string.
- private_key_pass: The password to access your private key string.
- host_fingerprint: The MD5 checksum of the remote host's public key, used to authenticate the server (32 hexadecimals) string.
- known_hosts: If you have have an OpenSSH known_hosts file for authenticating remote hosts, you can specify it here string.
Returns
- A connection object table.
For More Information
- Using File and FTP Interfaces
- The net API reference: File transfer and email using the FTP, FTPS, HTTP, SFTP and SMTP message protocols
- Wikipedia: File Transfer Protocols (ftp)
- Wikipedia: SSH File Transfer Protocol
net.sftp.list
Example Usage of SftpConn:list{remote_path=<value> [, debug=<value>]}
local SftpConn = net.sftp.init{server='example', username='user', password='password'} -- recommended usage: SftpConn:list{remote_path='/'} -- which is shorthand for: net.sftp.list(SftpConn, {remote_path='/'})
FtpConn:list{remote_path=''} -- users home directory
FtpConn:list{remote_path='/'} -- ftp root directory
FtpConn:list{remote_path='/fox_out/'} -- user specified data directory
Usage
SftpConn:list{remote_path=<value> [, debug=<value>]}
List the contents of a remote path.
Required Parameters
- id: Connection id returned from net.sftp.init table.
Note: This is only required for the functional syntax (it is implicit in the OO/colon syntax) - remote_path: The directory path on the remote server to list the contents for string.
Optional Parameters
- debug: When true return verbose debug information, errors thrown will also contain debug information (defaults to false) boolean.
Returns
- An array of {filename, is_retrievable} values table.
- Debug information (if requested) string.
For More Information
- How to use the ftp list command
- Using File and FTP Interfaces
- The net API reference: File transfer and email using the FTP, FTPS, HTTP, SFTP and SMTP message protocols
- Wikipedia: File Transfer Protocols (ftp)
- Wikipedia: SSH File Transfer Protocol
- Understanding Lua OO syntax: what the colon operator means
net.sftp.put
Example Usage of SftpConn:put{remote_path=<value> [, data=<value>] [, ...]}
local SftpConn = net.sftp.init{server='example', username='user', password='password'} -- recommended usage: SftpConn:put{remote_path='afile.txt', data=Data} -- which is shorthand for: net.sftp.put(SftpConn, {remote_path='afile.txt', data=Data})
--How to upload text and binary files
-- cache the connection parameters
local SftpConn = net.sftp.init{server='foxton_sftp', username='test_sftp',password='secret'}
-- put (upload) a text file (opens/closes an ASCII connection) SftpConn:put{remote_path='/fox_in/test.png',local_path='temp/test.txt'} -- put (upload) a binary (picture) file (opens/closes a binary connection)
SftpConn:put{remote_path='/fox_in/test.png',local_path='temp/test.png'}
Usage
SftpConn:put{remote_path=<value> [, data=<value>] [, ...]}
Put a single file on the specified server.
The local_path is relative to the Iguana install directory. So the absolute path for 'temp/myfile.txt' is something like 'c:/program files/interfaceware/iguana/temp/myfile.txt (Windows), or '/Users/julianmuir/Downloads/temp/myfile.txt' (Mac/Linux). You can also specify an absolute path.
Required Parameters
- id: Connection id returned from net.sftp.init table.
Note: This is only required for the functional syntax (it is implicit in the OO/colon syntax) - remote_path: The name to be used for the uploaded file on the remote server string.
Note: The file name may include a path and/or an extension (but neither of these are required)
Optional Parameters
- data: Data to upload string.
- local_path: The name of a local file to be uploaded to the remote server. If specified, the 'data' parameter is ignored string.
Note: The file name may include a path and/or an extension (but neither of these are required) - overwrite: Allow remote_path to be overwritten if it already exists boolean.
- tmp_postfix: If not nil the file will first be uploaded as remote_path..tmp_postfix, and then renamed remote_path. Useful to ensure remote processes do not read a partially uploaded file string.
- debug: When true return verbose debug information, errors thrown will also contain debug information (defaults to false) boolean.
Returns
- True if successful false is never returned, errors are thrown instead boolean.
- Debug information (if requested) string.
For More Information
- Using File and FTP Interfaces
- The net API reference: File transfer and email using the FTP, FTPS, HTTP, SFTP and SMTP message protocols
- Wikipedia: File Transfer Protocols (ftp)
- Wikipedia: SSH File Transfer Protocol
- Understanding Lua OO syntax: what the colon operator means
net.sftp.rename
Example Usage of SftpConn:rename{remote_path=<value>, new_remote_path=<value>, ...}
local SftpConn = net.sftp.init{server='example', username='user', password='password'} -- recommended usage: SftpConn:rename{remote_path='old_name.txt', new_remote_path='new_name.txt'} -- which is shorthand for: net.sftp.rename(SftpConn, {remote_path='old_name.txt', new_remote_path='new_name.txt'})
-- move a file to a 'processed' directory
SftpConn:rename{
remote_path='/fox_out/test.txt',
new_remote_path='/fox_processed/test'..os.date()..'.txt'
}
-- use the 'live' parameter to rename a file in the editor
-- cache the connection parameters, set live = true
local SftpConn = net.sftp.init{server='foxton_sftp', username='test_sftp',password='secret', live=true}
-- rename the file
SftpConn:rename{remote_path='/fox_out/test.txt', new_remote_path='/fox_processed/test_old'.txt'}
Usage
SftpConn:rename{remote_path=<value>, new_remote_path=<value>, ...}
Renames a single file or directory on the server.
Required Parameters
- id: Connection id returned from net.sftp.init table.
Note: This is only required for the functional syntax (it is implicit in the OO/colon syntax) - remote_path: The old name of the file or directory to be renamed on the remote server string.
Note: The name may include a path and/or an extension (but neither of these are required) - new_remote_path: The new name of the file or directory to be renamed on the remote server string.
Note: The name may include a path and/or an extension (but neither of these are required)
Optional Parameters
- debug: When true return verbose debug information, errors thrown will also contain debug information (defaults to false) boolean.
Returns
- True if successful false is never returned, errors are thrown insteadboolean.
- Debug information (if requested) string.
For More Information
- Using File and FTP Interfaces
- The net API reference: File transfer and email using the FTP, FTPS, HTTP, SFTP and SMTP message protocols
- Wikipedia: File Transfer Protocols (ftp)
- Wikipedia: SSH File Transfer Protocol
- Understanding Lua OO syntax: what the colon operator means
net.smtp
net.smtp.send
Example Usage of net.smtp.send{server=<value>, from=<value>, header=<value>, body=<value> [, username=<value>] [, ...]}
local Header = {To = 'adam@smith.com'; -- bcc to jane@smith.com
From = 'will@smith.com'; -- show a different name as sender
Date = 'Thu, 23 Aug 2001 21:27:04 -0400';
Subject = 'Test Subject';
}
local Results = net.smtp.send{
server='smtp://mysmtp.com:25',
username='john', password='password',
from='john@smith.com',
to={'adam@smith.com', 'jane@smith.com'},
header=Header,
body='Test Email Body',
use_ssl='try'
}
Usage
net.smtp.send{server=<value>, from=<value>, header=<value>, body=<value> [, username=<value>] [, ...]}
Sends an email using the SMTP protocol.
Note: The header fields are for display only, the "To" param contains the actual email recipient(s). Therefore to do Bcc you just add the recipient address in the "To" param, but omit it from the header (so it is not displayed).
Some common header fields include: "From:" (mandatory), "To:", "Subject:", "Date:" (mandatory, "Message-ID:", "Bcc:", " Cc:", "Content-Type:" (non-standard), "In-Reply-To:", "Precedence:" (non-standard), "Received:", "References:", "Reply-To:", "Sender:", "Return-Path:", "Errors-To:" (non-standard), "X-*" (recommended for custom fields)
Note: Though "X-*" is recommended for custom header fields, in fact, any header not expressly defined in the RFC, is allowed, and ignored by most e-mail systems. For example there are three (common) non-standard fields in the list above: "Content-Type:", "Precedence:" and "Errors-To:"
Required Parameters
- server: The server the email will be sent through string.
- to: Recipient emails, an array containing a list of strings, each of the form 'email@domain.com' table.
- from: Sender email address, e.g., 'user@host.com' string.
- header: A table of key value pairs representing the header table.
- body: A string containing the body of the message string.
Optional Parameters
- username: Username to use. If this and password are empty or not specified, no authentication will be used string.
- password: Password to use. If this and username are empty or not specified, no authentication will be used string.
- timeout: Timeout for the send. Default is 15 seconds integer.
- use_ssl: Defaults to 'no'. Options are: 'yes' - SSL will be used or an error will occur; 'no' - SSL will not be used; or 'try' - SSL will be used if possible string.
- live: When true, emails will be sent while in the editor (defaults to false) boolean.
- debug: When true return verbose debug information - errors thrown will also contain debug information (defaults to false) boolean.
For More Information
- The net interface modules - file transfer and email using the FTP, FTPS, HTTP, SFTP and SMTP message protocols
- Send an Email
- Wikipedia: Email provides a good overview, with many links to RFCs etc.
- RFC 5321 is the current email standard
- RFC 5322 is the current email message standard, with header fields
- RFC 4021 is a older standard for mail and MIME header fields (including some fields omitted from 5322)
net.tcp
net.tcp.close
Example Usage of Socket:close()
local s = net.tcp.connect('hostname:8086') s:send(Data) local Ack = s:recv() s:close()
Usage
Socket:close()
Close an open socket.
For More Information
net.tcp.connect
Example Usage of net.tcp.connect('hostname:port') alternatively: net.tcp.connect{host=<value>, port=<value>}
local s = net.tcp.connect('hostname:8086') s:send(Data) local Ack = s:recv() s:close()
local s = net.tcp.connect{host=hostname, port=8086} s:send(Data) local Ack = s:recv() s:close()
Usage
net.tcp.connect('hostname:port') alternatively: net.tcp.connect{host=<value>, port=<value>}
Connect to a remote host with TCP/IP.
Note: you can specify hostname and port as single parameter or in a table (see examples below).
Required Parameters
- host_port: (Omit when host + port table is used) a string combining host and port in the form 'hostname:port' string.
- host: (Omit when host_port parameter used) the hostname of the remote site string.
- port: (Omit when host_port parameter used) the port on the remote site integer.
Optional Parameters
- timeout: Maximum wait time, in seconds (default 5s) integer.
Returns
- A socket socket.
For More Information
- The net interface modules - file transfer and email using the FTP, FTPS, HTTP, SFTP and SMTP message protocols
- Using the Translator as an LLP Client
net.tcp.recv
Example Usage of Socket:recv()
local s = net.tcp.connect('hostname:8086') s:send(Data) local Ack = s:recv() s:close()
Usage
Socket:recv()
Receive data from a remote host via an open socket.
Returns
- The data (a string) or nil (connection closed) string or nil.
For More Information
net.tcp.send
Example Usage of Socket:send(Data [, Start [, Stop]])
local s = net.tcp.connect('hostname:8086') s:send(Data) local Ack = s:recv() s:close()
Usage
Socket:send(Data [, Start [, Stop]])
Send data to a remote host via an open socket.
Required Parameters
- Socket: The socket to send data on table.
- Data: The data to send string.
Optional Parameters
- Start: Where in Data to start integer.
- End: Where in Data to stop integer.
Returns
- The number of bytes sent integer.
For More Information
node
node.append
Example Usage of Node:append(Type, Value)
-- recommended usage: local node = Node:append(Type, Value) -- which is shorthand for: local node = node.append(Node, Type, Value)
Usage
Node:append(Type, Value)
Create and append a new node (works with XML only).
Required Parameters
- Node: The XML node to which a new child node is to be appended xml node tree.
- Type: The type of the new node: xml.ELEMENT, xml.ATTRIBUTE, xml.TEXT or xml.CDATA string.
- Value: The name or data of the new node string
Returns
- The new node which was appended xml node tree.
For More Information
- The node module - working with messages in Node Tree format
- Generating an XML document i.e. like a CDA document
- Writing extensions to the node and string libraries
- Understanding Lua OO syntax: what the colon operator means
node.child
Example Usage of Node:child(Name [, Repeat])
-- recommended usage: local name = Node:child(Name) -- which is shorthand for: local name = node.child(Node, Name)
-- local name = Node:child(Name, Repeat)
Usage
Node:child(Name [, Repeat])
Find a child with a specific name.
Required Parameters
- Node: The parent node node tree.
- Name: The name of the child to return string.
Optional Parameters
- Repeat: When several children have the same name, this can be used to specify which of them to return integer
Returns
- The child with the specified name node tree.
For More Information
- The node module - working with messages in Node Tree format
- Parsing the IguanaConfiguration.xml file
- Writing extensions to the node and string libraries
- Understanding Lua OO syntax: what the colon operator means
node.childCount
Example Usage of Node:childCount([Name])
-- recommended usage: local cnt = Node:childCount() -- which is shorthand for: local cnt = node.childCount(Node)
-- count named children only local cnt = Node:childCount(Name)
Usage
Node:childCount([Name])
Determine the number of children a node has.
Required Parameters
- Node: The node whose children are to be counted node tree.
Optional Parameters
- Name: When used, only children with this name are counted string.
Returns
- The number of children integer.
For More Information
- The node module - working with messages in Node Tree format
- Parsing the IguanaConfiguration.xml file
- Writing extensions to the node and string libraries
- Understanding Lua OO syntax: what the colon operator means
node.insert
Example Usage of Node:insert(Index, Type, Value)
-- recommended usage: local node = Node:insert(Index, Type, Value) -- which is shorthand for: local node = node.insert(Node, Index, Type, Value)
Usage
Node:insert(Index, Type, Value)
Create and insert a new node (works with XML only).
Required Parameters
- Node: The XML node to which a new child node is to be appended xml node tree.
- Index: The index at which the new node should be inserted integer.
- Type: The type of the new node: xml.ELEMENT, xml.ATTRIBUTE, xml.TEXT or xml.CDATA string.
- Value: The name or data of the new node string.
Returns
- The new node which was inserted node tree.
For More Information
- The node module - working with messages in Node Tree format
- Writing extensions to the node and string libraries
- Understanding Lua OO syntax: what the colon operator means
node.isKey
Example Usage of Node:isKey()
-- recommended usage: local iskey = Node:isKey() -- which is shorthand for: local iskey = node.isKey(Node)
Usage
Node:isKey()
Determine if a column is the primary key for the table.
Note: This function only works with table node trees.
Required Parameters
- Node: The node to be checked table node tree.
Returns
- True if the column is a primary key, false otherwise boolean.
For More Information
- The node module - working with messages in Node Tree format
- Writing extensions to the node and string libraries
- Understanding Lua OO syntax: what the colon operator means
node.isLeaf
Example Usage of Node:isLeaf()
-- recommended usage: local isleaf = Node:isLeaf() -- which is shorthand for: local isleaf = node.isLeaf(Node)
Usage
Node:isLeaf()
Determine if a node is a leaf.
Required Parameters
- Node: The node to be checked node tree.
Returns
- True if the node is a leaf (has no children), false otherwise boolean.
For More Information
- The node module - working with messages in Node Tree format
- Writing extensions to the node and string libraries
- Understanding Lua OO syntax: what the colon operator means
node.isNull
Example Usage of Node:isNull()
-- recommended usage: local isnull = Node:isNull() -- which is shorthand for: local isnull = node.isNull(Node)
Usage
Node:isNull()
Determine if a node is null.
Required Parameters
- Node: The node to be checked node tree.
Returns
- True if the node is null (not present), false otherwise boolean.
For More Information
- The node module - working with messages in Node Tree format
- Dealing with NULL data from databases
- Writing extensions to the node and string libraries
- Understanding Lua OO syntax: what the colon operator means
node.mapRange
Example Usage of Node:mapRange(Source, Start [, End])
-- recommended usage: local Node:mapRange(Source, Start) -- which is shorthand for: local node.mapRange(Dest, Source, Start)
-- local Node:mapRange(Source, Start, End)
Usage
Node:mapRange(Source, Start [, End])
Maps a range of fields from a source node to a destination node.
Required Parameters
- Dest: The destination node node tree.
- Source: The source node node tree.
- start: An index representing the start of the range integer.
Optional Parameters
- end: An index representing the end of the range integer.
For More Information
- The node module - working with messages in Node Tree format
- Translating HL7
- Writing extensions to the node and string libraries
- Understanding Lua OO syntax: what the colon operator means
node.mapTree
Example Usage of Node:mapTree(Source)
-- recommended usage: Node:mapTree(Source) -- which is shorthand for: node.mapTree(Dest, Source)
Usage
Node:mapTree(Source)
Maps fields from a source node to a destination node.
Required Parameters
- Dest: The destination node node tree.
- Source: The source node node tree.
For More Information
- The node module - working with messages in Node Tree format
- Tracing an HL7 message
- Writing extensions to the node and string libraries
- Understanding Lua OO syntax: what the colon operator means
node.nodeName
Example Usage of Node:nodeName()
-- recommended usage: local name = Node:nodeName(Name) -- which is shorthand for: local name = node.nodeName(Node, Name)
Usage
Node:nodeName()
Determine the name of a node.
Required Parameters
- Node: The node whose name is to be returned node tree.
Returns
- The name of a node string.
For More Information
- The node module - working with messages in Node Tree format
- Helper method to see if a node has a member with a given name
- Writing extensions to the node and string libraries
- Understanding Lua OO syntax: what the colon operator means
node.nodeType
Example Usage of Node:nodeType()
-- recommended usage: local type = Node:nodeType() -- which is shorthand for: local type = node.nodeType(Node)
Usage
Node:nodeType()
Determine the type and category of a node.
Required Parameters
- Node: The node whose type is to be returned node tree.
Returns
- The type and category of the node as a string string.
For More Information
- The node module - working with messages in Node Tree format
- Node Types for Iguana Node Trees
- Formatting output HL7 without trailing | characters
- Writing extensions to the node and string libraries
- Understanding Lua OO syntax: what the colon operator means
node.nodeValue
Example Usage of Node:nodeValue()
-- recommended usage: local value = Node:nodeValue() -- which is shorthand for: local value = node.nodeValue(Node)
Usage
Node:nodeValue()
Determine the value of a node.
Required Parameters
- Node: The node whose value is to be returned node tree
Returns
- The value of a node string.
For More Information
- The node module - working with messages in Node Tree format
- S() versus nodeValue() - which string conversion to use
- Writing extensions to the node and string libraries
- Understanding Lua OO syntax: what the colon operator means
node.remove
Example Usage of Node:remove(Index)
-- recommended usage: local isleaf = Node:remove(Index) -- which is shorthand for: local isleaf = node.remove(Node, Index)
Usage
Node:remove(Index)
Removes a child node.
Required Parameters
- Node: The node from which a child is to be removed node tree.
- Index: The index or name of the child to remove string.
For More Information
- The node module - working with messages in Node Tree format
- Writing extensions to the node and string libraries
- Understanding Lua OO syntax: what the colon operator means
node.setInner
Example Usage of Node:setInner(Content)
-- recommended usage: local node = Node:setInner(Content) -- which is shorthand for: local node = node.setInner(Node, Content)
Usage
Node:setInner(Content)
Sets the contents of an XML node (works with XML only).
Required Parameters
- Node: The node whose contents are being set node tree.
- Content: A string containing the content to be parsed string.
Returns
- The modified node after its contents have been set node tree.
For More Information
- The node module - working with messages in Node Tree format
- Generating an XML document i.e. like a CDA document
- Writing extensions to the node and string libraries
- Understanding Lua OO syntax: what the colon operator means
node.setNodeValue
Example Usage of Node:setNodeValue(Value)
MyNode:setNodeValue(os.date('%Y%m%H%m'))
-- which is equivalent to
node.setNodeValue(MyNode, os.date('%Y%m%H%m'))
local Msg = hl7.message{vmd='demo.vmd', name='ADT'}
-- you want to set the Time in the MSH segment:
Msg.MSH[7][1] = os.date('%Y%m%H%m') -- works: assigns value to the child node
Msg.MSH[7][1]:setNodeValue(os.date('%Y%m%H%m')) -- works: set the node value
-- if you decide to use a variable then:
local MsgTime = Msg.MSH[7][1]
MsgTime = os.date('%Y%m%H%m') -- fails: assigns the date to the variable (try it)
MsgTime:setNodeValue(os.date('%Y%m%H%m')) -- works: set the node value
-- a useful function to empty/clear nodes with or without children
function node:clearNode()
trace(self)
if self:isLeaf() then
self:setNodeValue('') -- usng setNodeValue() is the only way to clear leaf nodes
else
for nChild = self:childCount(), 1 , -1 do
self:remove(nChild)
end
trace(self)
end
end
Usage
Node:setNodeValue(Value)
Updates the value of this node with the value provided in the parameter.
Required Parameters
- Node: The node which is being set. node tree
- Value: The new value of the node. string
Returns
- the node itself whose value was just set (for chaining). node tree
For More Information
- The node module - working with messages in Node Tree format
- Understanding Lua OO syntax: what the colon operator means
os
os.clock
Example Usage of os.clock()
local duration = os.clock()
trace(duration)
-- the sub-second portion of the clock time can be useful
local _,subsec = math.modf(os.clock())
local msec=tostring(subsec):sub(3,5)
trace (subsec) -- as a number
trace (msec) -- as a millisecond string
Usage
os.clock()
Returns an approximation of the amount in seconds of CPU time used by the program.
Returns
- An approximation of the amount in seconds of CPU time used by the program number.
For More Information
- The os modules - operating system utilities
- How to build milliseconds value for timestamp from os.clock() reading
- Online documentation for os.clock
os.date
Example Usage of os.date([format [, time]])
-- today's date and time
local todayDateTime = os.date('%c')
-- today's date and time (default format = '%c')
local todayDateTime = os.date()
-- today's date returned in a table
local todayDateTime = os.date('*t')
-- using custom (userdata) input generated from os.time()
os.date('%c',os.time{year=1999, month=12, day=1}) -- date returned as formatted string
os.date('*t',os.time{year=1999, month=12, day=1}) -- date returned as a table
os.date(_,os.time{year=1999, month=12, day=1}) -- date returned as formatted string
os.date('',os.time{year=1999, month=12, day=1}) -- returns '' (an empty string)
Usage
os.date([format [, time]])
Returns a string or a table containing date and time, formatted according to the given string format
.
Note: os.date
is identical to os.ts.date
, except that os.ts.date
takes a Unix Epoch Time for the "time" parameter.
If the time
argument is present, this is the custom time format (userdata) returned from os.time
(see the os.time
function for a description of this value). Otherwise, os.date
formats the current time.
If format starts with '!', then the date is formatted in Coordinated Universal Time (UTC).
If format
is the string '*t
', then os.date
returns a table with the following fields: year
(four digits), month
(1--12), day
(1--31), hour
(0--23), min
(0--59), sec
(0--61), wday
(weekday, Sunday is 1), and yday
(day of the year).
If format
is not '*t
', then os.date
returns the date as a string, formatted according to the same rules as the C function strftime
.
When called without arguments, os.date
returns a reasonable date and time representation that depends on the host system and on the current locale (that is, os.date()
is equivalent to os.date('%c')
).
This table gives the strftime codes that are accepted.
Code | Replaced by | Example |
---|---|---|
%a | Abbreviated weekday name | Thu |
%A | Full weekday name | Thursday |
%b | Abbreviated month name | Aug |
%B | Full month name | August |
%c | Date and time representation | Thu Aug 23 14:55:02 2001 |
%d | Day of the month (01-31) | 23 |
%H | Hour in 24h format (00-23) | 14 |
%I | Hour in 12h format (01-12) | 02 |
%j | Day of the year (001-366) | 235 |
%m | Month as a decimal number (01-12) | 08 |
%M | Minute (00-59) | 55 |
%p | AM or PM designation | PM |
%S | Second (00-61) | 02 |
%U | Week number with the first Sunday as the first day of week one (00-53) | 33 |
%w | Weekday as a decimal number with Sunday as 0 (0-6) | 4 |
%W | Week number with the first Monday as the first day of week one (00-53) | 34 |
%x | Date representation * | 08/23/01 |
%X | Time representation * | 14:55:02 |
%y | Year, last two digits (00-99) | 01 |
%Y | Year | 2001 |
%% | A % sign | % |
Required Parameters
- format: Format string string.
- time: Time object to be formatted custom format (userdata).
Returns
- Date and time as a string string. OR date and time as a table table.
For More Information
- The os modules - operating system utilities
- The evolution of Iguana Date and Time functions
- Date time conversion with Iguana
- Using os.date to output arbitrary date/time formats
- Lua 5.0 online documentation for os.date and os.time(with strftime codes)
os.difftime
Example Usage of os.difftime(t2, t1)
-- get the difference between the current time and another time
os.difftime(os.time(), os.time{year=1999, month=12, day=01, hour=22})
Usage
os.difftime(t2, t1)
Returns the number of seconds from time t1
to time t2
. It is important to use this function rather than comparing dates directly, since this function will take into account time zones and daylight saving.
Note: os.difftime
is identical to os.ts.difftime
, except that os.ts.difftime
takes a Unix Epoch Times for the "t2" and "t1" parameters.
Note: the time parameters must be supplied in the custom time format (userdata) returned from os.time
, dates formatted as strings do not work.
Required Parameters
- t2: End time custom format (userdata).
- t1: Start time custom format (userdata).
Returns
- The number of seconds from time
t1
to timet2
integer.
For More Information
- The os modules - operating system utilities
- The evolution of Iguana Date and Time functions
- Date time conversion with Iguana
os.execute
Example Usage of os.execute([command])
local Success = os.execute('dir > out.temp')
os.execute('net start Iguana')
os.execute('"C:/Program files/iNTERFACEWARE/Chameleon/Simulator.exe"')
Usage
os.execute([command])
Execute an external application - usually a command line. It passes command
to be executed by an operating system shell. It returns a status code, which is system-dependent. If command
is absent, then it returns nonzero if a shell is available and zero otherwise.
You might want to consider using io.popen instead of os.execute since it allows you to see the output of a command line program.
Optional Parameters
- command: Command to run string.
Returns
- A status code, which is system-dependent integer.
For More Information
os.fs
os.fs.abspath
Example Usage of os.fs.abspath(path)
local FullPath = os.fs.abspath('..\\docs\\')
Usage
os.fs.abspath(path)
Convert a relative path to an absolute one.
Required Parameters
- path: A relative path to convert to an absolute path string.
Returns
- An absolute path for 'path' string.
For More Information
os.fs.access
Example Usage of os.fs.access(path [, mode])
local ReadWriteable = os.fs.access('IguanaConfiguration.xml', 'rw')
Usage
os.fs.access(path [, mode])
Determine if you can access the file specified. If 'mode' is not specified, only the existence of 'path' is checked. Otherwise, 'mode' is a string containing 'r', 'w', and/or 'x', for which read-, write- and/or execute-access is checked.
Required Parameters
- path: Path to be checked string.
Optional Parameters
- mode: Mode of access to test string.
Returns
- True if the file exists and can be accessed according to 'mode' (if used), false otherwise boolean.
For More Information
- The os modules - operating system utilities
- Sample backup script for monitoring configuration changes
- File and FTP Interfaces
os.fs.chmod
Example Usage of os.chmod(path, mode)
-- grant full access
os.fs.chmod('temp', '777') -- mode must be octal
os.fs.chmod('temp', '0777') -- can use 3 or 4 digits
os.fs.chmod('temp', '-rwxrwxrwx') -- mode using symbolic format does not work
Usage
os.chmod(path, mode)
Change the permission mode of a file.
Note: the mode must be in octal format, i.e., to apply full permissions use '0777' or '777' (the symbolic form '-rwxrwxrwx' does not work)
Required Parameters
- path: File path string.
- mode: Mode of access to apply (using octal format) string.
For More Information
- File and FTP Interfaces
- Wikipedia chmod
- Wikipedia file permissions, scroll down for numerical (octal) notation
os.fs.chown
Example Usage of os.chown(path, uid, gid)
-- change user and group
os.fs.stat('temp') -- identfy current uid and gid
os.fs.chown('temp', 503, 504) -- change user and group
os.fs.stat('temp') -- change back
os.fs.chown('temp', 501, 80) -- confirm
Usage
os.chown(path, uid, gid)
Change the owner and group IDs of a file.
Required Parameters
- path: File path string.
- uid: User ID integer.
- gid: Group ID integer.
For More Information
os.fs.glob
Example Usage of os.fs.glob(pattern)
for FileName, FileInfo in os.fs.glob('logs/*.log') do print(FileName) print(FileInfo) end
Usage
os.fs.glob(pattern)
Iterate over files matching a pattern. The pattern must contain wildcards such as * and ?. E.g., 'input/*.hl7'.
Required Parameters
- pattern: Pattern used to match files string.
Returns
- An iterator which returns the name of each matching file and its os.fs.stat() table interator function.
For More Information
os.fs.mkdir
Example Usage of os.fs.mkdir(path [, mode])
-- create and delete a directory
os.fs.mkdir('MyTempDir')
os.fs.stat('MyTempDir')
os.fs.rmdir('MyTempDir') -- remove (delete) the directory
os.fs.stat('MyTempDir') -- stats no longer available
Usage
os.fs.mkdir(path [, mode])
Create a new directory. The permission 'mode' can also be specified on POSIX platforms (defaults to 644).
Required Parameters
- path: Path to be created string.
Optional Parameters
- mode: Mode of access to apply string.
For More Information
- The os modules - operating system utilities
- Sample backup script for monitoring configuration changes
- File and FTP Interfaces
- Wikipedia mkdir
os.fs.rmdir
Example Usage of os.fs.rmdir(path)
-- create and delete a directory
os.fs.mkdir('MyTempDir')
os.fs.stat('MyTempDir')
os.fs.rmdir('MyTempDir') -- remove (delete) the directory
os.fs.stat('MyTempDir') -- stats no longer available
Usage
os.fs.rmdir(path)
Remove an empty directory.
Required Parameters
- path: Directory path string.
For More Information
os.fs.stat
Example Usage of os.fs.stat(path)
local FileInfo = os.fs.stat('IguanaConfiguration.xml')
Usage
os.fs.stat(path)
Collect various statistics on the specified file. It returns a Lua table with the following entries:
Field | Description |
---|---|
ctime | Create timestamp |
mtime | Last modified timestamp |
atime | Last accessed timestamp |
mode | Permission flags for the file |
size | Size of the file in bytes |
isdir | Is this file a directory? |
isreg | Is this a regular file |
Required Parameters
- path: File path string.
Returns
- A lua table with the file's information as shown above table.
For More Information
- The os modules - operating system utilities
- Sample backup script for monitoring configuration changes
- File and FTP Interfaces
- Wikipedia stat
os.fs.utime
Example Usage of os.fs.utime(path [, actime, modtime])
-- set access and modification times to current time
os.fs.utime('temp/Angel copy.png')
-- set access and modification times to '1 Jan 1999 03:37'
os.fs.utime('temp/Angel copy.png',915158239,915158239)
Usage
os.fs.utime(path [, actime, modtime])
Changes the access and modification times of the specified file. If called with no parameters both the access and modification time are set to the current time. The time parameters (actime
and modtime
) cannot be used separately they must be supplied together.
The time parameters must be supplied in Unix Epoch time format. You can get the current time in Unix Epoch format by using os.ts.time()
.
Required Parameters
- path: Path to the file to change string.
Optional Parameters
- actime: New file access time in epoch format time.
- modtime: New file modification time in epoch format time.
For More Information
os.getenv
Example Usage of os.getenv(varname)
local Path = os.getenv('PATH')
Usage
os.getenv(varname)
Returns the value of the process environment variable varname
, or nil if the variable is not defined. Combined with the ability to set environmental variables within Iguana this can be a powerful technique for customizing the behavior of scripts based the server they are sitting in.
Required Parameters
- varname: Name of the environment variable you want to retrieve string.
Returns
- Either the value of the process environment variable
varname
string. OR nil if the variable is not defined nil.
For More Information
- The os modules - operating system utilities
- Altering environmental variables using the Settings page
- Online documentation for os.getenv
os.remove
Example Usage of os.remove(filename)
-- create and delete a directory
os.fs.mkdir('MyTempDir')
os.fs.stat('MyTempDir')
os.remove('MyTempDir') -- remove (delete) the directory
os.fs.stat('MyTempDir') -- stats no longer available
Usage
os.remove(filename)
Deletes the file or directory with the given name. Directories must be empty to be removed. If this function fails, it returns nil, plus a string describing the error.
Required Parameters
- file: The file or directory to be deleted string.
Returns
- If this function fails, it returns nil nil.
- If this function fails, it also returns a string describing the error string.
For More Information
- The os modules - operating system utilities
- File and FTP Interfaces
- Online documentation for os.remove
os.rename
Example Usage of os.rename(oldname, newname)
-- create and create and rename a directory
os.fs.mkdir('MyTempDir')
os.fs.stat('MyTempDir')
os.rename('MyTempDir','YourTempDir') -- rename the directory
os.fs.stat('MyTempDir') -- stats no longer available
os.remove('YourTempDir')
Usage
os.rename(oldname, newname)
Renames a file or directory. If this function fails, it returns nil, plus a string describing the error.
Required Parameters
- oldname: Old file or directory name/path string.
- newname: New file or directory name/path string.
Returns
- If this function fails, it returns nil nil.
- If this function fails, it also returns a string describing the error string.
For More Information
- The os modules - operating system utilities
- File and FTP Interfaces
- Online documentation for os.rename
os.time
Example Usage of os.time([table])
get the current date/time
os.time()
specify date/time in a table (mandatory fields)
os.time{year=1999, month=12, day=01}
specify date/time in a table (all fields)
os.time{year=1999, month=12, day=1, hour=22, min=23, sec=24}
Usage
os.time([table])
Returns the current time when called without arguments, or a time representing the date and time specified by the given table.
Note: os.time
is identical to os.ts.time
, except that os.ts.time
returns a Unix Epoch time as an integer.
If specified the table must have fields year
, month
, and day
, and may have fields hour
, min
, and sec
(for a description of these fields, see the os.date
function). The value returned by os.time
can only be used as an argument to os.date
and os.difftime
.
Note: To find the difference duration between two times use os.difftime
function, which takes into account time zones and daylight saving.
Optional Parameters
- table: A table containing the the date and time to be formatted table.
Returns
- Date and Time custom format (userdata).
For More Information
- The os modules - operating system utilities
- The evolution of Iguana Date and Time functions
- Date time conversion with Iguana
- Lua 5.0 online documentation for os.date and os.time(with strftime codes)
os.tmpname
Example Usage of os.tmpname()
-- create and write to a temporary file
local tmp = os.tmpname()
trace(tmp)
local f=io.open(tmp, 'w')
f:write('Hello World!')
f:close()
os.remove(tmp) -- remove (delete) the file
io.open(tmp) -- trying to open again fails
Usage
os.tmpname()
Returns a string with a file name that can be used for a temporary file. The file must be explicitly opened before its use and explicitly removed when no longer needed.
On some systems (POSIX), this function also creates a file with that name, to avoid security risks. (Someone else might create the file with wrong permissions in the time between getting the name and creating the file.) You still have to open the file to use it and to remove it (even if you do not use it).
Returns
- A file name for a temporary file string.
For More Information
os.ts
os.ts.date
Example Usage of os.ts.date([format [, time]])
-- today's date and time
local todayDateTime = os.ts.date('%c')
-- today's date and time (default format = '%c')
local todayDateTime = os.ts.date()
-- today's UTC date returned in a table
local todayDateTime = os.ts.date('!*t')
-- using Unix Epoch Time input generated from os.ts.time()
os.ts.date('%c',os.ts.time{year=1999, month=12, day=1}) -- date returned as formatted string
os.ts.date('*t',os.ts.time{year=1999, month=12, day=1}) -- date returned as a table
os.ts.date(_,os.ts.time{year=1999, month=12, day=1}) -- date returned as formatted string
os.ts.date('',os.ts.time{year=1999, month=12, day=1}) -- returns '' (an empty string)
Usage
os.ts.date([format [, time]])
Returns a string or a table containing date and time, formatted according to the given string format
.
Note: os.ts.date
is identical to os.date
, except that os.date
takes a custom time format (userdata) returned from os.time
for the "time" parameter.
If the time
argument is present, this is the Unix Epoch time as an integer. Otherwise, os.ts.date
formats the current time.
If format
starts with '!
', then the date is formatted in Coordinated Universal Time (UTC).
If format
starts with '*t
', then os.ts.date
returns a table with the following fields: year
(four digits), month
(1--12), day
(1--31), hour
(0--23), min
(0--59), sec
(0--61), wday
(weekday, Sunday is 1), yday
(day of the year), and isdst
(daylight saving flag, a boolean).
If format
is not '*t
', then os.ts.date
returns the date as a string, formatted according to the same rules as the C function strftime
.
Note: '!
' + '*t
' can be combined as '!*t
' to return Coordinated Universal Time (UTC) in a table.
When called without arguments, os.ts.date
returns a reasonable date and time representation that depends on the host system and on the current locale (that is, os.ts.date()
is equivalent to os.ts.date('%c')
).
This table gives the strftime codes that are accepted.
Code | Replaced by | Example |
---|---|---|
%a | Abbreviated weekday name | Thu |
%A | Full weekday name | Thursday |
%b | Abbreviated month name | Aug |
%B | Full month name | August |
%c | Date and time representation | Thu Aug 23 14:55:02 2001 |
%d | Day of the month (01-31) | 23 |
%H | Hour in 24h format (00-23) | 14 |
%I | Hour in 12h format (01-12) | 02 |
%j | Day of the year (001-366) | 235 |
%m | Month as a decimal number (01-12) | 08 |
%M | Minute (00-59) | 55 |
%p | AM or PM designation | PM |
%S | Second (00-61) | 02 |
%U | Week number with the first Sunday as the first day of week one (00-53) | 33 |
%w | Weekday as a decimal number with Sunday as 0 (0-6) | 4 |
%W | Week number with the first Monday as the first day of week one (00-53) | 34 |
%x | Date representation * | 08/23/01 |
%X | Time representation * | 14:55:02 |
%y | Year, last two digits (00-99) | 01 |
%Y | Year | 2001 |
%% | A % sign | % |
Required Parameters
- format: Format string string.
Optional Parameters
- time: Time to be formatted (as a Unix Epoch time in seconds) integer.
Returns
- Either date and time as a string string. OR date and time as a table table.
For More Information
- The os modules - operating system utilities
- The evolution of Iguana Date and Time functions
- Date time conversion with Iguana
- Using os.date to output arbitrary date/time formats
- Lua 5.0 online documentation for os.date and os.time(with strftime codes)
os.ts.difftime
Example Usage of os.ts.difftime(t2, t1)
-- get the difference between the current time and another time
os.ts.difftime(os.ts.time(), os.ts.time{year=1999, month=12, day=01, hour=22})
Usage
os.ts.difftime(t2, t1)
Returns the number of seconds from time t1
to time t2
. It is important to use this function rather than comparing dates directly, since this function will take into account time zones and daylight saving.
Note: os.ts.difftime
is identical to os.difftime
, except that os.difftime
takes the custom time format (userdata) returned from os.time
for the "t2" and "t1" parameters.
Note: the time parameters must be supplied in Unix Epoch time as integers (same format as returned from os.ts.time
or os.ts.gmtime
), dates formatted as strings do not work.
Required Parameters
- t2: End time (as a Unix Epoch time in seconds) integer.
- t1: Start time (as a Unix Epoch time in seconds) integer.
Returns
- The number of seconds from time
t1
to timet2
integer.
For More Information
- The os modules - operating system utilities
- The evolution of Iguana Date and Time functions
- Date time conversion with Iguana
os.ts.gmdate
Example Usage of os.ts.gmdate([format [, time]])
-- today's date and time
local todayDateTime = os.ts.gmdate('%c')
-- today's date and time (default format = '%c')
local todayDateTime = os.ts.gmdate()
-- today's UTC date returned in a table
local todayDateTime = os.ts.gmdate('!*t')
-- using Unix Epoch Time input generated from os.ts.time()
os.ts.gmdate('%c',os.ts.time{year=1999, month=12, day=1}) -- date returned as formatted string
os.ts.gmdate('*t',os.ts.time{year=1999, month=12, day=1}) -- date returned as a table
os.ts.date(_,os.ts.time{year=1999, month=12, day=1}) -- date returned as formatted string
os.ts.gmdate('',os.ts.time{year=1999, month=12, day=1}) -- returns '' (an empty string)
Usage
os.ts.gmdate([format [, time]])
Returns a Coordinated Universal Time (UTC) as a string or a table containing date and time, formatted according to the given string format
.
Note: os.ts.gmdate
is identical to os.ts.date
, except that os.ts.gmdate
always returns a UTC date.
If the time
argument is present, this is the time to be formatted (a Unix Epoch time integer value). Otherwise, os.ts.gmdate
formats the current time.
The date is always formatted in Coordinated Universal Time (UTC). If format
is the string '*t
', then os.ts.gmdate
returns a table with the following fields: year
(four digits), month
(1--12), day
(1--31), hour
(0--23), min
(0--59), sec
(0--61), wday
(weekday, Sunday is 1), and yday
(day of the year).
If format
is not '*t
', then os.ts.gmdate
returns the date as a string, formatted according to the same rules as the C function strftime
.
When called without arguments, os.ts.gmdate
returns a reasonable date and time representation that depends on the host system and on the current locale (that is, os.ts.gmdate()
is equivalent to os.ts.gmdate('%c')
).
This table gives the strftime codes that are accepted.
Code | Replaced by | Example |
---|---|---|
%a | Abbreviated weekday name | Thu |
%A | Full weekday name | Thursday |
%b | Abbreviated month name | Aug |
%B | Full month name | August |
%c | Date and time representation | Thu Aug 23 14:55:02 2001 |
%d | Day of the month (01-31) | 23 |
%H | Hour in 24h format (00-23) | 14 |
%I | Hour in 12h format (01-12) | 02 |
%j | Day of the year (001-366) | 235 |
%m | Month as a decimal number (01-12) | 08 |
%M | Minute (00-59) | 55 |
%p | AM or PM designation | PM |
%S | Second (00-61) | 02 |
%U | Week number with the first Sunday as the first day of week one (00-53) | 33 |
%w | Weekday as a decimal number with Sunday as 0 (0-6) | 4 |
%W | Week number with the first Monday as the first day of week one (00-53) | 34 |
%x | Date representation * | 08/23/01 |
%X | Time representation * | 14:55:02 |
%y | Year, last two digits (00-99) | 01 |
%Y | Year | 2001 |
%% | A % sign | % |
Required Parameters
- format: Format string string.
- time: Time to be formatted (as a Unix Epoch time in seconds) integer.
Returns
- Either date and time as a string string. OR date and time as a table table.
For More Information
- The os modules - operating system utilities
- The evolution of Iguana Date and Time functions
- Date time conversion with Iguana
- Using os.date to output arbitrary date/time formats
- Lua 5.0 online documentation for os.date and os.time(with strftime codes)
os.ts.gmtime
Example Usage of os.ts.gmtime([time])
get the current date/time
os.ts.gmtime()
specify date/time in a table (mandatory fields)
os.ts.gmtime{year=1999, month=12, day=01}
specify date/time in a table (all fields)
os.ts.gmtime{year=1999, month=12, day=1, hour=22, min=23, sec=24}
Usage
os.ts.gmtime([time])
Returns the current time when called without arguments, or a time representing the date and time specified by the given table.
Note: os.ts.gmtime
is identical to os.ts.time
.
If specified the table must have fields year
, month
, and day
, and may have fields hour
, min
, sec
, and isdst
(for a description of these fields, see the os.ts.date
function). The value returned by os.ts.time
is a Unix Epoch time as an integer, which can be used as an argument to os.ts.date
and os.ts.difftime
.
Note: To find the difference duration between two times use os.ts.difftime
, which takes into account time zones and daylight saving. Subtracting Unix Epoch time values directly does not work, because it doesn't take into account time zones and daylight saving.
Optional Parameters
- table: A table containing the the date and time to be formatted table.
Returns
- A Unix Epoch time in seconds integer.
For More Information
- The os modules - operating system utilities
- The evolution of Iguana Date and Time functions
- Date time conversion with Iguana
- Lua 5.0 online documentation for os.date and os.time(with strftime codes)
os.ts.time
Example Usage of os.ts.time([table])
get the current date/time
os.ts.time()
specify date/time in a table (mandatory fields)
os.ts.time{year=1999, month=12, day=01}
specify date/time in a table (all fields)
os.ts.time{year=1999, month=12, day=1, hour=22, min=23, sec=24}
Usage
os.ts.time([table])
Returns the current time when called without arguments, or a time representing the date and time specified by the given table.
Note: os.ts.time
is identical to os.time
, except that os.time
returns a custom time format (userdata).
If specified the table must have fields year
, month
, and day
, and may have fields hour
, min
, sec
, and isdst
(for a description of these fields, see the os.ts.date
function). The value returned by os.ts.time
is a Unix Epoch time as an integer, which can be used as an argument to os.ts.date
and os.ts.difftime
.
Note: To find the difference duration between two times use os.ts.difftime
, which takes into account time zones and daylight saving. Subtracting Unix Epoch time values directly does not work, because it doesn't take into account time zones and daylight saving.
Optional Parameters
- table: A table containing the the date and time to be formatted table.
Returns
- A Unix Epoch time in seconds integer.
For More Information
- The os modules - operating system utilities
- The evolution of Iguana Date and Time functions
- Date time conversion with Iguana
- Lua 5.0 online documentation for os.date and os.time(with strftime codes)
package
package.loadlib
Usage
package.loadlib(libname, funcname)
Dynamically links the host program with the C library libname
. Inside this library, looks for a function funcname
and returns this function as a C function. (So, funcname
must follow the protocol (see lua_CFunction
)).
This is a low-level function. It completely bypasses the package and module system. Unlike require
, it does not perform any path searching and does not automatically adds extensions. libname
must be the complete file name of the C library, including if necessary a path and extension. funcname
must be the exact name exported by the C library (which may depend on the C compiler and linker used).
This function is not supported by ANSI C. As such, it is only available on some platforms (Windows, Linux, Mac OS X, Solaris, BSD, plus other Unix systems that support the dlfcn
standard).
Required Parameters
- libname: Name of the library to load string.
- funcname: Name of the function to use string.
Returns
- The function
funcname
as a C function function.
For More Information
package.seeall
Example Usage of package.seeall(module)
module('foo', package.seeall)
Usage
package.seeall(module)
Sets a metatable for module with its __index field referring to the global environment, so that this module inherits values from the global environment. To be used as an option to function module
.
Generally speaking we advise not using the module keyword for defining your own modules.
Required Parameters
- module: Name of the module string.
For More Information
- The package module - package functions
- Working with shared modules.
- Online documentation for package.seeall.
queue
queue.push
Example Usage of queue.push{data=<value>} or queue.push(<value>)
local Id = queue.push{data=Data}
iguana.logInfo('Message queued', Id)
-- split a large message into several parts and queue them separately
queue.push('Message part one')
queue.push('Message part two')
queue.push('Message part three')
Usage
queue.push{data=<value>} or queue.push(<value>)
Pushes a message for the channel into the Iguana queue when the channel is running. Be aware that queue.push()
does not push messages into the queue when using the editor (test mode). queue.push()
works in three types of component: Filter, From Translator, and From HTTPS. You can call queue.push()
multiple times in any of these components, an example where this is useful is when splitting a complex message into several smaller messages.
The queue.push()
function returns the message ID of the current message being processed. This is a unique message ID from Iguana's internal logging system, formatted as a string containing today's date followed by seven digits "YYYYMMDD-NNNNNNN". See the iguana.messageId
help for more information.
Note: When being used in the editor (test mode) a return of "0-0" is displayed in annotations as a placeholder (IDs are only generated when a channel is running).
Required Parameters
- data: The message to be pushed into the queue string.
Returns
- A unique Message ID string in the format "YYYYMMDD-NNNNNNN" string.
For More Information
- The queue module - working with the Iguana message queue
- More about queue.push and Iguana's queuing system
- Filtering Sensitive Demographics from Real Data
- Random ADT Generator
- Polling a database, and generating CSV files
- Calling a web service
string
The string module contains all the string utility functions.
string.byte
Example Usage of string:byte([i [, j]])
local A,B,C = string.byte('ABC', 1,3)
local A,B,C = AString:byte(1,3)
Usage
string:byte([i [, j]])
Returns the internal numerical codes of the characters s[i]
, s[i+1]
, ···, s[j]
. The default value for i
is 1; the default value for j
is i
.
Note: that numerical codes are not necessarily portable across platforms.
Required Parameters
- s: Source string string.
Optional Parameters
- i: Start position integer.
- j: End position integer.
Returns
- Multiple returns: One numerical code for each requested character integer.
For More Information
- The string module - string operations
- Extending the string library
- Online documentation for string.byte
- Strings Tutorial
- String Library Tutorial
- String Recipes
- Patterns Tutorial
- Understanding Lua OO syntax: what the colon operator means
string.char
Example Usage of string.char(code, ...)
local ABC = string.char(65,66,67)
Usage
string.char(code, ...)
Receives zero or more integers. Returns a string with length equal to the number of arguments, in which each character has the internal numerical code equal to its corresponding argument. Note that numerical codes are not necessarily portable across platforms.
Required Parameters
- code: Multiple parameters: Integer representing a character integer.
Returns
- A string representing the supplied numerical codes string.
For More Information
- The string module - string operations
- Extending the string library
- Online documentation for string.char
- Strings Tutorial
- String Library Tutorial
- String Recipes
- Patterns Tutorial
- Understanding Lua OO syntax: what the colon operator means
string.dump
Example Usage of string.dump(function)
function Boom() return 'Bang' end function main() local A = string.dump(Boom) local Func = loadstring(A) local Bang = Func(Boom) end
Usage
string.dump(function)
Returns a string containing a binary representation of the given function, so that a later loadstring
on this string returns a copy of the function.
Note: function
must be a Lua function without upvalues.
Required Parameters
- s: Function to be dumped function.
Returns
- A string containing a binary representation of the given function string.
For More Information
- The string module - string operations
- Extending the string library
- Online documentation for string.dump
- Strings Tutorial
- String Library Tutorial
- String Recipes
- Patterns Tutorial
- Understanding Lua OO syntax: what the colon operator means
string.find
Example Usage of string:find(pattern [, init [, plain]])
local s= 'Hello Lua user are you enjoying Lua?' local ix1, ix2=s:find('Lua') --> 7,9
local s= 'Hello Lua user are you enjoying Lua?' local ix1, ix2=s:find('Lua', 10) --> 33,35
-- start search 5 characters from the end of the string local s= 'Hello Lua user are you enjoying Lua?' local ix1, ix2=s:find('Lua', -5) --> 33,35
-- capture the "pair" but not "=" sign pair = 'name = Anna' _, _, key, value = pair:find('(%a+)%s*=%s*(%a+)') print(key, value) --> name Anna
Usage
string:find(pattern [, init [, plain]])
Looks for the first match of pattern
in the string s
. If it finds a match, then find
returns the indices of s
where this occurrence starts and ends; otherwise, it returns nil. A third, optional numerical argument init
specifies where to start the search; its default value is 1 and can be negative. A value of true as a fourth, optional argument plain
turns off the pattern matching facilities, so the function does a plain "find substring" operation, with no characters in pattern
being considered "magic".
Note: if plain
is given, then init
must be given as well. If the pattern has captures, then in a successful match the captured values are also returned, after the two indices.
Required Parameters
- s: String to be searched string.
- pattern: Pattern to be matched string.
Optional Parameters
- init: Position to start the search string.
- plain: Turn off pattern matching, defaults to false boolean.
Returns
- Index for start of match or nil if no match found integer or nil.
- Index for end of match (not returned if no match) string.
For More Information
- The string module - string operations
- Extending the string library
- Online documentation for string.find
- Strings Tutorial
- String Library Tutorial
- String Recipes
- Patterns Tutorial
- Understanding Lua OO syntax: what the colon operator means
string.format
Example Usage of string.format(formatstring, string, ...)
string.format("%s %q", "Hello", "Lua user!") -- string and quoted string -->Hello "Lua user!"
string.format("%c%c%c", 76,117,97) -- char -->Lua
string.format("%e, %E", math.pi,math.pi) -- exponent -->3.141593e+000, 3.141593E+000
string.format("%f, %g", math.pi,math.pi) -- float and compact float -->3.141593, 3.14159
string.format("%d, %i, %u", -100,-100,-100) -- signed, signed, unsigned integer -->-100, -100, 4294967196
string.format("%o, %x, %X", -100,-100,-100) -- octal, hex, hex -->37777777634, ffffff9c, FFFFFF9C
Usage
string.format(formatstring, string, ...)
Returns a formatted version of its variable number of arguments following the description given in its first argument (which must be a string). The format string follows the same rules as the printf
family of standard C functions. The only differences are that the options/modifiers *
, l
, L
, n
, p
, and h
are not supported and that there is an extra option, q
. The q
option formats a string in a form suitable to be safely read back by the Lua interpreter: the string is written between double quotes, and all double quotes, newlines, embedded zeros, and backslashes in the string are correctly escaped when written. For instance, the call string.format('%q', 'a string with "quotes" and \n new line')
will produce the string: "a string with \"quotes\" and \
The options
new line"c
, d
, E
, e
, f
, g
, G
, i
, o
, u
, X
, and x
all expect a number as argument, whereas q
and s
expect a string. This function does not accept string values containing embedded zeros, except as arguments to the q
option.
Required Parameters
- formatstring: Format string string.
- string: Multiple parameters: String(s) or number(s) to be formatted integer.
Returns
- A string formatted as specified string.
For More Information
- The string module - string operations
- Extending the string library
- Online documentation for string.format
- Strings Tutorial
- String Library Tutorial
- String Recipes
- Patterns Tutorial
- Understanding Lua OO syntax: what the colon operator means
string.gfind
string.gmatch
Example Usage of string:gmatch(pattern)
-- This loop iterates over all the words from string s
, printing one per line:
s = "hello world from Lua"
for w in s:gmatch("%a+") do
print(w)
end
-- The next example collects all pairs key=value
from the given string into a table:
t = {}
s = "from=world, to=Lua"
for k, v in s:gmatch("(%w+)=(%w+)") do
t[k] = v
end
Usage
string:gmatch(pattern)
Returns an iterator function that, each time it is called, returns the next captures from pattern
over string s
. If pattern
specifies no captures, then the whole match is produced in each call.
For this function, a '^
' at the start of a pattern does not work as an anchor, as this would prevent the iteration.
Note: string.gfind
is a alias for string.gmatch
(string.gfind
was renamed string.gmatch
in Lua 5.1).
Required Parameters
- s: String to be searched string.
- pattern: Pattern to be matched string.
Returns
- An iterator function, used to loop through the pattern matches iterator function.
For More Information
- The string module - string operations
- Extending the string library
- Strings Tutorial
- String Library Tutorial
- String Recipes
- Patterns Tutorial
- Online documentation Changes in the Libraries
- Online documentation for string.gmatch
- Understanding Lua OO syntax: what the colon operator means
string.gsub
Example Usage of string:gsub(pattern, repl [, n])
local s = "hello world" x = s:gsub( "(%w+)", "%1 %1") --> x="hello hello world world"
local s = "hello world" x = s:gsub("%w+", "%0 %0", 1) --> x="hello hello world"
local s = "hello world from Lua" x = s:gsub("(%w+)%s*(%w+)", "%2 %1") --> x="world hello Lua from"
local s = "home = $HOME, user = $USER" x = s:gsub("%$(%w+)", os.getenv) --> x="home = /home/roberto, user = roberto"
x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s) return loadstring(s)() end) --> x="4+5 = 9"
local t = {name="lua", version="5.1"} x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t) --> x="lua-5.1.tar.gz"
Usage
string:gsub(pattern, repl [, n])
Returns a copy of s
in which all (or the first n
, if given) occurrences of the pattern
have been replaced by a replacement string specified by repl
, which can be a string, a table, or a function. gsub
also returns, as its second value, the total number of matches that occurred.
If repl
is a string, then its value is used for replacement. The character %
works as an escape character: any sequence in repl
of the form %n
, with n between 1 and 9, stands for the value of the n-th captured substring (see below). The sequence %0
stands for the whole match. The sequence %%
stands for a single %
. If repl
is a table, then the table is queried for every match, using the first capture as the key; if the pattern specifies no captures, then the whole match is used as the key.If repl
is a function, then this function is called every time a match occurs, with all captured substrings passed as arguments, in order; if the pattern specifies no captures, then the whole match is passed as a sole argument.If the value returned by the table query or by the function call is a string or a number, then it is used as the replacement string; otherwise, if it is false or nil, then there is no replacement (that is, the original match is kept in the string).
Required Parameters
- s: String to be searched string.
- pattern: Pattern to be matched string.
- repl: Substitution string OR function OR table.
Optional Parameters
- n: Maximum number of matches to substitute integer.
Returns
- A copy of
s
in which the specified occurrences of thepattern
been replaced string.
For More Information
- The string module - string operations
- Extending the string library
- Online documentation for string.gsub
- Strings Tutorial
- String Library Tutorial
- String Recipes
- Patterns Tutorial
- Understanding Lua OO syntax: what the colon operator means
string.len
Example Usage of string:len()
local s = 'abcd' trace(#s, s:len(), string.len(s), s.len(s)) --> trace(4,4,4,4)
Usage
string:len()
Receives a string and returns its length. The empty string ""
has length 0. Embedded zeros are counted, so "a\000bc\000"
has length 5.
Note: string:len()
is equivalent to #string
(the # operator will also return the length of a table).
Required Parameters
- s: Source string to return the length of string.
Returns
- The length of the string integer.
For More Information
- The string module - string operations
- What is the difference between the "#" operator and string.len(s) function?
- Extending the string library
- Online documentation for string.len
- Strings Tutorial
- String Library Tutorial
- String Recipes
- Patterns Tutorial
- Understanding Lua OO syntax: what the colon operator means
string.lower
Usage
string:lower()
Receives a string and returns a copy of this string with all uppercase letters changed to lowercase. All other characters are left unchanged. The definition of what an uppercase letter is depends on the current locale.
Required Parameters
- s: Source string to convert to lowercase string.
Returns
- A copy of the string with all uppercase letters changed to lowercase string.
For More Information
- The string module - string operations
- Extending the string library
- Online documentation for string.lower
- Strings Tutorial
- String Library Tutorial
- String Recipes
- Patterns Tutorial
- Understanding Lua OO syntax: what the colon operator means
string.match
Example Usage of string:match(pattern [, init])
local s='hello Lua user are you enjoying Lua today' s:match('Lua%s(%a+)') --> "user" s:match('Lua%s(%a+)',20) --> "today" s:match('Lua%s(%a+)',-10) --> "today"
Usage
string:match(pattern [, init])
Looks for the first match of pattern
in the string s
. If it finds one, then match
returns the captures from the pattern; otherwise it returns nil. If pattern
specifies no captures, then the whole match is returned. A third, optional numerical argument init
specifies where to start the search; its default value is 1 and can be negative.
Required Parameters
- s: String to be searched string.
- pattern: Pattern to be matched string.
Optional Parameters
- init: Position to start the search string.
Returns
- Either the matching string string. OR multiple returns: One for each matching capture string.
For More Information
- The string module - string operations
- Extending the string library
- Online documentation for string.match
- Strings Tutorial
- String Library Tutorial
- String Recipes
- Patterns Tutorial
- Understanding Lua OO syntax: what the colon operator means
string.rep
Usage
string:rep(n)
Returns a string that is the concatenation of n
copies of the string s
.
Required Parameters
- s: Source string string.
- n: Number of copies to concatenate integer.
Returns
- A string that is the concatenation of
n
copies of the strings
string.
For More Information
- The string module - string operations
- Extending the string library
- Online documentation for string.rep
- Strings Tutorial
- String Library Tutorial
- String Recipes
- Patterns Tutorial
- Understanding Lua OO syntax: what the colon operator means
string.reverse
Usage
string:reverse()
Returns a string that is the string s
reversed.
Required Parameters
- s: Source string string.
Returns
- String
s
in the reverse order string.
For More Information
- The string module - string operations
- Extending the string library
- Online documentation for string.reverse
- Strings Tutorial
- String Library Tutorial
- String Recipes
- Patterns Tutorial
- Understanding Lua OO syntax: what the colon operator means
string.rxmatch
Example Usage of string:rxmatch(regex [, mods])
-- This loop iterates over all the words from string s
, printing one per line:
s = "hello world from Lua"
for w in s:rxmatch("\\S*") do
print(w)
end
-- The next example collects all pairs key=value
from the given string into a table:
t = {}
s = "from=world, to=Lua"
for k, v in s:rxmatch("(\\w*)=(\\w*)") do
t[k] = v
end
Usage
string:rxmatch(regex [, mods])
Returns an iterator function that, each time it is called, returns the next captures from regex
over string s
. If regex
specifies no captures, then the whole match is produced in each call.
For this function, any Perl-Compatible Regular Expression may be used, including the start-of-string anchor ^
and the end-of-string anchor $
. Common token shorthands like \s
for whitespace and \D
for non-digits are also supported.
An additional optional argument can be specified as a string of modifier characters to enable additional Regular Expression behaviour:
- m: Multi-line anchoring mode
- s: Single-line/Dot-all mode
- i: Case-insensitive matching
- x: Extended mode
- X: Extra mode
- u: Unicode support mode
- U: Ungreedy/lazy matching (
?
now means greedy matching) - A: Anchored mode
- J: Allow duplicate subpattern names
For full details on how these modifiers work, visit the additional rxmatch examples page.
Note: Backslashes must be escaped (\\
) when specifying token shorthands or $
in the interpreter (e.g. \\w
).
Required Parameters
- s: String to be searched string.
- regex: Regular expression to be matched string.
Optional Parameters
- mods: Regular expression modifiers string.
Returns
- An iterator function, used to loop through the regular expression matches iterator function.
For More Information
- The string module - string operations
- Extending the string library
- Strings Tutorial
- Understanding Lua OO syntax: what the colon operator means
- Additional examples for rxmatch
string.rxsub
Example Usage of string:rxsub(regex, sub [, n ] [, mods])
local s = "hello world" x = s:rxsub("(\\w+)", "$1 $1") --> x="hello hello world world"
local s = "hello world" x = s:rxsub("(\\w+)", "$0 $0", 1) --> x="hello hello world"
local s = "hello world from Lua" x = s:rxsub("(\\w+)\\s*(\\w+)", "\\2 \\1") --> x="world hello Lua from"
local s = "home = $HOME, user = $USER" x = s:rxsub("\\$(\\w+)", os.getenv) --> x="home = /home/roberto, user = roberto"
local s = "4 + 5 = $return 4 + 5$" x = s:rxsub("\\$(.*?)\\$", function (s) return loadstring(s)() end) --> x="4 + 5 = 9"
local t = {name="lua", version="5.1"} local x = string.rxsub("$name-$version.tar.gz", "\\$(\\w+)", t) --> x="lua-5.1.tar.gz"
Usage
string:rxsub(regex, sub [, n ] [, mods])
This function behaves almost identically to string.gsub. It accepts the same substitution values along with the maximum match count, and it returns the same values. The only difference is that the first argument can be any Perl Compatible Regular Expression.
Similarly, if the substitution pattern is a string, back substitutions are supported in the form $n
or \n
where n
references the value of a specific match group. For regular expressions, back substitution indices may exceed 9. Any index with a valid corresponding match group is supported.
An additional optional argument can be specified as a string of modifier characters to enable additional Regular Expression behaviour:
- m: Multi-line anchoring mode
- s: Single-line/Dot-all mode
- i: Case-insensitive matching
- x: Extended mode
- X: Extra mode
- u: Unicode support mode
- U: Ungreedy/lazy matching (
?
now means greedy matching) - A: Anchored mode
- J: Allow duplicate subpattern names
For full details on how these modifiers work, visit the additional rxsub examples page.
Note: Backslashes must be escaped (\\
) when specifying token shorthands or $
in the interpreter (e.g. \\w
).
Required Parameters
- s: String to be searched string.
- regex: Regular expression to be matched string.
- sub: Substitution string OR function OR table.
Optional Parameters
- n: Maximum number of matches to substitute integer.
- mods: Regular expression modifiers string.
Returns
- A copy of the
s
in which matches ofregex
are replaced string.
For More Information
- The string module - string operations
- Extending the string library
- Online documentation for string.gsub
- Strings Tutorial
- Understanding Lua OO syntax: what the colon operator means
- Additional examples for rxsub
string.split
Example Usage of string:split(separator)
local s = "one two three" local items = s:split(" ") trace(items[1], items[2], items[3]) -->trace('one','two','three')
Usage
string:split(separator)
Returns a table of values in the string s
separated by the delimiter
string. If delimiter
is not found in the string, the resulting table consists of only the single value s
.
If delimiter
appears multiple times in a row, the resulting table will contain empty strings as the values in between these segments.
Required Parameters
- s: Source string to split string.
- separator: Delimiter string string.
Returns
- A table with the string values separated by the split string table.
For More Information
- The string module - string operations
- Extending the string library
- Strings Tutorial
- Understanding Lua OO syntax: what the colon operator means
string.sub
Example Usage of string:sub(i [, j])
local AString = 'Fred' local ASubString=AString:sub(1,1) -- which is equivalent to local ASubString=string.sub(AString,1,1)
Usage
string:sub(i [, j])
Returns the substring of s
that starts at i
and continues until j
; i
and j
can be negative. If j
is absent, then it is assumed to be equal to -1 (which is the same as the string length). In particular, the call string.sub(s,1,j)
returns a prefix of s
with length j
, and string.sub(s, -i)
returns a suffix of s
with length i
.
The most convenient way to invoke sub is using the method syntax like MyString:sub(1,3).
Required Parameters
- s: Source string string.
Optional Parameters
- i: Start position integer.
- j: End position integer.
Returns
- The specified substring string.
For More Information
- The string module - string operations
- Extending the string library
- Online documentation for string.sub
- Strings Tutorial
- String Library Tutorial
- String Recipes
- Patterns Tutorial
- Understanding Lua OO syntax: what the colon operator means
string.upper
Usage
string:upper()
Receives a string and returns a copy of this string with all lowercase letters changed to uppercase. All other characters are left unchanged. The definition of what a lowercase letter is depends on the current locale.
Required Parameters
- s: Source string to convert to uppercase string.
Returns
- A copy of the string with all lowercase letters changed to uppercase string.
For More Information
- The string module - string operations
- Extending the string library
- Online documentation for string.upper
- Strings Tutorial
- String Library Tutorial
- String Recipes
- Patterns Tutorial
- Understanding Lua OO syntax: what the colon operator means
table
table.concat
Example Usage of table.concat(table [, sep [, i [, j]]])
t = {'A','B','C'} result = table.concat(t) trace(result) --> 'ABC'
-- using separator and start/end t = {'junk','A','B','C','more junk'} result = table.concat(t,',',2,4) trace(result) --> 'A,B,C'
Usage
table.concat(table [, sep [, i [, j]]])
Given an array where all elements are strings or numbers, returns table[i]..sep..table[i+1] ··· sep..table[j]
. The default value for sep
is the empty string, the default for i
is 1, and the default for j
is the length of the table. If i
is greater than j
, returns the empty string.
Required Parameters
- table: Table to process table.
Optional Parameters
- sep: Position of the element to remove string.
- i: Start position integer.
- j: End position integer.
Returns
- The concatenated values from within the table string.
For More Information
table.foreach
Usage
Deprecated: use a for loop with pairs or ipairs instead.
Functions table.foreach and table.foreachi are deprecated. You can use a for loop with pairs or ipairs instead.
For More Information
table.foreachi
Usage
Deprecated: use a for loop with pairs or ipairs instead.
Functions table.foreach and table.foreachi are deprecated. You can use a for loop with pairs or ipairs instead.
For More Information
table.getn
Usage
Deprecated
Deprecated: use # operator instead. Function table.getn corresponds to the new length operator (#); use the operator instead of the function.
For More Information
table.insert
Example Usage of table.insert(table [, pos], value)
-- insert at the end of the table t = {[1]='one',[2]='two'} table.insert(t,'three') trace(t[3]) --> "three"
-- insert in the middle of the table t = {[1]='one',[2]='three'} table.insert(t,2,'two') trace(t[2]) --> "two"
Usage
table.insert(table [, pos], value)
Inserts element value
at position pos
in table
, shifting up other elements to open space, if necessary. The default value for pos
is n+1
, where n
is the length of the table, so that a call table.insert(t,x)
inserts x
at the end of table t
.
Required Parameters
- table: Table to process table.
- value: Data to insert any type.
Optional Parameters
- pos: Position to insert the element integer.
For More Information
table.maxn
Example Usage of table.maxn(table)
t = {[-10]='A',[-1]='B',[33]='C'} value = table.maxn(t) trace(value) --> 33
t = {[-10]='A',[-1]='B',[0]='C'} value = table.maxn(t) trace(value) --> 0
t = {['x']='A',['y']='B',['z']='C'} value = table.maxn(t) trace(value) --> 0
Usage
table.maxn(table)
Returns the value of the largest positive numerical index of the given table, or zero if the table has no positive numerical indices. (To do its job this function does a linear traversal of the whole table.)
Required Parameters
- table: Table to process table.
Returns
- The the largest positive numerical index of the given table, or zero if there are no positive numerical indices number.
For More Information
table.remove
Example Usage of table.remove(table [, pos])
-- remove the last element in the table t = {[1]='one',[2]='two',[3]='three'} table.remove(t) trace(t[3]) --> nil
-- remove the impostor (second element) t = {[1]='one',[2]='I am an impostor',[3]='two'} table.remove(t,2) trace(t[2]) --> "two"
Usage
table.remove(table [, pos])
Removes from table
the element at position pos
, shifting down other elements to close the space, if necessary. Returns the value of the removed element. The default value for pos
is n
, where n
is the length of the table, so that a call table.remove(t)
removes the last element of table t
.
Required Parameters
- table: Table to process table.
Optional Parameters
- pos: Position of the element to remove integer.
Returns
- The value of the removed element type varies: same as the removed element.
For More Information
table.setn
Usage
Deprecated
Deprecated.
For More Information
table.sort
Example Usage of table.sort(table [, comp])
t = {3,2,1} table.sort(t) trace(t) --> table with values {1,2,3}
Usage
table.sort(table [, comp])
Sorts table elements in a given order, in-place, from table[1] to table[n], where n is the length of the table. If comp is given, then it must be a function that receives two table elements, and returns true when the first is less than the second (so that not comp(a[i+1],a[i]) will be true after the sort). If comp is not given, then the standard Lua operator < is used instead.
Note:The sort algorithm is not stable; that is, elements considered equal by the given order may have their relative positions changed by the sort.
Required Parameters
- table: Table to sort table.
Optional Parameters
- comp: Sorting function function.
For More Information
util
util.guid
Example Usage of util.guid(Size)
local guid = util.guid(Size)
Usage
util.guid(Size)
Generate a GUID (Globally Unique ID).
Note: Size argument must be an integer of at least 128, and divisible by 8.
Required Parameters
- Size: The size of the GUID in bits integer.
Returns
- The new GUID string.
For More Information
- The util module - utility script functions
- Generate GUIDs and use these to associate records together
util.md5
Example Usage of util.md5(Data)
local md5 = util.md5(Data)
Usage
util.md5(Data)
Compute the MD5 hash of a specified string.
Required Parameters
- Data: String to be hashed string.
Returns
- The MD5 hash string.
For More Information
util.sleep
Example Usage of util.sleep(Milliseconds)
util.sleep(Milliseconds)
Usage
util.sleep(Milliseconds)
Pause the script for a specified number of milliseconds integer.
Required Parameters
- Milliseconds: Time to sleep in milliseconds integer.
For More Information
x12
x12.message
Example Usage of x12.message{vmd=<value>, name=<value>}
local Msg = x12.message{vmd='example.vmd', name='841 Claim'}
Usage
x12.message{vmd=<value>, name=<value>}
Create an empty X12 data tree to populate with data.
Required Parameters
- vmd: The name of a VMD schema file string.
- name: The name of a message definition in the specified VMD file string.
Returns
- An empty data tree representing an X12 message X12 node tree.
For More Information
- The x12 module - working with X12
- Node types for Iguana node trees
- Automatic TA1 acknowledgment to X12 messages
x12.parse
Example Usage of x12.parse{vmd=<value>, data=<value>}
local Msg = x12.parse{vmd='demo.vmd', data=Data}
Usage
x12.parse{vmd=<value>, data=<value>}
Parses an X12 message.
Required Parameters
- vmd: The name of a VMD schema file string.
- data: A string containing a message to be parsed
Returns
- The parsed message as a data tree X12 node tree.
For More Information
- The x12 module - working with X12
- Node types for Iguana node trees
- X12 Batch Processing Example
- X12 Processing One Transaction Set at a Time
xml
xml.parse
Example Usage of xml.parse{data=<value>} or xml.parse(<value>)
local Msg = xml.parse{data=Data}
Usage
xml.parse{data=<value>} or xml.parse(<value>)
Parses an XML document.
Required Parameters
- data: The XML to be parsed string.
Returns
- An XML tree containing the parsed data xml node tree.