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
These functions create and send acknowledgment (ACK) messages.
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". If you try to use it in another component it will give the following error: "attempt to index global 'ack' (a nil value)" (meaning the ack module is not available).
Required Parameters
- ack: The ACK to send string.
For More Information
chm
The chm module is provided as a convenience for Chameleon users who are switching to the Iguana Translator.
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>}
Converts an HL7 version 2.X XML string into an HL7 message (the reverse function is chm.toXml).
If you need to convert HL7 to and from the official XML formats for HL7 version 2.X this function may be useful. The style of conversion will depend on how the vmd is configured.
Note: This exposes the Chameleon XML to HL7 conversion functionality.
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 string.
Note: This XML string must conform to the HL7 XML message formats defined in the HL7 version 2 standard.
Returns
- A string populated with the HL7 message returned from the conversion. string
For More Information
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 legacy (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
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>}
Converts an HL7 message into an HL7 version 2.X XML string (the reverse function is chm.fromXml).
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.
Note: This exposes Chameleon HL7 to XML conversion functionality.
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 returned from the conversion. string
For More Information
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>, ...}
Recommended best practice: Not intended for use in production code.
Performs a legacy (Chameleon style) 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 against 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
crypto
These functions work with OpenSSL encryption. Including functions for signing, verifying, encrypting, decrypting and checking OpenSSL version etc.
crypto.aes
These functions work with AES encryption.
crypto.aes.decrypt
Example Usage of crypto.aes.decrypt{data=<data>, key=<secret>, iv=<random>, blockcipher=<blockcipher>}
local Decrypted = crypto.aes.decrypt{data=filter.hex.dec('6C0C78D1E15455FFE12316DA57CFC669'), key='1234567890123456', iv='1234567890123456', blockcipher='cbc'} trace(Decrypted) --> hello world
Usage
crypto.aes.decrypt{data=<data>, key=<secret>, iv=<random>, blockcipher=<blockcipher>}
Decrypts data generated using AES encryption. The supplied key, IV, and block-cipher mode must match what was used when encrypting the original data.
Depending on the block-cipher mode, a failure can result in either an error, or an incorrect result string (with no error).
Required Parameters
- data: The input to decrypt string or stream.
- key: The shared secret key, in binary-encoding string.
- iv: The randomly-generated initialization vector, in binary-encoding string.
- blockcipher: The AES block-cipher mode, one of: ecb, cbc, cfb, ofb, or ctr string.
Returns
- The decrypted message, in binary encoding string or stream.
crypto.aes.encrypt
Example Usage of crypto.aes.encrypt{data=<data>, key=<secret>, iv=<random>, blockcipher=<blockcipher>}
local Encrypted = crypto.aes.encrypt{data='hello world', key='1234567890123456', iv='1234567890123456', blockcipher='cbc'} local EncryptedHex = filter.hex.enc(Encrypted) trace(EncryptedHex) --> 6C0C78D1E15455FFE12316DA57CFC669
Usage
crypto.aes.encrypt{data=<data>, key=<secret>, iv=<random>, blockcipher=<blockcipher>}
Encrypts data using AES encryption. The encrypted data can only be decrypted with the same key, IV, and block-cipher mode.
The key size determines the block-size. Assuming the key is binary-encoded, the key size, in bits, correspond directly to the AES block-size, in bits. Use a key size of 16 bytes (binary characters) for AES-128, 24 bytes for AES-192, and 32 bytes for AES-256.
The initialization vector (IV) can be treated as salt. It should be randomized for each input to make it harder to detect patterns between encrypted outputs. Like salts, the IV does not need to be kept secure.
Required Parameters
- data: The input to encrypt string or stream.
- key: The shared secret key, in binary-encoding string.
- iv: The randomly-generated initialization vector, in binary-encoding string.
- blockcipher: The AES block-cipher mode, one of: ecb, cbc, cfb, ofb, or ctr string.
Returns
- The encrypted message, in binary encoding string or stream.
crypto.algorithms
Example Usage of crypto.algorithms()
local DigestAlgorithms = crypto.algorithms() local Digest = crypto.digest{data='hello', algorithm=DigestAlgorithms[1]}
Usage
crypto.algorithms()
Deprecated: Use crypto.library.digests
instead.
Requests a full list of available digest algorithms from OpenSSL. Note that digest algorithms are case-insensitive, and may appear in uppercase or lowercase.
Certain digest algorithms are not meant to be used with certain crypto methods. For example, most applications expect only "DSA-SHA" to be used when signing with a DSA private key, and may not accept anything other than "DSA-SHA" when attempting to verify the signature.
Returns
- The list of supported digest algorithms table.
For More Information
crypto.digest
Example Usage of crypto.digest{data=<data>, algorithm=<algorithm>}
local BinaryChecksum = crypto.digest{data='hello', algorithm='sha1'}
Usage
crypto.digest{data=<data>, algorithm=<algorithm>}
Computes a binary checksum of input data using a specified hashing algorithm.
Required Parameters
- data: The data to checksum string or stream.
- algorithm: The message digest algorithm to use (e.g. SHA1) string.
Returns
- The checksum of the input data in binary string.
For More Information
crypto.hmac
Example Usage of crypto.hmac{data=<data>, key=<secret>, algorithm=<algorithm>}
local BinaryHmac = crypto.hmac{data='hello', key='key', algorithm='sha1'}
Usage
crypto.hmac{data=<data>, key=<secret>, algorithm=<algorithm>}
Generates a Keyed-Hash Message Authentication code (HMAC) based on input data and a shared secret key. The HMAC can be used to verify the integrity of the data when received by a server using the same input data and the same shared secret, and comparing the results. This scheme requires that both sides (client and server) have access to the same key.
Required Parameters
- data: The input to hash string or stream.
- key: The shared secret string.
- algorithm: The hashing algorithm string.
Returns
- The keyed-hash message authentication code in binary string.
For More Information
crypto.library
These library functions identify available ciphers, versions and digests.
crypto.library.ciphers
Example Usage of crypto.library.ciphers()
local Ciphers = crypto.library.ciphers() local AES128CBCinfo = Ciphers['AES-128-CBC'] trace(AES128CBCinfo.keysize) --> 16
Usage
crypto.library.ciphers()
Fetches the list of supported/builtin OpenSSL encryption ciphers along with information about them. The resulting table uses the cipher name as keys, and maps to either another string (i.e. the current cipher name is an alias for the value), or an object containing information about the cipher.
Cipher information includes the following fields:
- nid: Internal ASN.1 object ID.
- blocksize: Size of discrete chunks used in encryption/decryption
- keysize: Size of key used in the cipher
- ivsize: Size of the initialization vector (IV) used in the cipher
WARNING: The return format is subject to change. This is meant to be used for interactive querying and debugging.
Returns
- The supported encryption ciphers, along with their associated metadata table.
crypto.library.digests
Example Usage of crypto.library.digests()
local Digests = crypto.library.digests() local MD5info = Digests['MD5'] trace(MD5info.size) --> 16
Usage
crypto.library.digests()
Fetches the list of supported/builtin OpenSSL digest algorithms along with information about them. The resulting table uses the algorithm name as keys, and maps to either another string (i.e. the current algorithm name is an alias for the value), or an object containing information about the algorithm.
Algorithm information includes the following fields:
- nid: Internal ASN.1 object ID.
- size: Digest output size
- blocksize: Size of discrete chunks used in digest computation
WARNING: The return format is subject to change. This is meant to be used for interactive querying and debugging.
Returns
- The supported digest algorithms, along with their associated metadata table.
crypto.library.version
Usage
crypto.library.version()
Fetches the version string from the builtin OpenSSL library.
Returns
- The builtin OpenSSL library version string.
crypto.pbkdf2
Example Usage of crypto.pbkdf2{password=<password>, salt=<salt>[, iterations=2048][, algorithm='sha1']}
local Key = crypto.pbkdf2{password='password', salt='12345678'} local KeyHex = filter.hex.enc(Key) trace(KeyHex) --> 647F7D6E20297DD71D1338592943185A91DA4E7548CB71C5ED0001876797536E0FAE3744616903A35E9D675E5E8F93CE85D63236FE3730123A8C940A74094924
Usage
crypto.pbkdf2{password=<password>, salt=<salt>[, iterations=2048][, algorithm='sha1']}
Derives a secure encryption key from an input password and randomized salt. The resulting key is computationally expensive to compute, and is at least as long as the digest size, so it's highly resistant to brute-force password attacks.
The same parameters (password, salt, iterations, and hash algorithm) will always result in the same output key. This makes it ideal for strenghtening a potentially insecure password and/or storing it in a database.
The salt does not need to be kept secure. It is only used as a randomization offset to make it harder to brute-force the password.
Required Parameters
- password: The password to derive the key from string.
- salt: A random, binary-encoded salt string.
Optional Parameters
- iterations: Number of calculation cycles (default = 2048) integer.
- algorithm: The message digest algorithm to use (default = SHA1) string.
Returns
- The derived key string.
crypto.rsa
These functions work with RSA encryption.
crypto.rsa.decrypt
Example Usage of crypto.rsa.decrypt{data=<data>, key=<privkey>[, keyform=<format>]}
local PrivateKey = io.open('path/to/private.pem'):read('*a') local Decrypted = crypto.rsa.decrypt{data=Encrypted, key=PrivateKey, keyform='pem'}
Usage
crypto.rsa.decrypt{data=<data>, key=<privkey>[, keyform=<format>]}
Decrypts data generated using RSA encryption. The data must have been encrypted using the public key corresponding to the input private key.
Any padding added by the encryption routine will be automatically removed before returning.
Required Parameters
- data: The input to decrypt string.
- key: The RSA private key string.
Optional Parameters
- keyform: The input key format, either pem or der (default = pem) string.
Returns
- The decrypted message, in binary encoding string.
crypto.rsa.decryptPublic
Example Usage of crypto.rsa.decryptPublic{data=<data>, key=<pubkey>[, keyform=<format>]}
local PublicKey = io.open('path/to/public.pem'):read('*a') local Decrypted = crypto.rsa.decryptPublic{data=Encrypted, key=PublicKey, keyform='pem'}
Usage
crypto.rsa.decryptPublic{data=<data>, key=<pubkey>[, keyform=<format>]}
Decrypts data generated using RSA private-key encryption. The data must have been encrypted using the private key corresponding to the input public key.
This is a lower-level primitive used to implement the higher-level "signature" of a message. When verifying a signature, this method is used to decrypt the message hash and compare it against the incoming message.
Required Parameters
- data: The input to decrypt string.
- key: The RSA public key string.
Optional Parameters
- keyform: The input key format, either pem or der (default = pem) string.
Returns
- The decrypted message, in binary encoding string.
crypto.rsa.encrypt
Example Usage of crypto.rsa.encrypt{data=<data>, key=<pubkey>[, keyform=<format>]}
local PublicKey = io.open('path/to/public.pem'):read('*a') local Encrypted = crypto.rsa.encrypt{data='hello', key=PublicKey, keyform='pem'}
Usage
crypto.rsa.encrypt{data=<data>, key=<pubkey>[, keyform=<format>]}
Encrypts data using RSA encryption. The encrypted data can only be decrypted with the corresponding RSA private key.
The key size determines the maximum size of the input data. RSA encryption supports a maximum data size equal to the RSA key size (in bytes) minus 11. For example, a 1024-bit RSA key can encrypt a maximum of 117 bytes (binary characters), while a 2048-bit RSA key can encrypt up to 245 bytes. Inputs that are shorter than the maximum are padded with standard PKCS#1 v1.5 padding.
RSA public-key encryption uses some randomized components, so each run may result in a different output. This is normal, and they will all result in the original data when decrypted with the corresponding private key.
Required Parameters
- data: The input to encrypt string.
- key: The RSA public key string.
Optional Parameters
- keyform: The input key format, either pem or der (default = pem) string.
Returns
- The encrypted message, in binary encoding string.
crypto.rsa.encryptPrivate
Example Usage of crypto.rsa.encryptPrivate{data=<data>, key=<privkey>[, keyform=<format>]}
local PrivateKey = io.open('path/to/private.pem'):read('*a') local Encrypted = crypto.rsa.encryptPrivate{data='hello', key=PrivateKey, keyform='pem'}
Usage
crypto.rsa.encryptPrivate{data=<data>, key=<privkey>[, keyform=<format>]}
Encrypts data using RSA private-key encryption. This is also known as "signing" with RSA (not to be confused with crypto.sign
).RSA private-key encryption is a low-level primitive used to implement the higher-level notion of a message signature (i.e. crypto.sign
). It is generally used on a message digest to generate the higher-level "signature" of a message.
The resulting encrypted data can only be decrypted with the corresponding public key.
Required Parameters
- data: The input to encrypt string.
- key: The RSA private key string.
Optional Parameters
- keyform: The input key format, either pem or der (default = pem) string.
Returns
- The encrypted message, in binary encoding string.
crypto.sign
Example Usage of crypto.sign{data=<data>, key=<RSA or DSA private key>, algorithm=<algorithm>}
local PrivateKey = io.open('path/to/private.pem'):read('*a') local BinarySignature = crypto.sign{data='hello', key=PrivateKey, algorithm='sha1'}
Usage
crypto.sign{data=<data>, key=<RSA or DSA private key>, algorithm=<algorithm>}
Used to sign documents with either RSA or DSA private keys. Signatures are generated with private keys and verified with public keys.
Required Parameters
- data: The data to sign string or stream.
- key: The RSA or DSA private key string.
- algorithm: The hashing algorithm string.
Optional Parameters
- keyform: The input key format, either pem or der (default = pem) string.
Returns
- The RSA or DSA digital signature in binary string.
For More Information
crypto.verify
Example Usage of crypto.verify{data=<data>, key=<RSA or DSA public key>, algorithm=<algorithm>, signature=<signature>}
local PublicKey = io.open('path/to/public.pem'):read('*a') local IsValid = crypto.verify{data='hello', key=PublicKey, algorithm='sha1', signature=Signature}
Usage
crypto.verify{data=<data>, key=<RSA or DSA public key>, algorithm=<algorithm>, signature=<signature>}
Used to verify the validity of an RSA or DSA signature. Note that verification only requires a public key.
Required Parameters
- data: The data to verify string
- algorithm: The hashing algorithm string.
- key: The RSA or DSA public key string.
- signature: The RSA or DSA digital signature string.
Optional Parameters
- keyform: The input key format, either pem or der (default = pem) string.
Returns
- Whether or not the signature is valid boolean.
For More Information
db
The db module contains the Iguana Translator script functions that interact with databases. Functions exist to create local database tables, merge them with external databases, and perform queries on external databases.
It is recommended best practice to use the new style database methods. They are easier to use and offer improved database transaction handling.
Advantages of the new style connection objects:
-
Connections are not pooled, resulting in safer transactions:
-
Create dedicated connections using
db.connect()
-
Legacy connections are pooled so it is possible (rarely) to receive a different connection and rollback a transaction
Note: If network connectivity to the database is lost, a rollback will occur with new and legacy connections
-
Create dedicated connections using
-
NEW! The ability to check a connection to confirm that the database is still available:
-
Use the
conn:check()
method to test a connection
-
Use the
Note: it is important to understand the behaviour of the live flag for db.connect and how it affects the execution the new style database methods in the Iguana editor:
- By default the connection handle returned from db.connect is live (live = true).
- If db.connect live = true (the default) connection methods will run in the editor (based on their default or live setting).
- If db.connnect live = false it means that all database operations are always non-live.
For more information on how Iguana Translator scripts work with databases, see our Database Documentation.
The db page below describes the old style database functions. Functions exist to create local database tables, merge them with external databases, and perform queries on external databases.
Every function in the db namespace in Translator scripts now accepts a "use_unicode" flag that allows you to control whether or not database connections from Iguana are configured to use Unicode. This flag may be necessary if you are dealing with information that contains international characters.
The "use_unicode" flag is set to false by default in order to maintain backwards compatibility with older versions of Iguana 5.0.x
Database codes used for supported databases
Supported Database | Database code to use with the api parameter |
My SQL | db.MY_SQL |
Oracle OCI | db.ORACLE_OCI |
Oracle ODBC | db.ORACLE_ODBC |
SQL Lite | db.SQLITE |
Microsoft SQL Server | db.SQL_SERVER |
Postgres | db.POSTGRES |
DB2 | db.DB2 |
Informix | db.INFORMIX |
Interbase | db.INTERBASE |
Filemaker | db.FILEMAKER |
Sybase ASA | db.SYBASE_ASA |
Sybase ASE | db.SYBASE_ASE |
MS Access | db.ACCESS |
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 = true) boolean.
- use_unicode: If true, Unicode will be used when communicating with the database (default = false) boolean.
- timeout: Maximum time in seconds allowed for the query (0 for infinite) integer.
Note: Timeout is supported only for ODBC based connections (default = 5 minutes).
For More Information
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 = true) boolean.
- use_unicode: If true, Unicode will be used when communicating with the database (default = false) boolean.
- timeout: Maximum time in seconds allowed for the query (0 for infinite) integer.
Note: Timeout is supported only for ODBC based connections (default = 5 minutes).
For More Information
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 = true) boolean.
- use_unicode: If true, Unicode will be used when communicating with the database (default = false) boolean.
- timeout: Maximum time in seconds allowed for the query (0 for infinite) integer.
Note: Timeout is supported only for ODBC based connections (default = 5 minutes).
For More Information
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 (default = true) boolean
- use_unicode: if true, Unicode will be used when communicating with the database (default = false) boolean.
- timeout: maximum time in seconds allowed for the query (0 for infinite). integer.
Note: Timeout is supported only for ODBC based connections (default = 5 minutes).
Returns
- A new database connection handle db_connection object.
For More Information
db.db_connection
This page describes the new "connection" style database methods. Methods exist to create local database tables, merge them with external databases, and perform queries on external databases.
Note: first use db.connect
function to create the connection object - then use the methods on the connection object.
For more information on how Iguana Translator scripts work with databases, see our Database Documentation.
In Iguana 5.0.14 a bug was fixed when 0 or "" (empty string) was returned from a database as a NULL value - now 0 and "" are returned correctly.
Database codes used for supported databases
Supported Database | Database code to use with the api parameter |
My SQL | db.MY_SQL |
Oracle OCI | db.ORACLE_OCI |
Oracle ODBC | db.ORACLE_ODBC |
SQL Lite | db.SQLITE |
Microsoft SQL Server | db.SQL_SERVER |
Postgres | db.POSTGRES |
DB2 | db.DB2 |
Informix | db.INFORMIX |
Interbase | db.INTERBASE |
Filemaker | db.FILEMAKER |
Sybase ASA | db.SYBASE_ASA |
Sybase ASE | db.SYBASE_ASE |
MS Access | db.ACCESS |
db.db_connection.begin
Example Usage of conn:begin{[live=true|false]}
local conn = db.connect{ api=db.MY_SQL, name='test@localhost', user='root', password='secret' } conn:begin{}
Usage
conn:begin{[live=true|false]}
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 = true) boolean.
For More Information
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
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
db.db_connection.commit
Example Usage of conn:commit{[live=true|false]}
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=true|false]}
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 = true) boolean.
For More Information
db.db_connection.execute
Example Usage of conn:execute{sql=<value> [, live=true|false]} 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=true|false]} 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 = 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
- db conn execute{} - Writing to a Database
- See our Database documentation
- 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
db.db_connection.merge
Example Usage of conn:merge{data=<value> [, bulk_insert=true|false] [, ...]} or conn:merge(data)
conn:merge{ data=Out, bulk_insert=true, transaction=false }
Usage
conn:merge{data=<value> [, bulk_insert=true|false] [, ...]} 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 (default = false) boolean.
- transaction: set to false to disable inserting/updating all rows as a transaction (default = true) boolean.
- live: if true, the merge will be executed in the editor (default = false) boolean.
For More Information
db.db_connection.query
Example Usage of conn:query{sql=<value> [, live=true|false]} 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=true|false]} 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 = true) boolean.
Returns
- The first result set result_set node tree.
- An array containing all the result sets table.
For More Information
- See our Database documentation
- 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
db.db_connection.rollback
Example Usage of conn:rollback{[live=true|false]}
conn:rollback{}
Usage
conn:rollback{[live=true|false]}
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 = true) boolean.
For More Information
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 = false) boolean.
- use_unicode: If true, Unicode will be used when communicating with the database (default = false) boolean.
- timeout: Maximum time in seconds allowed for the query (0 for infinite) integer.
Note: Timeout is supported only for ODBC based connections (default = 5 minutes).
Returns
- For queries: the first result set result_set node tree.
- An array containing all the result sets table.
For More Information
- db conn execute{} - Writing to a Database (
db.execute
return values and error handling work in the same way) - See our Database documentation
- 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 (default = false) boolean.
- transaction: Set to false to disable inserting/updating all rows as a transaction (default = true) boolean.
- live: If true, the merge will be executed in the editor (default = false) boolean.
- use_unicode: If true, Unicode will be used when communicating with the database (default = false) boolean.
- timeout: Maximum time in seconds allowed for the query (0 for infinite) integer.
Note: Timeout is supported only for ODBC based connections (default = 5 minutes).
For More Information
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 = true) boolean.
- use_unicode: If true, Unicode will be used when communicating with the database (default = false) boolean.
- timeout: Maximum time in seconds allowed for the query (0 for infinite) integer.
Note: Timeout is supported only for ODBC based connections (default = 5 minutes).
Returns
- The first result set result_set node tree.
- An array containing all the result sets table.
For More Information
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 = true) boolean.
- use_unicode: If true, Unicode will be used when communicating with the database (default = false) boolean.
- timeout: Maximum time in seconds allowed for the query (0 for infinite) integer.
Note: Timeout is supported only for ODBC based connections (default = 5 minutes).
For More Information
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
dbs
The dbs module contains class for loading dababase schema in dbs format.
dbs.dbs_cache
First use dbs.init
function to create the dbs object before main() and then use the tables method on the object from main().
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
The debug module exposes the native Lua debugging functions.
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
- 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
- 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
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
- 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
- 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
- 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
- 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
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
- 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
- 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
These functions perform various types of encoding, compression and encryption.
For more information on how these to use these functions with streams of data, see Streaming and Filtering Data.
Note: they are implemented in C and are about 300 times faster than equivalent logic in Lua.
filter.aes
Encrypt and decrypt data using AES encryption.
Note: Both filter.aes.enc and filter.aes.dec meet the NIST standard (FIPS PUB 197).
Recommended Best Practice
The output produced by the aes function is essentially a binary string. As such, we recommend that you include an encoding/decoding function as part of your script so that your encrypted messages transmit and decrypt correctly:
- Apply an encoding step before transmitting the results of aes.filter.enc function calls.
- Apply a decoding step before applying the aes.filter.dec function to incoming encrypted messages.
There are several encoding/decoding functions available to you:
- filter.base64
- filter.uuencode
- filter.hex
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
Encode and decode Base64 data.
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
Compress and decompress BZIP2 data.
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
Compress and decompress GZIP data.
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
Encode and decode Hex (Base16) data.
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
Encode text for 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
Encode and decode URI component text.
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
Encode and decode data for a Unix to Unix transfer (uuencode).
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 (default = 644) integer.
For More Information
filter.zip
Compress and decompress zip data.
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 (directories may be nested) table.
Returns
- A binary string containing the compressed zip data string.
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.
The decompressed file contents are returned in an hierarchical structure reflecting the directory structure within the ZIP file. Directory and file names are represented as table keys and data as table values.
Required Parameters
- data: The string (or stream) to decompress string or stream.
Returns
- A table containing the directory hierarchy from a decompressed string (or stream) table.
For More Information
global
These are the global functions defined in the global namespace of Lua, like print etc.
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.
Tuning of the garbage collection parameters should be undertaken with caution. You will need to experiment until you find out what works best for your circumstances (which may also vary from program to program).
The garbage-collector pause controls how long the collector waits before starting a new cycle. Larger values make the collector less aggressive. Values smaller than 100 mean the collector will not wait to start a new cycle. The default value of 200 means that the collector waits for the total memory in use to double before starting a new cycle.
The step multiplier controls the relative speed of the collector relative to memory allocation. Larger values make the collector more aggressive but also increase the size of each incremental step. Values smaller than 100 make the collector too slow and may result in the collector never finishing a cycle (which can slow down or freeze a program). The default value of 200 means that the collector runs at “twice” the speed of memory allocation.
Note: Use collectgarbage("count")
instead of the the deprecated gcinfo()
function.
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.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
- 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
- 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.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 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 [, ...])
Deprecated: Use the recommended module structure instead. The module
function is deprecated in Lua 5.2 and will be removed in 5.3.
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.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.
Remember that 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.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.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
- 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
- table: Name of table string.
- index: Index for table any type.
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.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
- 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
- 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.
Note: The builtin node.S()
function is equivalent to tostring()
.
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
The help module allows you to add help for your own library code.
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.
- See the Store module in the Tools repository.
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.
- See the Store module in the Tools repository.
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
These functions use VMD files built using Chameleon to parse and generate version 2.x HL7 messages.
For more information on how to use scripts to process HL7 messages, see our Documentation for working with 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
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
- Documentation for working with HL7
- Using the Warnings returned from hl7.parse{}
- Node types for Iguana node trees
iconv
These functions convert characters between Unicode and other (country specific) encodings.
iconv.aliases
Example Usage of iconv.aliases(encoding)
local ASCIIaliases = iconv.aliases("ascii") trace(ASCIIaliases[3], ASCIIaliases[9]) --> 'ASCII', 'US'
Usage
iconv.aliases(encoding)
Returns a list of aliases for a supplied encoding.
Aliases are simply different names for the same underlying encoding. Passing in a different alias of an encoding to iconv.convert
does not change the result of the conversion.
Required Parameters
- encoding: The name of the encoding string.
Returns
- A list of aliases for the supplied encoding table.
For More Information
iconv.ascii
These functions convert characters between ascii and Unicode (UTF-8).
iconv.ascii.dec
Example Usage of iconv.ascii.dec(data)
local Utf8Data = iconv.ascii.dec("Hello") trace(Utf8Data) --> Hello
Usage
iconv.ascii.dec(data)
Convert the character encoding of the supplied data from ASCII to UTF-8.
Required Parameters
- data: The string or stream in ASCII encoding. string or stream.
Returns
- A string (or stream) re-encoded in UTF-8 string or stream.
For More Information
iconv.ascii.enc
Example Usage of iconv.ascii.enc(data)
local AsciiData = iconv.ascii.enc("Hello") trace(AsciiData) --> Hello
Usage
iconv.ascii.enc(data)
Convert the character encoding of the supplied data from UTF-8 to ASCII.
Required Parameters
- data: The string or stream in UTF-8 encoding. string or stream.
Returns
- A string (or stream) re-encoded in ASCII string or stream.
For More Information
iconv.convert
Example Usage of iconv.convert(data, from, to)
local Utf8Data = iconv.convert("Here is an inverted exclamation mark in ISO 8859-9: \161", "ISO-8859-9", "UTF-8") trace(Utf8Data) --> Here is an inverted exclamation mark in ISO 8859-9: ¡
local s = iconv.convert("It is 15°C outside today", "UTF-8", "ASCII//TRANSLIT") trace(s) --> It is 15^0C outside today
Usage
iconv.convert(data, from, to)
Convert the character encoding of the supplied data from a variety of encodings to another encoding.
In addition to any of the available encodings, appending "//TRANSLIT" or "//IGNORE" to the target encoding name activates transliteration mode and ignore mode, respectively. During conversion, if a character cannot be represented in the target encoding, transliteration is attempted in transliteration mode, or the character is simply skipped in ignore mode. Transliteration attempts to approximate the original character in the target encoding with characters that are visually similar to the offending character.
Required Parameters
- data: The string or stream in the original encoding. string or stream.
- from: The name of the original encoding string.
- to: The name of the target encoding string.
Returns
- A string (or stream) re-encoded in the target encoding string or stream.
For More Information
iconv.cp1252
These functions convert characters between cp1252 and Unicode (UTF-8).
iconv.cp1252.dec
Example Usage of iconv.cp1252.dec(data)
local Utf8Data = iconv.cp1252.dec("\128") trace(Utf8Data) --> €
Usage
iconv.cp1252.dec(data)
Convert the character encoding of the supplied data from CP1252 to UTF-8.
Required Parameters
- data: The string or stream in CP1252 encoding. string or stream.
Returns
- A string (or stream) re-encoded in UTF-8 string or stream.
For More Information
iconv.cp1252.enc
Example Usage of iconv.cp1252.enc(data)
local Cp1252Data = iconv.cp1252.enc("€") trace(Cp1252Data) --> \128
Usage
iconv.cp1252.enc(data)
Convert the character encoding of the supplied data from UTF-8 to CP1252.
Required Parameters
- data: The string or stream in UTF-8 encoding. string or stream.
Returns
- A string (or stream) re-encoded in CP1252 string or stream.
For More Information
iconv.iso8859_1
These functions convert characters between iso8859_1 and Unicode (UTF-8).
iconv.iso8859_1.dec
Example Usage of iconv.iso8859_1.dec(data)
local Utf8Data = iconv.iso8859_1.dec("\177") trace(Utf8Data) --> ±
Usage
iconv.iso8859_1.dec(data)
Convert the character encoding of the supplied data from ISO 8859-1 to UTF-8.
Required Parameters
- data: The string or stream in ISO 8859-1 encoding. string or stream.
Returns
- A string (or stream) re-encoded in UTF-8 string or stream.
For More Information
iconv.iso8859_1.enc
Example Usage of iconv.iso8859_1.enc(data)
local Iso8859_1Data = iconv.iso8859_1.enc("±") trace(Iso8859_1Data) --> \177
Usage
iconv.iso8859_1.enc(data)
Convert the character encoding of the supplied data from UTF-8 to ISO 8859-1.
Required Parameters
- data: The string or stream in UTF-8 encoding. string or stream.
Returns
- A string (or stream) re-encoded in ISO 8859-1 string or stream.
For More Information
iconv.list
Example Usage of iconv.list()
local AllEncodings = iconv.list() local ASCIIaliases = AllEncodings[1] trace(ASCIIaliases[3], ASCIIaliases[9]) --> 'ASCII', 'US'
Usage
iconv.list()
Returns a list of all character encodings understood by iconv.
The returned table is only useful for debugging purposes. To check whether or not a particular encoding is available, iconv.supported
should be used.
Returns
- A table containing aliases for each encoding available table.
For More Information
iconv.supported
Example Usage of iconv.supported(encoding)
iconv.supported("utf8") --> true
iconv.supported("hello") --> false
Usage
iconv.supported(encoding)
Returns a boolean representing whether or not a requested encoding is supported by the iconv library.
Note: Although an encoding may be supported by the iconv library, it does not necessarily mean that it can be freely converted to or from any other encoding. Conversion between two supported encodings may still fail if there are characters that cannot be represented in the target encoding.
Required Parameters
- encoding: The name of the encoding string.
Returns
- Whether or not the encoding is supported boolean.
For More Information
iguana
Various advanced functions to to enable scripts to interact with Iguana's run-time system. From the basic, "Am I running in the editor?" and "What channel is this?", to custom logging and feedback, to controlling how errors are handled and how long your script can run.
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=<value> OR name=<value>}
--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=<value> OR name=<value>}
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 configuration to fetch string.
Returns
- The channel configuration as XML string.
For More Information
iguana.channelDesc
Example Usage of iguana.channelDesc()
local name = iguana.channelDesc()
Usage
iguana.channelDesc()
Get the name of the channel running the script.
Returns
- the current channel description 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 code for test or production
- Prevent code from running in the editor
- Prevent code from running in a live channel
- Faster Editor code execution
- Using isTest() to prevent accidentally updating live data
- Building a custom GUI to configure a template
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
- Get the current message ID
- Programmatically reading Iguana log entries from Lua
- Understanding the Iguana Message Queue
iguana.project
Functions to retrieve Iguana project related information.
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.
For More Information
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.
For More Information
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.
For More Information
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
- Set channel dashboard status
- The Retry module in the Tools repository
- Schedule Channel Run in the Tools repository
- Retrying unreliable external resources
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
- Set channel timeout
- Modify the behaviour of code for test or production
- Faster Editor code execution
- Set channel timeout
iguana.status
Example Usage of local Xml = iguana.status()
local Xml = iguana.status() local S = xml.parse{data=Xml}
Usage
local Xml = iguana.status()
Returns an XML summary of Iguana's runtime state (the same as that returned by the web api /monitor_query
).
This function is quite handy since it's much easier to use than the equivalent web api call.
Returns
- A string containing the XML summary of the channel status.
For More Information
- monitor_query - Retrieve Iguana Performance Statistics
- Get Iguana runtime status
- Set channel dashboard status
- Control Panel > Status
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.
Note: This refers to a program error not a logged error, so calling iguana.logError()
will not stop the channel, however calling error()
will stop the channel.
Required Parameters
- stop: If false, errors will not stop the channel (default = true) 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()
Returns a table containing the local Iguana web server and HTTP channel server configuration.
This is helpful for scripts that access the Iguana web API (because you can find the right ports etc. programatically).
Returns
- A Lua table containing the data.
For More Information
- Get Iguana web server configuration
- Load and Save a File
- Read a directory
- Control Panel > Web Server
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
The io module contains all usual file operations. It also includes popen
which can run a program and read/write data from it.
Note: Operations are available as functions io.read()
and as methods on a file object file:read()
.
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
- File and FTP interfaces with Iguana.
- Load and Save a File.
- Streaming File Operations.
- Read from a file.
- Online documentation for io.close.
io.filehandle
This page describes all the file:
methods for the file object.
Note: First use the io.open()
function to create the file handle object, then use the methods on the file handle.
io.filehandle.close
Example Usage of file:close()
-- close "myFile"
myFile:close()
Usage
file:close()
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
- File and FTP interfaces with Iguana.
- Load and Save a File.
- Streaming File Operations.
- Read from a file.
- 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
- File and FTP interfaces with Iguana.
- Write to a file.
- 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
- File and FTP interfaces with Iguana.
- Load and Save a File.
- Streaming File Operations.
- Read from a file.
- 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
- File and FTP interfaces with Iguana.
- Streaming File Operations.
- Create a SQLite database and tables.
- 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
- 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
- size: Size of buffer.
- mode: Buffering mode.
For More Information
- 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
- File and FTP interfaces with the translator.
- Documenting an HL7 interface.
- 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
- File and FTP interfaces with Iguana.
- Create a SQLite database and tables.
- 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
- File and FTP interfaces with Iguana.
- Load and Save a File.
- Streaming File Operations.
- Read from a file.
- Online documentation for io.lines.
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
- File and FTP interfaces with Iguana.
- Load and Save a File.
- Streaming File Operations.
- Read from a file.
- 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
- File and FTP interfaces with Iguana.
- Documenting an HL7 interface.
- 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 . - 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
- File and FTP interfaces with Iguana.
- Streaming File Operations.
- Create a SQLite database and tables.
- 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
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
- File and FTP interfaces with Iguana.
- Documenting an HL7 interface.
- Online documentation for io.write.
json
The json module contains all functions that handle JSON data.
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
- Using JSON in the translator
- Serializing as JSON
- Parse and serialize 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
- Using JSON in the translator
- Serializing as JSON
- Parse and serialize JSON
- Dehydrate (serialize) 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 (default = false) boolean.
- alphasort: Sort table keys alphabetically if true (default = false) boolean.
Returns
- The Lua table serialized as JSON string.
For More Information
- Using JSON in the translator
- Serializing as JSON
- Parse and serialize JSON
- Dehydrate (serialize) as JSON
math
The math module contains all the mathematical operations.
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
All the functions relating to various network operations.
net.ftp
Using ftp file transfer operations.
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 ftp server specified by the FtpConn connection handle.
Note: Use net.ftp.init{}
to create a connection handle.
Required Parameters
- 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 (default = 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
- Read from FTP site in the in the Iguana Files repository
- Using ftp
- 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 specified by the FtpConn connection handle.
Note: Use net.ftp.init{}
to create a connection handle.
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
- 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 (default = false) boolean.
- debug: When true return verbose debug information, errors thrown will also contain debug information (default = 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
- Read from FTP site in the in the Iguana Files repository
- Using ftp
- 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 (default = 21) integer.
- timeout: Timeout for operations (default = 15 seconds) integer.
- live: Enable write operations (put, rename, delete) while in the editor (default = false) 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 (default = false) boolean.
- no_epsv: Passive mode: do not try EPSV before PASV, just use PASV (default = false) boolean.
- skip_pasv_ip: Passive mode: ignore the IP address sent by the server; instead open the new port on the same machine (default = false) boolean.
- use_pret: Send a non-standard PRET command before PASV or EPSV (default = false) 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. Valid options: 'all' (always enable), 'try' (optional), 'control' (control connection) (default = 'try') 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(s). Possible values are ssl-v3, tls-v1, tls-v1.1, tls-v1.2. Default behaviour is to try tls-v1.2 then tls-v1.1. ssl-v2 is no longer supported and ssl-v3 won't be used unless specified. Specifying tls-v1 will allow connections to use all tls versions (starting with tls-v1.2 down to tls-v1.0).string.
- cipher_list: Provide a list of ciphers in OpenSSL format to use. By default Iguana uses a list selected for optimal security. string
Returns
- a connection object table.
For More Information
- Using File and FTP Interfaces
- Read from FTP site in the in the Iguana Files repository
- Using ftp
- 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 on the ftp server specified by the FtpConn connection handle.
Note: Use net.ftp.init{}
to create a connection handle.
Required Parameters
- 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 (default = false) boolean.
Returns
- An array of {filename, is_retrievable} values table
- Debug information (if requested) string.
For More Information
- Using File and FTP Interfaces
- Read from FTP site in the in the Iguana Files repository
- Using ftp
- Using the ftp list command
- 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
-- use the 'live' parameter to upload files in the editor (for testing)
-- 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 server specified by the FtpConn connection handle.
Note: Use net.ftp.init{}
to create a connection handle.
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
- 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 (default = false) 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 (default = 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
- Read from FTP site in the in the Iguana Files repository
- Using ftp
- 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 specified by the FtpConn connection handle.
Note: Use net.ftp.init{}
to create a connection handle.
Required Parameters
- 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 (default = 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
- Read from FTP site in the in the Iguana Files repository
- Using ftp
- Wikipedia: File Transfer Protocols (ftp)
- Understanding Lua OO syntax: what the colon operator means
net.ftps
Using ftps file transfer operations.
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 (or files) from the ftp server specified by the FtpConn connection handle.
Note: Use net.ftps.init{}
to create a connection handle.
Required Parameters
- 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 (default = 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
- Read from FTP site in the in the Iguana Files repository
- Using ftp
- Using the ftp list command
- 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 serverftp server specified by the FtpConn connection handle.
Note: Use net.ftps.init{}
to create a connection handle.
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
- 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 (default = false) boolean.
- debug: When true return verbose debug information, errors thrown will also contain debug information (default = 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
- Read from FTP site in the in the Iguana Files repository
- Using ftp
- Using the ftp list command
- 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 (default = 22) integer.
- timeout: Timeout for operations (default = 15 seconds) integer.
- live: Enable write operations (put, rename, delete) while in the editor (default = false) 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 (default = false) boolean.
- no_epsv: Passive mode: do not try EPSV before PASV, just use PASV (default = false) boolean.
- skip_pasv_ip: Passive mode: ignore the IP address sent by the server; instead open the new port on the same machine (default = false) boolean.
- use_pret: Send a non-standard PRET command before PASV or EPSV (default = false) 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(s). Possible values are ssl-v3, tls-v1, tls-v1.1, tls-v1.2. Default behaviour is to try tls-v1.2 then tls-v1.1. ssl-v2 is no longer supported and ssl-v3 won't be used unless specified. Specifying tls-v1 will allow connections to use all tls versions (starting with tls-v1.2 down to tls-v1.0).string.
- cipher_list: Provide a list of ciphers in OpenSSL format to use. By default Iguana uses a list selected for optimal security. 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
- Read from FTP site in the in the Iguana Files repository
- Using ftp
- Using the ftp list command
- 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 on the ftp server specified by the FtpConn connection handle.
Note: Use net.ftps.init{}
to create a connection handle.
Required Parameters
- 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 (default = false) boolean.
Returns
- An array of {filename, is_retrievable} values table.
- Debug information (if requested) string.
For More Information
- Using File and FTP Interfaces
- Read from FTP site in the in the Iguana Files repository
- Using ftp
- Using the ftp list command
- 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 ftp server specified by the FtpConn connection handle.
Note: Use net.ftps.init{}
to create a connection handle.
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
- 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 (default = false) 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 (default = 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
- Read from FTP site in the in the Iguana Files repository
- Using ftp
- Using the ftp list command
- 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 ftp server specified by the FtpConn connection handle.
Note: Use net.ftps.init{}
to create a connection handle.
Required Parameters
- 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 (default = 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
- Read from FTP site in the in the Iguana Files repository
- Using ftp
- Using the ftp list command
- Wikipedia: File Transfer Protocols (ftp)
- Understanding Lua OO syntax: what the colon operator means
net.http
Using http connections.
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.
For More Information
- Connecting to web services
- HTTP basic authentication
- Web Services FAQs
- Web Services documentation
- Connecting to Highrise CRM using Web Services
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 = 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 (default = 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(s). Possible values are ssl-v3, tls-v1, tls-v1.1, tls-v1.2. Default behaviour is to try tls-v1.2 then tls-v1.1. ssl-v2 is no longer supported and ssl-v3 won't be used unless specified. Specifying tls-v1 will allow connections to use all tls versions (starting with tls-v1.2 down to tls-v1.0).
- cipher_list : Provide a list of ciphers in OpenSSL format to use. By default Iguana uses a list selected for optimal security.
- cache_connection_by_host: When true, re-use the HTTP connection for subsequent requests to the same host. When false, re-use the connection for subsequent requests to the same URL, including the path but not including the query string. (default = true) boolean.
- debug: When true return verbose debug information - errors thrown will also contain debug information (default = false) boolean.
- live: When true, requests are sent while in the editor (default = false) boolean.
Returns
- Response data string.
- Response code integer.
- Response headers table.
For More Information
- Connecting to web services
- HTTP basic authentication
- Web Services FAQs
- Web Services documentation
- Connecting to Highrise CRM using Web Services
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 = 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 (default = 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(s). Possible values are ssl-v3, tls-v1, tls-v1.1, tls-v1.2. Default behaviour is to try tls-v1.2 then tls-v1.1. ssl-v2 is no longer supported and ssl-v3 won't be used unless specified. Specifying tls-v1 will allow connections to use all tls versions (starting with tls-v1.2 down to tls-v1.0).
- cipher_list : Provide a list of ciphers in OpenSSL format to use. By default Iguana uses a list selected for optimal security.
- cache_connection_by_host: When true, re-use the HTTP connection for subsequent requests to the same host. When false, re-use the connection for subsequent requests to the same URL, including the path but not including the query string. (default = true) boolean.
- live: When true, requests are sent while in the editor (default = false) boolean.
- debug: When true return verbose debug information - errors thrown will also contain debug information (default = false) boolean.
Returns
- Response data string.
- Response code integer.
- Response headers table.
For More Information
- Connecting to web services
- HTTP basic authentication
- Web Services FAQs
- Web Services documentation
- Connecting to Highrise CRM using Web Services
net.http.head
Example Usage of net.http.head{url=<value> [, timeout=<value>] [, ...]} or net.http.head(<value>)
local Results = net.http.head{url='http://www.interfaceware.com', parameters={key='value'}}
Usage
net.http.head{url=<value> [, timeout=<value>] [, ...]} or net.http.head(<value>)
Fetches data from an HTTP address using the HEAD method. (Behaves like net.http.get.)
Required Parameters
- url: The URL to fetch data from string.
Optional Parameters
- timeout: Timeout for the operation (default = 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.
- 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(s). Possible values are ssl-v3, tls-v1, tls-v1.1, tls-v1.2. Default behaviour is to try tls-v1.2 then tls-v1.1. ssl-v2 is no longer supported and ssl-v3 won't be used unless specified. Specifying tls-v1 will allow connections to use all tls versions (starting with tls-v1.2 down to tls-v1.0).
- cipher_list : Provide a list of ciphers in OpenSSL format to use. By default Iguana uses a list selected for optimal security.
- cache_connection_by_host: When true, re-use the HTTP connection for subsequent requests to the same host. When false, re-use the connection for subsequent requests to the same URL, including the path but not including the query string. (default = true) boolean.
- debug: When true return verbose debug information - errors thrown will also contain debug information (default = false) boolean.
- live: When true, requests are sent while in the editor (default = false) boolean.
Returns
- Response data string.
- Response code integer.
- Response headers table.
For More Information
- Connecting to web services
- HTTP basic authentication
- Web Services FAQs
- Web Services documentation
- Connecting to Highrise CRM using Web Services
net.http.options
Example Usage of net.http.options{url=<value> [, timeout=<value>] [, ...]} or net.http.options(<value>)
local Results = net.http.options{url='http://www.interfaceware.com', parameters={key='value'}}
Usage
net.http.options{url=<value> [, timeout=<value>] [, ...]} or net.http.options(<value>)
Fetches data from an HTTP address using the OPTIONS method. (Behaves like net.http.get.)
Required Parameters
- url: The URL to fetch data from string.
Optional Parameters
- timeout: Timeout for the operation (default = 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.
- 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(s). Possible values are ssl-v3, tls-v1, tls-v1.1, tls-v1.2. Default behaviour is to try tls-v1.2 then tls-v1.1. ssl-v2 is no longer supported and ssl-v3 won't be used unless specified. Specifying tls-v1 will allow connections to use all tls versions (starting with tls-v1.2 down to tls-v1.0).
- cipher_list : Provide a list of ciphers in OpenSSL format to use. By default Iguana uses a list selected for optimal security.
- cache_connection_by_host: When true, re-use the HTTP connection for subsequent requests to the same host. When false, re-use the connection for subsequent requests to the same URL, including the path but not including the query string. (default = true) boolean.
- debug: When true return verbose debug information - errors thrown will also contain debug information (default = false) boolean.
- live: When true, requests are sent while in the editor (default = false) boolean.
Returns
- Response data string.
- Response code integer.
- Response headers table.
For More Information
- Connecting to web services
- HTTP basic authentication
- Web Services FAQs
- Web Services documentation
- Connecting to Highrise CRM using Web Services
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
- Connecting to web services
- HTTP basic authentication
- Web Services FAQs
- Web Services documentation
- Connecting to Highrise CRM using Web Services
net.http.patch
Example Usage of net.http.patch{url=<value> [, timeout=<value>] [, ...]}
local Results = net.http.patch{url='http://www.interfaceware.com/not-real-example', data='I need a consult!'}
Usage
net.http.patch{url=<value> [, timeout=<value>] [, ...]}
Uploads data to an HTTP address using the PATCH method. (Behaves like net.http.put.)
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 = 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.
- {['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.
- 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(s). Possible values are ssl-v3, tls-v1, tls-v1.1, tls-v1.2. Default behaviour is to try tls-v1.2 then tls-v1.1. ssl-v2 is no longer supported and ssl-v3 won't be used unless specified. Specifying tls-v1 will allow connections to use all tls versions (starting with tls-v1.2 down to tls-v1.0).
- cipher_list : Provide a list of ciphers in OpenSSL format to use. By default Iguana uses a list selected for optimal security.
- cache_connection_by_host: When true, re-use the HTTP connection for subsequent requests to the same host. When false, re-use the connection for subsequent requests to the same URL, including the path but not including the query string. (default = true) boolean.
- debug: When true return verbose debug information - errors thrown will also contain debug information (default = false) boolean.
- live: When true, requests are sent while in the editor (default = false) boolean.
Returns
- Response data string.
- Response code integer.
- Response headers table.
For More Information
- Connecting to web services
- HTTP basic authentication
- Web Services FAQs
- Web Services documentation
- Connecting to Highrise CRM using Web Services
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 = 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 (default = 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(s). Possible values are ssl-v3, tls-v1, tls-v1.1, tls-v1.2. Default behaviour is to try tls-v1.2 then tls-v1.1. ssl-v2 is no longer supported and ssl-v3 won't be used unless specified. Specifying tls-v1 will allow connections to use all tls versions (starting with tls-v1.2 down to tls-v1.0).
- cipher_list : Provide a list of ciphers in OpenSSL format to use. By default Iguana uses a list selected for optimal security.
- cache_connection_by_host: When true, re-use the HTTP connection for subsequent requests to the same host. When false, re-use the connection for subsequent requests to the same URL, including the path but not including the query string. (default = true) boolean.
- debug: When true return verbose debug information - errors thrown will also contain debug information (default = false) boolean.
- live: When true, requests are sent while in the editor (default = false) boolean.
Returns
- Response data string.
- Response code integer.
- Response headers table.
For More Information
- Connecting to web services
- HTTP basic authentication
- Web Services FAQs
- Web Services documentation
- 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 = 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 (default = 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(s). Possible values are ssl-v3, tls-v1, tls-v1.1, tls-v1.2. Default behaviour is to try tls-v1.2 then tls-v1.1. ssl-v2 is no longer supported and ssl-v3 won't be used unless specified. Specifying tls-v1 will allow connections to use all tls versions (starting with tls-v1.2 down to tls-v1.0).
- cipher_list : Provide a list of ciphers in OpenSSL format to use. By default Iguana uses a list selected for optimal security.
- cache_connection_by_host: When true, re-use the HTTP connection for subsequent requests to the same host. When false, re-use the connection for subsequent requests to the same URL, including the path but not including the query string. (default = true) boolean.
- debug: When true return verbose debug information - errors thrown will also contain debug information (default = false) boolean.
- live: When true, requests are sent while in the editor (default = false) boolean.
Returns
- Response data string.
- Response code integer.
- Response headers table.
For More Information
- Connecting to web services
- HTTP basic authentication
- Web Services FAQs
- Web Services documentation
- Connecting to Highrise CRM using Web Services
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 (default = 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 (default = 'text/html') string.
- use_gzip: Use gzip compression (if request supports it) (default = true) boolean.
- persist: Include a header in the response to persist the connection (if request supports it) (default = true) boolean.
- cache_connection_by_host: When true, re-use the HTTP connection for subsequent requests to the same host. When false, re-use the connection for subsequent requests to the same URL, including the path but not including the query string. (default = true) boolean.
- debug_result: Return the response sent as a string for debug purposes (default = true) boolean.
Returns
- The result data or empty string (depending on debug_result parameter) string.
For More Information
- Connecting to web services
- HTTP basic authentication
- Web Services FAQs
- Web Services documentation
- Connecting to Highrise CRM using Web Services
net.http.trace
Example Usage of net.http.trace{url=<value> [, timeout=<value>] [, ...]} or net.http.trace(<value>)
local Results = net.http.trace{url='http://www.interfaceware.com', parameters={key='value'}}
Usage
net.http.trace{url=<value> [, timeout=<value>] [, ...]} or net.http.trace(<value>)
Fetches data from an HTTP address using the TRACE method. (Behaves like net.http.post.)
Required Parameters
- url: The URL to fetch data from string.
Optional Parameters
- timeout: Timeout for the operation (default = 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.
- 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(s). Possible values are ssl-v3, tls-v1, tls-v1.1, tls-v1.2. Default behaviour is to try tls-v1.2 then tls-v1.1. ssl-v2 is no longer supported and ssl-v3 won't be used unless specified. Specifying tls-v1 will allow connections to use all tls versions (starting with tls-v1.2 down to tls-v1.0).
- cipher_list : Provide a list of ciphers in OpenSSL format to use. By default Iguana uses a list selected for optimal security.
- cache_connection_by_host: When true, re-use the HTTP connection for subsequent requests to the same host. When false, re-use the connection for subsequent requests to the same URL, including the path but not including the query string. (default = true) boolean.
- debug: When true return verbose debug information - errors thrown will also contain debug information (default = false) boolean.
- live: When true, requests are sent while in the editor (default = false) boolean.
Returns
- Response data string.
- Response code integer.
- Response headers table.
For More Information
- Connecting to web services
- HTTP basic authentication
- Web Services FAQs
- Web Services documentation
- Connecting to Highrise CRM using Web Services
net.sftp
Using sftp file transfer operations.
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 ftp server specified by the FtpConn connection handle.
Note: Use net.sftp.init{}
to create a connection handle.
Required Parameters
- 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 (default = 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
- Read from FTP site in the in the Iguana Files repository
- Using ftp
- Using the ftp list command
- 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 ftp server specified by the FtpConn connection handle.
Note: Use net.sftp.init{}
to create a connection handle.
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
- 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 (default = false) boolean.
- debug: When true return verbose debug information, errors thrown will also contain debug information (default = 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
- Read from FTP site in the in the Iguana Files repository
- Using ftp
- Using the ftp list command
- Wikipedia: File Transfer Protocols (ftp)
- Wikipedia: SSH File Transfer Protocol
- 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 (default = 22) integer.
- timeout: Timeout for operations (default = 15 seconds) integer.
- live: Enable write operations (put, rename, delete) while in the editor (default = false) 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
- Read from FTP site in the in the Iguana Files repository
- Using ftp
- Using the ftp list command
- Wikipedia: File Transfer Protocols (ftp)
- Wikipedia: SSH File Transfer Protocol
- Understanding Lua OO syntax: what the colon operator means
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 on the ftp server specified by the FtpConn connection handle.
Note: Use net.sftp.init{}
to create a connection handle.
Required Parameters
- 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 (default = false) boolean.
Returns
- An array of {filename, is_retrievable} values table.
- Debug information (if requested) string.
For More Information
- Using File and FTP Interfaces
- Read from FTP site in the in the Iguana Files repository
- Using ftp
- Using the ftp list command
- 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 ftp server specified by the FtpConn connection handle.
Note: Use net.sftp.init{}
to create a connection handle.
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
- 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 (default = false) 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 (default = 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
- Read from FTP site in the in the Iguana Files repository
- Using ftp
- Using the ftp list command
- 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 specified by the FtpConn connection handle.
Note: Use net.sftp.init{}
to create a connection handle.
Required Parameters
- 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 (default = 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
- Read from FTP site in the in the Iguana Files repository
- Using ftp
- Using the ftp list command
- Wikipedia: File Transfer Protocols (ftp)
- Wikipedia: SSH File Transfer Protocol
- Understanding Lua OO syntax: what the colon operator means
net.smtp
Using smtp file transfer operations.
net.smtp.send
Example Usage of net.smtp.send{server=<value>, to=<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>, to=<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 = 15 seconds) integer.
- use_ssl: 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 (default = 'no') 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(s). Possible values are ssl-v3, tls-v1, tls-v1.1, tls-v1.2. Default behaviour is to try tls-v1.2 then tls-v1.1. ssl-v2 is no longer supported and ssl-v3 won't be used unless specified. Specifying tls-v1 will allow connections to use all tls versions (starting with tls-v1.2 down to tls-v1.0).string.
- cipher_list: Provide a list of ciphers in OpenSSL format to use. By default Iguana uses a list selected for optimal security. string
- live: When true, emails will be sent while in the editor (default = false) boolean.
- debug: When true return verbose debug information - errors thrown will also contain debug information (default = false) boolean.
For More Information
- Send rich HTML email in our Tools repository
- Email Alerts and Notifications
- Send an Email from Lua
- 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
Using tcp socket connections.
net.tcp.close
Example Usage of Socket:close()
local s = net.tcp.connect('hostname:8086') s:send(Data) local Ack = s:recv() s:close() which is shorthand for: net.tcp.close(s)
Usage
Socket:close()
Close an open socket.
Note: Use net.tcp.connect{}
to open a 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
net.tcp.recv
Example Usage of Socket:recv()
local s = net.tcp.connect('hostname:8086') s:send(Data) local Ack = s:recv() s:close() which is shorthand for: local Ack = net.tcp.recv(s)
Usage
Socket:recv()
Receive data from a remote host via an open socket.
Note: Use net.tcp.connect{}
to open a 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 [, End]])
local s = net.tcp.connect('hostname:8086') s:send(Data) local Ack = s:recv() s:close() which is shorthand for: net.tcp.send(s)
Usage
Socket:send(Data [, Start [, End]])
Send data to a remote host via an open socket.
Note: Use net.tcp.connect{}
to open a socket.
Required Parameters
- 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
These functions perform operations on HL7, XML and X12 messages parsed into Iguana Node Trees.
node.S
Example Usage of Node:S()
-- recommended usage: local s = Node:S() -- which is equivalent to: local s = tostring(Node)
Usage
Node:S()
Converts the specified Node to a string.
The S()
function serializes any node into a string, and performs escaping if the protocol requires it. In general we recommend using Node:S()
for non-leaf nodes and Node:nodeValue()
for leaf nodes.
Returns
- The node converted to a string string.
For More Information
- String conversion S() or nodeValue()?
- Streaming and Filtering Data
- Remove selected characters from any HL7 field for any message, master string.gsub() replacements
- Writing extensions to the node and string libraries
- Understanding Lua OO syntax: what the colon operator means
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 to the specified (parent) XML Node.
Note: This only works with XML node trees.
Required Parameters
- 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
- Code: Setting an XML node to a space ” ” character
- CDA: Generate Document in the Protocols repository
- Append an XML node
- Writing extensions to the node and string libraries
- Understanding Lua OO syntax: what the colon operator means
node.capitalize
Example Usage of string.capitalize(string) or aString:capitalize()
local S = 'string to be capitalized' S:capitalize() --> 'String to be capitalized' string.capitalize('string to be capitalized') --> 'String to be capitalized'
Usage
string.capitalize(string) or aString:capitalize()
Capitalize the first letter of a string.
Required Parameters
- string: String to be capitalized string.
Returns
- String after it it has been capitalized string.
For More Information
- String Manipulation Extensions in our Tools repository
- String Manipulation Extensions in our Tools repository
- Tutorial: Transforming Messages – HL7 to HL7
- 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 child = Node:child(Name) -- which is shorthand for: local child = node.child(Node, Name)
-- local child = Node:child(Name, Repeat)
Usage
Node:child(Name [, Repeat])
Find a child with a specific name under the specified (parent) Node.
Required Parameters
- 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
- Get a child node by name
- Count child nodes
- 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 the specified (parent) Node has.
Optional Parameters
- Name: When used, only children with this name are counted string.
Returns
- The number of children integer.
For More Information
- Get a child node by name
- Count child nodes
- Parsing the IguanaConfiguration.xml file
- Writing extensions to the node and string libraries
- Understanding Lua OO syntax: what the colon operator means
node.compactWS
Example Usage of string.compactWS(string) or aString:compactWS()
local S = ' replace multiple spaces with a single space ' S:compactWS() --> ' replace multiple spaces with a single space ' string.compactWS(' replace multiple spaces with a single space ') --> ' replace multiple spaces with a single space '
Usage
string.compactWS(string) or aString:compactWS()
Replace multiple spaces in a string with a single space.
Required Parameters
- string: String to trim spaces from string.
Returns
- String after white spaces have been trimmed string.
For More Information
- String Manipulation Extensions in our Tools repository
- stringutil.lua - in our code repository.
- 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 under the specified (parent) XML Node.
Note: This only works with XML node trees.
Required Parameters
- 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
- Insert an XML node
- 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 the specified Node is a primary key column for the table.
Note: This function only works with table node trees.
Returns
- True if the column is a primary key, false otherwise boolean.
For More Information
- Check if a node is a primary key
- 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 the specified Node is a leaf node.
Returns
- True if the node is a leaf (has no children), false otherwise boolean.
For More Information
- Check if a node is a leaf node
- Check if a node is empty (null)
- Get the value of a node
- 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 the specified Node is null (not present).
Returns
- True if the node is null (not present), false otherwise boolean.
For More Information
- Dealing with NULL data from databases
- Check if a node is empty (null)
- Check if a node is a leaf node
- Writing extensions to the node and string libraries
- Understanding Lua OO syntax: what the colon operator means
node.mapRange
Example Usage of Dest:mapRange(Source, Start [, End])
-- recommended usage: Dest:mapRange(Source, Start) -- which is shorthand for: node.mapRange(Dest, Source, Start)
Dest:mapRange(Source, Start, End)
Usage
Dest:mapRange(Source, Start [, End])
Maps a range of fields from a source node to the specified destination node Dest.
Required Parameters
- 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
- Translating HL7
- Mapping messages
- Code: Mapping HL7 to HL7
- Writing extensions to the node and string libraries
- Understanding Lua OO syntax: what the colon operator means
node.mapTree
Example Usage of Dest:mapTree(Source)
-- recommended usage: Dest:mapTree(Source) -- which is shorthand for: node.mapTree(Dest, Source)
Usage
Dest:mapTree(Source)
Maps fields from a source node to the specified destination node Dest.
Required Parameters
- Source: The source node node tree.
For More Information
- Code Navigation
- 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 the specified Node.
Returns
- The name of a node string.
For More Information
- Get the name of a node
- 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.nodeText
Example Usage of Node:nodeText()
-- recommended usage: local text = Node:nodeText()
Usage
Node:nodeText()
Returns the text value of the specified Node
Returns
- the text node of that node.
For More Information
- XML Techniques in the Protocols repository
- Read an empty XML TEXT element
- 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 the specified Node.
Returns
- The type and category of the node as a string string.
For More Information
- Get the type of a node
- Node Types for Iguana Node Trees
- Formatting output HL7 without trailing | characters
- Mapping messages
- Code: Mapping HL7 to HL7
- 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 the specified Node.
Returns
- The value of a node string.
For More Information
- String conversion S() or nodeValue()? - which string conversion to use
- Get the value of a node
- Read an empty XML TEXT element
- 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: Node:remove(Index) -- which is shorthand for: node.remove(Node, Index)
Usage
Node:remove(Index)
Removes a child node from the specified Node.
Required Parameters
- Index: The index or name of the child to remove string.
For More Information
- Delete a node tree element
- Delete a table element
- Code: Mapping HL7 to HL7
- Prevent NULL values from causing “unintentional” database deletions
- 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 the specified XML Node.
Note: This only works with XML node trees.
Required Parameters
- 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
- CDA: Generate Document in the Protocols repository
- Set the value of an XML node
- Code: Setting an XML node to a space ” ” character
- 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)
Node:setNodeValue(os.date('%Y%m%H%m'))
-- which is shorthand for:
node.setNodeValue(Node, 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 the specified Node with the value provided in the parameter.
Required Parameters
- Value: The new value of the node. string
Returns
- the node itself whose value was just set (for chaining). node tree
For More Information
- Set the value of a node
- Writing extensions to the node and string libraries
- Understanding Lua OO syntax: what the colon operator means
node.trimLWS
Example Usage of string.trimLWS(string) or aString:trimLWS()
local S = ' trim spaces from the left ' S:trimLWS() --> 'trim spaces from the left ' string.trimLWS(' trim spaces from the left ') --> 'trim spaces from the left '
Usage
string.trimLWS(string) or aString:trimLWS()
Trims white space from the left of a string.
Required Parameters
- string: String to trim spaces from string.
Returns
- String after white spaces have been trimmed string.
For More Information
- String Manipulation Extensions in our Tools repository
- stringutil.lua - in our code repository.
- Dealing with NULL data from databases
- String Manipulation Extensions
- Writing extensions to the node and string libraries
- Understanding Lua OO syntax: what the colon operator means
node.trimRWS
Example Usage of string.trimRWS(string) or aString:trimRWS()
local S = ' trim spaces from the right ' S:trimRWS() --> ' trim spaces from the right' string.trimRWS(' trim spaces from the right ') --> ' trim spaces from the right'
Usage
string.trimRWS(string) or aString:trimRWS()
Trims white space from the right of a string.
Required Parameters
- string: String to trim spaces from string.
Returns
- String after white spaces have been trimmed string.
For More Information
- String Manipulation Extensions in our Tools repository
- stringutil.lua - in our code repository.
- String Manipulation Extensions
- Writing extensions to the node and string libraries
- Understanding Lua OO syntax: what the colon operator means
node.trimWS
Example Usage of string.trimWS(string) or aString:trimWS()
local S = ' trim spaces before and after ' S:trimWS() --> 'trim spaces before and after' string.trimWS(' trim spaces before and after ') --> 'trim spaces before and after'
Usage
string.trimWS(string) or aString:trimWS()
Trims white space from the start and the end of a string.
Required Parameters
- string: String to trim spaces from string.
Returns
- String after white spaces have been trimmed string.
For More Information
- String Manipulation Extensions in our Tools repository
- stringutil.lua - in our code repository.
- String Manipulation Extensions
- Writing extensions to the node and string libraries
- Understanding Lua OO syntax: what the colon operator means
os
The os module contains all the operating system utilities. Functions to access and manipulate the filesystem and various time and difftime functions.
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
- How to build milliseconds value for timestamp from os.clock() reading
- Improving Iguana Editor performance
- 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 evolution of Iguana Date and Time functions
- Parse any date time value
- Date/time conversion: Using the fuzzy date/time parser
- Get time and date
- 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 evolution of Iguana Date and Time functions
- Get the seconds between two times
- Calculate Age From DOB
- Date/time conversion: Using the fuzzy date/time parser
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
The os.fs module contains various file system utilities.
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
os.fs.chmod
Example Usage of os.fs.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.fs.chmod(path, mode)
Change the permission mode of a file.
The mode must be in octal format, i.e., to apply full permissions use '0777' or '777' (the symbolic form '-rwxrwxrwx' does not work).
Note: This command is only for “Unix like” systems, and therefore it does not work on Windows.
Required Parameters
- path: File path string.
- mode: Mode of access to apply (using octal format) string.
For More Information
- File and FTP Interfaces
- Set file permissions
- Wikipedia chmod
- Wikipedia file permissions, scroll down for numerical (octal) notation
os.fs.chown
Example Usage of os.fs.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.fs.chown(path, uid, gid)
Change the owner and group IDs of a file.
Note: This command is only for “Unix like” systems, and therefore it does not work on Windows.
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'.
Windows pattern matching is different, because Windows does not implement Posix style glob wildcard expansion. For example [a-c]* on Posix systems will return all files starting with “a” or “b” or “c”, on Windows it returns files starting with “[a-c]”. To get the same result in Windows you would need to manually expand “[a-c]*” string to “a*”, “b*” and “c*” (and make three calls using os.fs.glob).
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
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
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
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
- filename: 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
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
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 evolution of Iguana Date and Time functions
- Date/time conversion: Using the fuzzy date/time parser
- Get time and date
- How to build milliseconds value for timestamp from os.clock() reading
- 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
The os.ts module contains various time utilities that work with Unix Epoch time.
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 evolution of Iguana Date and Time functions
- Date/time conversion: Using the fuzzy date/time parser
- Get time and date
- 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 evolution of Iguana Date and Time functions
- Get the seconds between two times
- Parse any date time value
- Date/time conversion: Using the fuzzy date/time parser
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 evolution of Iguana Date and Time functions
- Date/time conversion: Using the fuzzy date/time parser
- 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
- time: A table containing the the date and time to be formatted table.
Returns
- A Unix Epoch time in seconds integer.
For More Information
- The evolution of Iguana Date and Time functions
- Date/time conversion: Using the fuzzy date/time parser
- Lua 5.0 online documentation for os.date and os.time(with strftime codes)
os.ts.time
Example Usage of os.ts.time([time])
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([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.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
- time: A table containing the the date and time to be formatted table.
Returns
- A Unix Epoch time in seconds integer.
For More Information
- The evolution of Iguana Date and Time functions
- Get time and date
- Get the seconds between two times
- Date/time conversion: Using the fuzzy date/time parser
- Lua 5.0 online documentation for os.date and os.time(with strftime codes)
package
The package module contains functions for using packages.
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
.
Note: The module
function is deprecated in Lua 5.2 and will be removed in 5.3. Use the recommended module structure instead.
Required Parameters
- module: Name of the module string.
For More Information
queue
In Iguana, all messages are stored in a single message queue, and internal pointers indicate, for each channel, which message is to be processed next. The queue module contains all functions that interact with this message queue. At present, there is only one function, queue.push()
.
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 Importance of queue.push{}
- HL7: Scrub Data in the Protocols repository
- Random ADT Generator
- Polling a database, and generating CSV files
- Connecting to web services
string
The string module contains all the string utility functions.
string.byte
Example Usage of string:byte([i [, j]])
local AString = 'ABC'
local A,B,C = AString:byte(1,3)
-- which is shorthand for:
local A,B,C = string.byte(AString,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.
Optional Parameters
- i: Start position integer.
- j: End position integer.
Returns
- Multiple returns: One numerical code for each requested character integer.
For More Information
- Dealing with binary data
- 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.capitalize
Example Usage of string.capitalize(string) or aString:capitalize()
local S = 'string to be capitalized' S:capitalize() --> 'String to be capitalized' string.capitalize('string to be capitalized') --> 'String to be capitalized'
Usage
string.capitalize(string) or aString:capitalize()
Capitalize the first letter of a string.
Required Parameters
- string: String to be capitalized string.
Returns
- String after it it has been capitalized string.
For More Information
- stringutil.lua - in our code repository.
- String Manipulation Extensions
- Tutorial: Transforming Messages – HL7 to HL7
- Transforming messages
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: 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
- 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.compactWS
Example Usage of string.compactWS(string) or aString:compactWS()
local S = ' replace multiple spaces with a single space ' S:compactWS() --> ' replace multiple spaces with a single space ' string.compactWS(' replace multiple spaces with a single space ') --> ' replace multiple spaces with a single space '
Usage
string.compactWS(string) or aString:compactWS()
Replace multiple spaces in a string with a single space.
Required Parameters
- string: String to trim spaces from string.
Returns
- String after white spaces have been trimmed string.
For More Information
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
- function: Function to be dumped function.
Returns
- A string containing a binary representation of the given function string.
For More Information
- 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
-- which is shorthand for:
local ix1, ix2 = string.find(s,'Lua')
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
- pattern: Pattern to be matched string.
Optional Parameters
- init: Position to start the search string.
- plain: Turn off pattern matching (default = 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
- Find text within a string
- 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
- Format a string
- Dehydrating and rehydrating HL7 messages
- 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
Example Usage of string:gmatch(pattern)
local iter = s:gmatch("hello")
-- which is shorthand for:
local iter = string.gmatch(s,"hello")
-- 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
- pattern: Pattern to be matched string.
Returns
- An iterator function, used to loop through the pattern matches iterator function.
For More Information
- 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.gmatch
Example Usage of string:gmatch(pattern)
local iter = s:gmatch("hello")
-- which is shorthand for:
local iter = string.gmatch(s,"hello")
-- 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
- pattern: Pattern to be matched string.
Returns
- An iterator function, used to loop through the pattern matches iterator function.
For More Information
- resubmit.lua (gfind)
- Format data using repeating fields or segments (gfind)
- What if … Date/Time is too fuzzy for date/time parser? (gmatch)
- Using rxmatch() and rxsub() with PCRE regex (gmatch)
- 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" -- which is shorthand for: x = string.gsub(s, "(%w+)", "%1 %1")
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
- pattern: Pattern to be matched string.
- repl: Replacement 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
- Replace text in a string
- Remove selected characters from any HL7 field for any message, master string.gsub() replacements
- Automatic TA1 acknowledgment to X12 messages
- 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 length = s:len()
-- which is shorthand for:
local length = string.len(s)
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).
Returns
- The length of the string integer.
For More Information
- What is the difference between the "#" operator and string.len(s) function?
- Find the length of a string
- 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
Example Usage of myString:lower()
local low = s:lower()
-- which is shorthand for:
local low = string.lower(s)
Usage
myString: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.
Returns
- A copy of the string with all uppercase letters changed to lowercase string.
For More Information
- Convert a string to upper or lower case
- Code: Filtering out messages you don’t want to forward
- 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 World' s:match('Hello') --> "Hello" -- which is shorthand for: s.match(s, 'Hello')
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
- 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
- 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
Example Usage of string:rep(n)
local s = "Hello!"
local r = s:rep(2)
-->"Hello!Hello!"
-- which is shorthand for:
local r = string.rep(s, 2)
Usage
string:rep(n)
Returns a string that is the concatenation of n
copies of the string s
.
Required Parameters
- n: Number of copies to concatenate integer.
Returns
- A string that is the concatenation of
n
copies of the strings
string.
For More Information
- 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
Example Usage of string:reverse()
local s = "12345"
local r = s:reverse()
-->"54321"
-- which is shorthand for:
local r = string.reverse(s)
Usage
string:reverse()
Returns a string in the reversed order.
Returns
- The string in the reverse order string.
For More Information
- 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])
s = "hello world from Lua" local iter = s:rxmatch("\\S*") -- which is shorthand for: local iter = string.rxmatch(s, "\\S*")
-- 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
- 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
- Extract html tags with PCRE regex
- Using rxmatch() and rxsub() with PCRE regex
- 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" -- which is shorthand for: x = string.rxsub(s, "(\\w+)", "$1 $1")
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
- 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
- Using negative indexes with string:sub()
- 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') -- which is shorthand for: local items = string.split(s, " ")
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
- separator: Delimiter string string.
Returns
- A table with the string values separated by the split string table.
For More Information
- Split strings using a delimiter
- Handling broken MSH segments
- Reformat Report
- 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 shorthand for: 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).
Optional Parameters
- i: Start position integer.
- j: End position integer.
Returns
- The specified substring string.
For More Information
- Using negative indexes with string:sub()
- Get part of a string
- 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.trimLWS
Example Usage of string.trimLWS(string) or aString:trimLWS()
local S = ' trim spaces from the left ' S:trimLWS() --> 'trim spaces from the left ' string.trimLWS(' trim spaces from the left ') --> 'trim spaces from the left '
Usage
string.trimLWS(string) or aString:trimLWS()
Trims white space from the left of a string.
Required Parameters
- string: String to trim spaces from string.
Returns
- String after white spaces have been trimmed string.
For More Information
- String Manipulation Extensions in our Tools repository
- stringutil.lua - in our code repository.
- Dealing with NULL data from databases
- String Manipulation Extensions
- Writing extensions to the node and string libraries
- Understanding Lua OO syntax: what the colon operator means
string.trimRWS
Example Usage of string.trimRWS(string) or aString:trimRWS()
local S = ' trim spaces from the right ' S:trimRWS() --> ' trim spaces from the right' string.trimRWS(' trim spaces from the right ') --> ' trim spaces from the right'
Usage
string.trimRWS(string) or aString:trimRWS()
Trims white space from the right of a string.
Required Parameters
- string: String to trim spaces from string.
Returns
- String after white spaces have been trimmed string.
For More Information
- String Manipulation Extensions in our Tools repository
- stringutil.lua - in our code repository.
- Dealing with NULL data from databases
- String Manipulation Extensions
- Writing extensions to the node and string libraries
- Understanding Lua OO syntax: what the colon operator means
string.trimWS
Example Usage of string.trimWS(string) or aString:trimWS()
local S = ' trim spaces before and after ' S:trimWS() --> 'trim spaces before and after' string.trimWS(' trim spaces before and after ') --> 'trim spaces before and after'
Usage
string.trimWS(string) or aString:trimWS()
Trims white space from the start and the end of a string.
Required Parameters
- string: String to trim spaces from string.
Returns
- String after white spaces have been trimmed string.
For More Information
- String Manipulation Extensions in our Tools repository
- stringutil.lua - in our code repository.
- String Manipulation Extensions
- Writing extensions to the node and string libraries
- Understanding Lua OO syntax: what the colon operator means
string.upper
Example Usage of string:upper()
local s = "hello world"
local r = s:upper()
--> "HELLO WORLD"
-- which is shorthand for:
local r = string.upper(s)
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.
Returns
- A copy of the string with all lowercase letters changed to uppercase string.
For More Information
- Convert a string to upper or lower case
- 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
The table module contains functions that manipulate Lua tables.
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
- Generating HL7 messages with non-standard delimiters
- urlcode.lua
- Online documentation for table.insert
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
The util module is a collection of handy utility script functions.
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
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
- Retrying unreliable external resources
- Throttling database inserts and updates
- Throttling during peak hours
x12
These functions handle messages that are in X12 format.
For more information on working with the X12 message format in Iguana Translator scripts, see Working with 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
- Node types for Iguana node trees
- X12: Parsing and Generation in the Protocols repository
- 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
- Node types for Iguana node trees
- X12: Parsing and Generation in the Protocols repository
- X12 Batch Processing Example
- X12 Processing One Transaction Set at a Time
xml
The xml module contains one function to parse an XML document into an XML node tree.
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.