MENU

Introduction

Welcome to the Iguana API reference section! The following built-in modules are available for use within your Iguana Translator scripts.

Select the Iguana version above and then browse or search for specific modules to see usage information and code examples. Enjoy.

ack

ack.generate

Example Usage of ack.generate(msg)

local Ack, Result = ack.generate(Data)

Usage

ack.generate(msg)

Generate a 'Fast-ACK' for the given message. Creates an ACK message using Iguana's Fast ACK internal acknowledgment message generator. (This is identical to the Fast ACK that can be specified in an LLP Listener source component.)

Note: This function is intended to be used in the script of an LLP Listener Source with ACKnowledgement Settings>ACK = "Translator".

Required Parameters

Returns

For More Information

ack.send

Example Usage of ack.send(ack)

ack.send(Ack)

Usage

ack.send(ack)

Specify the ACK message to send (or nil), it can be created using ack.generate() or built from scratch. If given an empty string or nil, no ACK will be sent.

Note: > This function will only work in the script of an LLP Listener Source with ACKnowledgement Setting>ACK = "Translator".

Required Parameters

For More Information

cache

cache.load

Example Usage of cache.load()

local cd = cache.load()
-- do not do this as the condition will always be true in production
if not cache.load() then
   -- do something I do not want to do in production
end

Usage

cache.load()

Load a value associated with the current sample message (returns nil when running in production).

This can be useful if you have data which is very slow to create, or perhaps not available on your development machine. Once the data is associated with a message (using cache.save) it can be accessed at anytime in the editor using using cache.load().

Returns

cache.save

Example Usage of cache.save(Data)

cache.save('Add you data string here')
local cd = cache.load() --> returns "Add your data string here"

Usage

cache.save(Data)

Save a value associated with the current sample message (does nothing outside the editor).

This can be useful if you have data which is very slow to create, or perhaps not available on your development machine. Once the data is associated with a message it can be accessed at anytime int the editor using using cache.load().

Required Parameters

chm

chm.fromXml

Example Usage of chm.fromXml{vmd=<value>, data=<value>}

local Data = chm.fromXml{vmd='example.vmd', data=XmlData}

Usage

chm.fromXml{vmd=<value>, data=<value>}

If you need to be able to convert HL7 to and from the official XML formats for HL7 version 2.X this function may be useful. This function will convert an XML message into a HL7 string. The style of conversion will depend on how the vmd is configured. This exposes Chameleon XML to HL7 conversion functionality. The reverse of this function is chm.toXml.

Required Parameters

Returns

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 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

Returns

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>}

If you need to be able to convert HL7 to and from the official XML formats for HL7 version 2.X this function may be useful. This function will convert an HL7 message into a XML string. The style of conversion will depend on how the vmd is configured. This exposes Chameleon HL7 to XML conversion functionality. The reverse of this function is chm.fromXml.

Required Parameters

Returns

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>, ...}

Performs a legacy (Chameleon style) VMD transformation. Perform a legacy VMD transformation.

Note: The API is intended to to be used for comparing the output of older Chameleon interfaces to equivalent Lua mapping code. This is useful for regression testing reusing legacy filters implemented with Chameleon.

Required Parameters

Returns

For More Information

db

db.begin

Example Usage of db.begin{api=<value>, name=<value>, ...}

db.begin{
   api=db.MY_SQL, name='test@localhost',
   user='root', password='secret'
}

Usage

db.begin{api=<value>, name=<value>, ...}

Deprecated: use conn:begin{} instead: conn = db.connect{api=db.MY_SQL, name='test@localhost',user='root', password='secret'} conn:begin{}Begins a transaction on the database (if transactions are supported by the database engine). If a transaction is already in progress, the behaviour is database specific.

Probably the most commonly used database that does not support transactions is MySQL when it used with the MyISAM database engine (the newer InnoDB engine for MySQL has transaction support).

Note: If transactions are not supported, then db.begin{}, db.commit{} and db.rollback{} 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 db.execute{} that contains three SQL statements, will be run as three independent commands (one for each SQL statement).

Required Parameters

Optional Parameters

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

Optional Parameters

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{} and db.rollback{} 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 db.execute{} that contains three SQL statements, will be run as three independent commands (one for each SQL statement).

Required Parameters

Optional Parameters

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.

Required Parameters

Optional Parameters

For More Information

db.db_connection

db.db_connection.begin

Example Usage of conn:begin{[live=<value>]}

local conn = db.connect{
   api=db.MY_SQL, name='test@localhost',
   user='root', password='secret'
}
conn:begin{}

Usage

conn:begin{[live=<value>]}

Begins a transaction on the database (if transactions are supported by the database engine). If a transaction is already in progress, the behaviour is database specific.

Probably the most commonly used database that does not support transactions is MySQL when it used with the MyISAM database engine (the newer InnoDB engine for MySQL has transaction support).

Note: If transactions are not supported, then conn:begin{}, conn:commit{} and conn:rollback{} 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 conn:execute{} that contains three SQL statements, will be run as three independent commands (one for each SQL statement).

Optional Parameters

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

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=<value>]}

local conn = db.connect{
   api=db.MY_SQL, name='test@localhost',
   user='root', password='secret'
}
conn:begin{}
conn:execute{
   sql='INSERT INTO Patient VALUES("Fred", "Smith")'
}conn:commit{}

Usage

conn:commit{[live=<value>]}

Commits a transaction, if one has begun (if transactions are supported by the database engine).

Probably the most commonly used database that does not support transactions is MySQL when it used with the MyISAM database engine (the newer InnoDB engine for MySQL has transaction support).

Note: If transactions are not supported, then conn:begin{}, conn:commit{} and conn:rollback{} 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 conn:execute{} that contains three SQL statements, will be run as three independent commands (one for each SQL statement).

Optional Parameters

For More Information

db.db_connection.execute

Example Usage of conn:execute{sql=<value> [, live=<value>]} or conn:execute(sql)

local conn = db.connect{api=db.MY_SQL, name='test@localhost', user='root', password='secret'}

conn:execute('INSERT INTO Patient (FirstName, LastName) VALUES("Fred", "Smith")')
-- Return an array containing multiple results sets, one for each query
-- Note: Some DBs do not support multiple queries in a single "sql" string

local Result = conn:execute{sql = 'SELECT * FROM Patient; SELECT * FROM Kin', live = true}
-- trap the database error thrown by conn:execute
-- Note: The "conn.execute" syntax is required to pass the "conn" object to pcall (conn:execute does not work)

-- try to insert a duplicate key = "Primary Key Violation" error
local TryDuplicateKey = 'INSERT INTO [dbo].[Patient] (Id,FirstName, LastName) VALUES (1, 'Fred', 'Smith')'

local Success, Error = pcall(conn.execute, conn, {sql = TryDuplicateKey, live = true}) -- "conn" as 1st param
local Success, Error = pcall(conn:execute, {sql = TryDuplicateKey, live = true}) -- this does not work

trace(Success) -- false in this case
trace(Error) -- view the pcall Error return as a table
local DbError = Error.message -- copy the DB error message string from Error
trace(DbError) -- view the DB error message

Usage

conn:execute{sql=<value> [, live=<value>]} or conn:execute(sql)

Executes an ad hoc SQL statement that can alter the database.

Both conn:execute() and conn:query() throw errors if a database error is encountered. The errors are regular Lua errors and will cause the execution of the script to halt, unless they are caught by Lua error handling using pcall or xpcall. The error thrown is a table with two fields:

Currently, error codes from ODBC sources and MySQL databases are supported.

Required Parameters

Optional Parameters

Returns

For More Information

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

For More Information

db.db_connection.merge

Example Usage of conn:merge{data=<value> [, bulk_insert=<value>] [, ...]} or conn:merge(data)

conn:merge{
   data=Out, bulk_insert=true, transaction=false
}

Usage

conn:merge{data=<value> [, bulk_insert=<value>] [, ...]} or conn:merge(data)

Merges the database tables created by db.tables() into the database.

Required Parameters

Optional Parameters

For More Information

db.db_connection.query

Example Usage of conn:query{sql=<value> [, live=<value>]} or conn:query(sql)

local conn = db.connect{api=db.MY_SQL, name='test@localhost', user='root', password='secret'}

local Result = conn:query('SELECT * FROM Patient WHERE Flag = "F"')
-- Return an array containing multiple results sets, one for each query
-- Note: Some DBs do not support multiple queries in a single "sql" string

local Result = conn:query('SELECT * FROM Patient; SELECT * FROM Kin')
-- trap the database error thrown by conn:query
-- Note: The "conn.query" syntax is required to pass the "conn" object to pcall (conn:query does not work)

local Success, Error = pcall(conn.query, conn, {sql = 'Select * from Not_a_table'}) -- "conn" as 1st param
local Success, Error = pcall(conn:query, {sql = 'Select * from Not_a_table'}) -- this does not work

trace(Success) -- false in this case
trace(Error) -- view the pcall Error return as a table
local DbError = Error.message -- copy the DB error message string from Error
trace(DbError) -- view the DB error message

Usage

conn:query{sql=<value> [, live=<value>]} or conn:query(sql)

Executes an ad hoc SQL query against a database. Insert or update statements are not allowed (for these, use the conn:execute method).

Both conn:query() and conn:execute() throw errors if a database error is encountered. The errors are regular Lua errors and will cause the execution of the script to halt, unless they are caught by Lua error handling using pcall or xpcall. The error thrown is a table with two fields:

Currently, error codes from ODBC sources and MySQL databases are supported.

Required Parameters

Optional Parameters

Returns

For More Information

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

Returns

For More Information

db.db_connection.rollback

Example Usage of conn:rollback{[live=<value>]}

conn:rollback{}

Usage

conn:rollback{[live=<value>]}

Rollback a transaction, if one has begun (if transactions are supported by the database engine).

Probably the most commonly used database that does not support transactions is MySQL when it used with the MyISAM database engine (the newer InnoDB engine for MySQL has transaction support).

Note: If transactions are not supported, then conn:begin{}, conn:commit{} and conn:rollback{} 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 conn:execute{} that contains three SQL statements, will be run as three independent commands (one for each SQL statement).

Optional Parameters

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 by db.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:

Currently, error codes from ODBC sources and MySQL databases are supported.

Required Parameters

Optional Parameters

Returns

For More Information

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

Optional Parameters

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 by db.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:

Currently, error codes from ODBC sources and MySQL databases are supported.

Required Parameters

Optional Parameters

Returns

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{} and db.rollback{} 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 db.execute{} that contains three SQL statements, will be run as three independent commands (one for each SQL statement).

Required Parameters

Optional Parameters

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

Returns

For More Information

dbs

dbs.dbs_cache

dbs.dbs_cache.tables

Example Usage of obj:tables() or obj:tables(name)

local DbsSchema = dbs.init{filename='table.dbs'}
function main(Data)
   local TableSet = DbsSchema:tables('ADT')
end
local DbsSchema = dbs.init{definition='table Patient (Id string, FirstName string, LastName string, Gender string, key(Id));'}
function main(Data)
   local TableSet = DbsSchema:tables()
end

Usage

obj:tables() or obj:tables(name)

Creates a set of empty record tables, which can be used with db.merge.

Optional Parameters

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

Returns

For More Information

debug

debug.debug

Usage

debug.debug()

Enters an interactive mode with the user, running each string that the user enters. Using simple commands and other debug facilities, the user can inspect global and local variables, change their values, evaluate expressions, and so on. A line containing only the word cont finishes this function, so that the caller continues its execution.

Note: that commands for debug.debug are not lexically nested within any function, and so have no direct access to local variables.

For More Information

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

Returns

For More Information

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:

MaskAction
"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

Returns

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

Optional Parameters

Returns

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

Optional Parameters

Returns

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

Returns

For More Information

debug.getregistry

Usage

debug.getregistry()

Returns the Lua registry table.

Returns

For More Information

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

Returns

For More Information

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

Returns

For More Information

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:

MaskAction
"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

Optional Parameters

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

Optional Parameters

Returns

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

Returns

For More Information

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

Returns

For More Information

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

Returns

For More Information

filter

filter.aes

filter.aes.dec

Example Usage of filter.aes.dec {data=<value>, key=<value>}

local Dec = filter.aes.dec{data=Data,key=Key}

Usage

filter.aes.dec {data=<value>, key=<value>}

Decrypts data encoded using AES encryption.

Required Parameters

Returns

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

Returns

For More Information

filter.base64

filter.base64.dec

Example Usage of filter.base64.dec(data)

local Enc = filter.base64.dec(data)

Usage

filter.base64.dec(data)

Decode Base64 encoded data.

Required Parameters

Returns

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

Returns

For More Information

filter.bzip2

filter.bzip2.deflate

Example Usage of filter.bzip2.deflate(data)

local zipped = filter.bzip2.deflate(data)

Usage

filter.bzip2.deflate(data)

Compress data with BZIP2.

Required Parameters

Returns

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

Returns

For More Information

filter.gzip

filter.gzip.deflate

Example Usage of filter.gzip.deflate(data)

local zipped = filter.gzip.deflate(data)

Usage

filter.gzip.deflate(data)

Compress data with GZIP.

Required Parameters

Returns

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

Returns

For More Information

filter.hex

filter.hex.dec

Example Usage of filter.hex.dec(data)

local Enc = filter.hex.dec(data)

Usage

filter.hex.dec(data)

Decode Hex (Base16) encoded data.

Required Parameters

Returns

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

Returns

For More Information

filter.html

filter.html.enc

Example Usage of filter.html.enc(data)

local Enc = filter.html.enc(data)

Usage

filter.html.enc(data)

Encode text for HTML.

Required Parameters

Returns

For More Information

filter.uri

filter.uri.dec

Example Usage of filter.uri.dec (data)

local Dec = filter.uri.dec(data)

Usage

filter.uri.dec (data)

Decode URI encoded component text.

Required Parameters

Returns

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

Returns

For More Information

filter.uuencoding

filter.uuencoding.dec

Example Usage of filter.uuencoding.dec(data)

local out, info = filter.uuencoding.dec(inp)
stream.toFile('output.tmp', out)
os.rename('output.tmp', info.filename)

Usage

filter.uuencoding.dec(data)

Decode a Unix to Unix transfer (uudecode).

Required Parameters

Returns

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

Optional Parameters

For More Information

filter.zip

filter.zip.deflate

Example Usage of filter.zip.deflate(table)

local T = filter.zip.deflate(table)

Usage

filter.zip.deflate(table)

Compress ZIP data.

Required Parameters

Returns

For More Information

filter.zip.inflate

Example Usage of filter.zip.inflate(data)

local T = filter.zip.inflate(data)

Usage

filter.zip.inflate(data)

Decompress ZIP data.

Required Parameters

Returns

For More Information

global

global.assert

Example Usage of assert(v [, message])

flag, msg = myFunc()
assert(flag) --> ERROR: assertion failed!
flag, msg = myFunc()
assert(flag,'myFunc returned false') --> ERROR: myFunc returned false

Usage

assert(v [, message])

Issues an error when the value of its argument v is false (i.e., nil or false); otherwise, returns all its arguments. message is an error message; when absent, it defaults to "assertion failed!"

Required Parameters

Optional Parameters

Returns

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:

Note: use collectgarbage("count") instead of gcinfo.

Required Parameters

Optional Parameters

Returns

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

Returns

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

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

Returns

For More Information

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

Returns

For More Information

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

Returns

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

Optional Parameters

Returns

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

Returns

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

Optional Parameters

Returns

For More Information

global.module

Usage

module(name [, ...])

Creates a module. If there is a table in package.loaded[name], this table is the module. Otherwise, if there is a global table t with the given name, this table is the module. Otherwise creates a new table t and sets it as the value of the global name and the value of package.loaded[name]. This function also initializes t._NAME with the given name, t._M with the module (t itself), and t._PACKAGE with the package name (the full module name minus last component; see below). Finally, module sets t as the new environment of the current function and the new value of package.loaded[name], so that require returns t.

If name is a compound name (that is, one with components separated by dots), module creates (or reuses, if they already exist) tables for each component. For instance, if name is a.b.c, then module stores the module table in field c of field b of global a.

This function can receive optional options after the module name, where each option is a function to be applied over the module.

Required Parameters

Optional Parameters

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.

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

Returns

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

Optional Parameters

Returns

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 endwill 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

Returns

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

Returns

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:

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

For More Information

global.rawequal

Usage

rawequal(v1, v2)

Checks whether v1 is equal to v2, without invoking any metamethod. Returns a boolean.

Required Parameters

Returns

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

Returns

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

Returns

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

Returns

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

Returns

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

Returns

For More Information

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

Returns

For More Information

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

Returns

For More Information

global.tostring

Usage

tostring(e)

Receives an argument of any type and converts it to a string in a reasonable format. For complete control of how numbers are converted, use string.format.

If the metatable of e has a "__tostring" field, then tostring calls the corresponding value with e as argument, and uses the result of the call as its result.

Required Parameters

Returns

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

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

Returns

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

Optional Parameters

Returns

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

Returns

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

Returns

For More Information

help

help.example

Example Usage of help.example()

local h = help.example()

Usage

help.example()

Returns an example of a table that is compatible with the interactive help system.

Returns

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

Returns

For More Information

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

For More Information

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

Returns

For More Information

hl7

hl7.message

Example Usage of hl7.message{vmd=<value>, name=<value>}

-- If you hardcode the 'name' then the Msg can only be used with that message type (in this case 'PatientRegister')

local Msg = hl7.message{vmd='example.vmd', name='PatientRegister'} -- 'name' hardcoded is not Best Practise
-- Best Practise: Use the message type returned by hl7.parse{} (2nd return) to create an output message to map to

local Msg, Name = hl7.parse{vmd = 'demo.vmd', data = Data} -- 'Name' the HL7 message type
local Out = hl7.message{vmd = 'demo.vmd', name = Name} -- 'Name' used as 2nd parameter

Usage

hl7.message{vmd=<value>, name=<value>}

Create an empty HL7/EDI data tree to populate with data. Returns an empty message object whose sub-fields are the segments of the message, e.g., Msg.PID for the PID segment.

Best Practise: We recommend that you do not hard-code the message 'name' (second parameter). Instead you should use the name returned from hl7.parse{} (second return). This allows the message you create to be compatible with all message types that are defined in the VMD file you are using.

Required Parameters

Returns

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

Returns

For More Information

iguana

iguana.appDir

Example Usage of iguana.appDir()

-- make a temporary directory under the install directory
iguana.appDir()
local mydir = iguana.workingDir()..[[temp_data\]]
os.mkdir(mydir)

Usage

iguana.appDir()

Get the directory where the Iguana executable resides.

Returns

For More Information

iguana.channelConfig

Example Usage of iguana.channelConfig{guid=iguana.channelGuid()}

--Fetching by GUID
local Config = iguana.channelConfig{guid=iguana.channelGuid()}
Config = xml.parse{data=Config}
--Or by channel name
local Config = iguana.channelConfig{name=iguana.channelName()}

Usage

iguana.channelConfig{guid=iguana.channelGuid()}

Fetches the configuration for a channel specified by name or guid.

Optional Parameters

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

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

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

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

For More Information

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

Optional Parameters

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

Optional Parameters

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

Optional Parameters

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

Optional Parameters

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

For More Information

iguana.project

iguana.project.files

Example Usage of iguana.project.files()

require('dateparse')

function main(Data)
   local files = iguana.project.files()
   local mainPath = files['main.lua']
   local dateparsePath = files['shared/dateparse.lua']
   local hl7VmdPath = files['other/hl7.vmd']
end

Usage

iguana.project.files()

Retrieve a table of the files available to the project. The names of files (platform-independent) are used as keys for the table, and the corresponding values contain the file path for each file in the project (platform-dependent), relative to the Iguana install directory.

Returns

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

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

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

For More Information

iguana.setTimeout

Example Usage of iguana.setTimeout(seconds)

iguana.setTimeout(120)

Usage

iguana.setTimeout(seconds)

Set a new timeout for the current script. The timeout has no effect while in the editor.

Normally scripts are allowed 5 minutes to run. When they take too long, Iguana assumes that is due to a programming error or a blocking operation and stops the channel. If you know how long an operation will take you can set the timeout to avoid this. The timeout does not apply to individual actions: e.g., a database operation may take more time than allowed by iguana.setTimeout(), but the script will be stopped as soon as the database operation completes.

Required Parameters

For More Information

iguana.status

Example Usage of local Xml = iguana.status()

local Xml = iguana.status()

local S = xml.parse{data=Xml}

Usage

local Xml = iguana.status()

Like the web API /monitor_query this function gives an XML summary of Iguana's runtime state. This function is quite handy since it's simpler to call than the equivalent web api call.

Returns

For More Information

iguana.stopOnError

Example Usage of iguana.stopOnError(stop)

iguana.stopOnError(false)

Usage

iguana.stopOnError(stop)

Enables/disables stopping the channel when errors occur.

Normally when an error occurs in your script Iguana will log the error and stop the channel - unless you catch it with pcall(). This function can be used to change that behaviour, causing Iguana to continue processing other messages after logging the error.

Required Parameters

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

For More Information

iguana.webInfo

Example Usage of local T = iguana.webInfo()

local T = iguana.webInfo()

Usage

local T = iguana.webInfo()

This function returns a Lua table with information on Iguana's web server and HTTP channel server configuration. It is handy for writing scripts that access the web API of a local Iguana instance since it means you can find the right ports etc. to call automatically.

Returns

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

For More Information

io

io.close

Example Usage of io.close([file])

-- close "myFile"
io.close(myFile)
-- close the default output file
io.close()

Usage

io.close([file])

Closes a file. If a file is not specified, it closes the default output file.

Note that files are automatically closed when their handles are garbage collected, but that takes an unpredictable amount of time to happen. It is usually best to call close() explicitly.

Equivalent to file:close().

Required Parameters

Returns

For More Information

io.filehandle

io.filehandle.close

Example Usage of file:close([file])

-- close "myFile"
myFile:close()

Usage

file:close([file])

Closes file.

Note: that files are automatically closed when their handles are garbage collected, but that takes an unpredictable amount of time to happen. It is usually best to call close() explicitly.

Returns

For More Information

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

For More Information

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

For More Information

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:

FormatDescription
"*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.
numberreads 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

Returns

For More Information

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:

OffsetDescription
"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

Returns

For More Information

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:

OffsetDescription
"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

For More Information

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

Returns

For More Information

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

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

Returns

For More Information

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

Returns

For More Information

io.open

Example Usage of io.open(filename [, mode])

local f, error = io.open('myFile')
local f=io.open('myFile.txt','w+')
f:write('Write a string and then a number',23)
f:close()
local f=io.open('myFile.txt','r')
f:read()

Usage

io.open(filename [, mode])

This function opens a file, in the mode specified in the string mode. It returns a new file handle, or, in case of errors, nil plus an error message.

The mode string can be any of the following:

FormatDescription
"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

Optional Parameters

Returns

For More Information

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

Returns

For More Information

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

Optional Parameters

Returns

For More Information

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:

FormatDescription
"*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.
numberreads 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

Returns

For More Information

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

Returns

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

Returns

For More Information

json

json.createObject

Example Usage of json.createObject()

local obj = json.createObject{data=Data}
-- show that createObject() just returns a "disguised" Lua table
local obj = json.createObject() -- annotation  = json_empty_object
trace(type(obj))                -- object type = table

Usage

json.createObject()

Creates an empty JSON object. This is useful for distinguishing between an empty object and an empty Lua table.

Note: you might expect that this function would return a node tree - it does not, it returns a Lua table labelled/annotated as "json_empty_object". The label is only for convenience/documentation purposes - you can just use tables for JSON objects (see examples).

Returns

For More Information

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

Returns

For More Information

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

Optional Parameters

Returns

For More Information

math

math.abs

Usage

math.abs(x)

Calculates the absolute value of a number.

Required Parameters

Returns

For More Information

math.acos

Usage

math.acos(x)

Calculates the arc cosine (in radians) of a number.

Required Parameters

Returns

For More Information

math.asin

Usage

math.asin(x)

Calculates an arc sine.

Required Parameters

Returns

For More Information

math.atan

Usage

math.atan(x)

Calculates an arc tangent (in radians) of a number.

Required Parameters

Returns

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

Returns

For More Information

math.ceil

Usage

math.ceil(x)

Calculates the smallest integer larger than or equal to a number.

Required Parameters

Returns

For More Information

math.cos

Usage

math.cos(x)

Calculates the cosine of an angle (in radians).

Required Parameters

Returns

For More Information

math.cosh

Usage

math.cosh(x)

Calculates an hyperbolic cosine.

Required Parameters

Returns

For More Information

math.deg

Usage

math.deg(x)

Converts an angle from radians to degrees.

Required Parameters

Returns

For More Information

math.exp

Usage

math.exp(x)

Calculates an exponential value.

Required Parameters

Returns

For More Information

math.floor

Usage

math.floor(x)

Calculates the largest integer smaller than or equal to a number.

Required Parameters

Returns

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

Returns

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

Returns

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

Returns

For More Information

math.log

Usage

math.log(x)

Calculates a natural logarithm.

Required Parameters

Returns

For More Information

math.log10

Usage

math.log10(x)

Calculates a base-10 logarithm.

Required Parameters

Returns

For More Information

math.max

Usage

math.max(x, ...)

Calculates the maximum value among its arguments.

Required Parameters

Returns

For More Information

math.min

Usage

math.min(x, ...)

Calculates the minimum value among its arguments.

Required Parameters

Returns

For More Information

math.modf

Usage

math.modf(x)

Calculates the integral and the fractional parts of a number.

Required Parameters

Returns

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

Returns

For More Information

math.rad

Usage

math.rad(x)

Converts an angle from degrees to radians.

Required Parameters

Returns

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

Returns

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

For More Information

math.sin

Usage

math.sin(x)

Calculates the sine of an angle (in radians).

Required Parameters

Returns

For More Information

math.sinh

Usage

math.sinh(x)

Calculates a hyperbolic sine.

Required Parameters

Returns

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

Returns

For More Information

math.tan

Usage

math.tan(x)

Calculates a tangent of an angle (in radians).

Required Parameters

Returns

For More Information

math.tanh

Usage

math.tanh(x)

Calculates an hyperbolic tangent.

Required Parameters

Returns

For More Information

net

net.ftp

net.ftp.delete

Example Usage of FtpConn:delete{remote_path=<value> [, debug=<value>]}

local FtpConn = net.ftp.init{server='example', username='user', password='password'}
-- recommended usage:
FtpConn:delete{remote_path='afile.txt'}
-- which is shorthand for:
net.ftp.delete(FtpConn, {remote_path='afile.txt'})
-- delete a file
FtpConn:delete{remote_path='/fox_out/test.txt'}
-- use the 'live' parameter to delete a file in the editor

-- cache the connection parameters, set live = true
local FtpConn = net.ftp.init{server='foxton_ftp', username='test_ftp',password='secret', live=true}

-- delete the file
FtpConn:delete{remote_path='/fox_out/test.txt'}

Usage

FtpConn:delete{remote_path=<value> [, debug=<value>]}

Deletes a file (or files) from the specified ftp server.

Required Parameters

Optional Parameters

Returns

For More Information

net.ftp.get

Example Usage of FtpConn:get{remote_path=<value> [, local_path=<value>] [, ...]}

local FtpConn = net.ftp.init{server='example', username='user', password='password'}
-- recommended usage:
FtpConn:get{remote_path='afile.txt'}
-- which is shorthand for:
net.ftp.get(FtpConn, {remote_path='afile.txt'})
--How to download text and binary files

-- cache the connection parameters
local FtpConn = net.ftp.init{server='foxton_ftp', username='test_ftp',password='secret'}

-- get (download) a text file (opens/closes an ASCII connection)
FtpConn:get{remote_path='/fox_out/test.png',local_path='temp/test.txt'}

-- get (download) a binary (picture) file (opens/closes a binary connection)
FtpConn:get{remote_path='/fox_out/test.png',local_path='temp/test.png'}

Usage

FtpConn:get{remote_path=<value> [, local_path=<value>] [, ...]}

Get a single file from the remote server.

The local_path is relative to the Iguana install directory. So the absolute path for 'temp/myfile.txt' is something like 'c:/program files/interfaceware/iguana/temp/myfile.txt (Windows), or '/Users/julianmuir/Downloads/temp/myfile.txt' (Mac, Linux, Unix). You can also specify an absolute path.

Note: The file type is detected and the correct transfer mode, 'ascii' (text) or 'binary', is chosen automatically.

Required Parameters

Optional Parameters

Returns

For More Information

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

Optional Parameters

Returns

For More Information

net.ftp.list

Example Usage of FtpConn:list{remote_path=<value> [, debug=<value>]}

local FtpConn = net.ftp.init{server='example', username='user', password='password'}
-- recommended usage:
FtpConn:list{remote_path='/'}
-- which is shorthand for:
net.ftp.list(FtpConn, {remote_path='/'})
FtpConn:list{remote_path=''}          -- users home directory
FtpConn:list{remote_path='/'} -- ftp root directory
FtpConn:list{remote_path='/fox_out/'} -- user specified data directory

Usage

FtpConn:list{remote_path=<value> [, debug=<value>]}

List the contents of a remote path.

Required Parameters

Optional Parameters

Returns

For More Information

net.ftp.put

Example Usage of FtpConn:put{remote_path=<value> [, data=<value>] [, ...]}

local FtpConn = net.ftp.init{server='example', username='user', password='password'}
-- recommended usage:
FtpConn:put{remote_path='afile.txt', data=Data}
-- which is shorthand for:
net.ftp.put(FtpConn, {remote_path='afile.txt', data=Data})
--How to upload text and binary files

-- cache the connection parameters
local FtpConn = net.ftp.init{server='foxton_ftp', username='test_ftp',password='secret'}

-- put (upload) a text file (opens/closes an ASCII connection)
FtpConn:put{remote_path='/fox_in/test.png',local_path='temp/test.txt'}

-- put (upload) a binary (picture) file (opens/closes a binary connection)
FtpConn:put{remote_path='/fox_in/test.png',local_path='temp/test.png'}

Usage

FtpConn:put{remote_path=<value> [, data=<value>] [, ...]}

Put a single file on the specified server.

The local_path is relative to the Iguana install directory. So the absolute path for 'temp/myfile.txt' is something like 'c:/program files/interfaceware/iguana/temp/myfile.txt (Windows), or '/Users/julianmuir/Downloads/temp/myfile.txt' (Mac, Linux, Unix). You can also specify an absolute path.

Note: The file type is detected and the correct transfer mode, 'ascii' (text) or 'binary', is chosen automatically.

Required Parameters

Optional Parameters

Returns

For More Information

net.ftp.rename

Example Usage of FtpConn:rename{remote_path=<value>, new_remote_path=<value>, ...}

local FtpConn = net.ftp.init{server='example', username='user', password='password'}
-- recommended usage:
FtpConn:rename{remote_path='old_name.txt', new_remote_path='new_name.txt'}
-- which is shorthand for:
net.ftp.rename(FtpConn, {remote_path='old_name.txt', new_remote_path='new_name.txt'})
-- move a file to a 'processed' directory
FtpConn:rename{
remote_path='/fox_out/test.txt',
new_remote_path='/fox_processed/test'..os.date()..'.txt'
}
-- use the 'live' parameter to rename a file in the editor

-- cache the connection parameters, set live = true
local FtpConn = net.ftp.init{server='foxton_ftp', username='test_ftp',password='secret', live=true}

-- rename the file
FtpConn:rename{remote_path='/fox_out/test.txt', new_remote_path='/fox_processed/test_old'.txt'}

Usage

FtpConn:rename{remote_path=<value>, new_remote_path=<value>, ...}

Renames a single file or directory on the remote server.

Required Parameters

Optional Parameters

Returns

For More Information

net.ftps

net.ftps.delete

Example Usage of FtpsConn:delete{remote_path=<value> [, debug=<value>]}

local FtpsConn = net.ftps.init{server='example', username='user', password='password'}
-- recommended usage:
FtpsConn:delete{remote_path='afile.txt'}
-- which is shorthand for:
net.ftps.delete(FtpsConn, {remote_path='afile.txt'})
-- delete a file
FtpsConn:delete{remote_path='/fox_out/test.txt'}
-- use the 'live' parameter to delete a file in the editor

-- cache the connection parameters, set live = true
local FtpsConn = net.ftps.init{server='foxton_ftps', username='test_ftps',password='secret', live=true}

-- delete the file
FtpsConn:delete{remote_path='/fox_out/test.txt'}

Usage

FtpsConn:delete{remote_path=<value> [, debug=<value>]}

Deletes a file from the specified ftp server.

Required Parameters

Optional Parameters

Returns

For More Information

net.ftps.get

Example Usage of FtpsConn:get{remote_path=<value> [, local_path=<value>] [, ...]}

local FtpsConn = net.ftps.init{server='example', username='user', password='password'}
-- recommended usage:
FtpsConn:get{remote_path='afile.txt'}
-- which is shorthand for:
net.ftps.get(FtpsConn, {remote_path='afile.txt'})
--How to download text and binary files

-- cache the connection parameters
local FtpsConn = net.ftps.init{server='foxton_ftps', username='test_ftps',password='secret'}

-- get (download) a text file (opens/closes an ASCII connection)
FtpsConn:get{remote_path='/fox_out/test.png',local_path='temp/test.txt'}

-- get (download) a binary (picture) file (opens/closes a binary connection)
FtpsConn:get{remote_path='/fox_out/test.png',local_path='temp/test.png'}

Usage

FtpsConn:get{remote_path=<value> [, local_path=<value>] [, ...]}

Get a single file from the remote server.

The local_path is relative to the Iguana install directory. So the absolute path for 'temp/myfile.txt' is something like 'c:/program files/interfaceware/iguana/temp/myfile.txt (Windows), or '/Users/julianmuir/Downloads/temp/myfile.txt' (Mac/Linux). You can also specify an absolute path.

Note: The file type is detected and the correct transfer mode, 'ascii' (text) or 'binary', is chosen automatically.

Required Parameters

Optional Parameters

Returns

For More Information

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

Optional Parameters

Returns

For More Information

net.ftps.list

Example Usage of FtpsConn:list{remote_path=<value> [, debug=<value>]}

local FtpsConn = net.ftps.init{server='example', username='user', password='password'}
-- recommended usage:
FtpsConn:list{remote_path='/'}
-- which is shorthand for:
net.ftps.list(FtpsConn, {remote_path='/'})
FtpConn:list{remote_path=''}          -- users home directory
FtpConn:list{remote_path='/'} -- ftp root directory
FtpConn:list{remote_path='/fox_out/'} -- user specified data directory

Usage

FtpsConn:list{remote_path=<value> [, debug=<value>]}

List the contents of a remote path.

Required Parameters

Optional Parameters

Returns

For More Information

net.ftps.put

Example Usage of FtpsConn:put{remote_path=<value> [, data=<value>] [, ...]}

local FtpsConn = net.ftps.init{server='example', username='user', password='password'}
-- recommended usage:
FtpsConn:put{remote_path='afile.txt', data=Data}
-- which is shorthand for:
net.ftps.put(FtpsConn, {remote_path='afile.txt', data=Data})
--How to upload text and binary files

-- cache the connection parameters
local FtpsConn = net.ftps.init{server='foxton_ftps', username='test_ftps',password='secret'}

-- put (upload) a text file (opens/closes an ASCII connection)
FtpsConn:put{remote_path='/fox_in/test.png',local_path='temp/test.txt'}

-- put (upload) a binary (picture) file (opens/closes a binary connection)
FtpsConn:put{remote_path='/fox_in/test.png',local_path='temp/test.png'}

Usage

FtpsConn:put{remote_path=<value> [, data=<value>] [, ...]}

Put a single file on the specified server.

The local_path is relative to the Iguana install directory. So the absolute path for 'temp/myfile.txt' is something like 'c:/program files/interfaceware/iguana/temp/myfile.txt (Windows), or '/Users/julianmuir/Downloads/temp/myfile.txt' (Mac/Linux). You can also specify an absolute path.

Note: The file type is detected and the correct transfer mode, 'ascii' (text) or 'binary', is chosen automatically.

Required Parameters

Optional Parameters

Returns

For More Information

net.ftps.rename

Example Usage of FtpsConn:rename{remote_path=<value>, new_remote_path=<value>, ...}

local FtpsConn = net.ftps.init{server='example', username='user', password='password'}
-- recommended usage:
FtpsConn:rename{remote_path='old_name.txt', new_remote_path='new_name.txt'}
-- which is shorthand for:
net.ftps.rename(FtpsConn, {remote_path='old_name.txt', new_remote_path='new_name.txt'})
-- move a file to a 'processed' directory
FtpsConn:rename{
remote_path='/fox_out/test.txt',
new_remote_path='/fox_processed/test'..os.date()..'.txt'
}
-- use the 'live' parameter to rename a file in the editor

-- cache the connection parameters, set live = true
local FtpsConn = net.ftps.init{server='foxton_ftps', username='test_ftps',password='secret', live=true}

-- rename the file
FtpsConn:rename{remote_path='/fox_out/test.txt', new_remote_path='/fox_processed/test_old'.txt'}

Usage

FtpsConn:rename{remote_path=<value>, new_remote_path=<value>, ...}

Renames a single file or directory on the server.

Required Parameters

Optional Parameters

Returns

For More Information

net.http

net.http.connectionInfo

Example Usage of net.http.connectionInfo()

-- recommended usage: returns "127.0.0.1" as a test IP address in the editor (choose your own test IP)
local info = net.http.connectionInfo() or {RemoteAddr='127.0.0.1'}

Usage

net.http.connectionInfo()

Get connection information such as the IP address of the incoming HTTP connection. Only valid in the context of a From HTTP source.

Returns

For More Information

net.http.delete

Example Usage of net.http.delete{url=<value> [, timeout=<value>] [, ...]} or net.http.delete(<value>)

local Results = net.http.delete{url='http://www.interfaceware.com/not-real-example'}

Usage

net.http.delete{url=<value> [, timeout=<value>] [, ...]} or net.http.delete(<value>)

Removes a resource from an HTTP site using the DELETE method.

Required Parameters

Optional Parameters

Returns

For More Information

net.http.get

Example Usage of net.http.get{url=<value> [, timeout=<value>] [, ...]} or net.http.get(<value>)

local Results = net.http.get{url='http://www.interfaceware.com', parameters={key='value'}}

Usage

net.http.get{url=<value> [, timeout=<value>] [, ...]} or net.http.get(<value>)

Fetches data from an HTTP address using the GET method.

Required Parameters

Optional Parameters

Returns

For More Information

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

Optional Parameters

Returns

For More Information

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

Optional Parameters

Returns

For More Information

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

Optional Parameters

Returns

For More Information

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

Optional Parameters

Returns

For More Information

net.sftp

net.sftp.delete

Example Usage of SftpConn:delete{remote_path=<value> [, debug=<value>]}

local SftpConn = net.sftp.init{server='example', username='user', password='password'}
-- recommended usage:
SftpConn:delete{remote_path='afile.txt'}
-- which is shorthand for:
net.sftp.delete(SftpConn, {remote_path='afile.txt'})
-- delete a file
SftpConn:delete{remote_path='/fox_out/test.txt'}
-- use the 'live' parameter to delete a file in the editor

-- cache the connection parameters, set live = true
local SftpConn = net.sftp.init{server='foxton_sftp', username='test_sftp',password='secret', live=true}

-- delete the file
SftpConn:delete{remote_path='/fox_out/test.txt'}

Usage

SftpConn:delete{remote_path=<value> [, debug=<value>]}

Deletes a file (or files) from the specified ftp server.

Required Parameters

Optional Parameters

Returns

For More Information

net.sftp.get

Example Usage of SftpConn:get{remote_path=<value> [, local_path=<value>] [, ...]}

local s SftpConn = net.sftp.init{server='example', username='user', password='password'}
-- recommended usage:
SftpConn:get{remote_path='afile.txt'}
-- which is shorthand for:
net.sftp.get(SftpConn, {remote_path='afile.txt'})
--How to download text and binary files

-- cache the connection parameters
local SftpConn = net.sftp.init{server='foxton_sftp', username='test_sftp',password='secret'}

-- get (download) a text file (opens/closes an ASCII connection) SftpConn:get{remote_path='/fox_out/test.png',local_path='temp/test.txt'} -- get (download) a binary (picture) file (opens/closes a binary connection)
SftpConn:get{remote_path='/fox_out/test.png',local_path='temp/test.png'}

Usage

SftpConn:get{remote_path=<value> [, local_path=<value>] [, ...]}

Get a single file from the remote server.

The local_path is relative to the Iguana install directory. So the absolute path for 'temp/myfile.txt' is something like 'c:/program files/interfaceware/iguana/temp/myfile.txt (Windows), or '/Users/julianmuir/Downloads/temp/myfile.txt' (Mac/Linux). You can also specify an absolute path.

Required Parameters

Optional Parameters

Returns

For More Information

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

Optional Parameters

Returns

For More Information

net.sftp.list

Example Usage of SftpConn:list{remote_path=<value> [, debug=<value>]}

local SftpConn = net.sftp.init{server='example', username='user', password='password'}
-- recommended usage:
SftpConn:list{remote_path='/'}
-- which is shorthand for:
net.sftp.list(SftpConn, {remote_path='/'})
FtpConn:list{remote_path=''}          -- users home directory
FtpConn:list{remote_path='/'} -- ftp root directory
FtpConn:list{remote_path='/fox_out/'} -- user specified data directory

Usage

SftpConn:list{remote_path=<value> [, debug=<value>]}

List the contents of a remote path.

Required Parameters

Optional Parameters

Returns

For More Information

net.sftp.put

Example Usage of SftpConn:put{remote_path=<value> [, data=<value>] [, ...]}

local SftpConn = net.sftp.init{server='example', username='user', password='password'}
-- recommended usage:
SftpConn:put{remote_path='afile.txt', data=Data}
-- which is shorthand for:
net.sftp.put(SftpConn, {remote_path='afile.txt', data=Data})
--How to upload text and binary files

-- cache the connection parameters
local SftpConn = net.sftp.init{server='foxton_sftp', username='test_sftp',password='secret'}

-- put (upload) a text file (opens/closes an ASCII connection) SftpConn:put{remote_path='/fox_in/test.png',local_path='temp/test.txt'} -- put (upload) a binary (picture) file (opens/closes a binary connection)
SftpConn:put{remote_path='/fox_in/test.png',local_path='temp/test.png'}

Usage

SftpConn:put{remote_path=<value> [, data=<value>] [, ...]}

Put a single file on the specified server.

The local_path is relative to the Iguana install directory. So the absolute path for 'temp/myfile.txt' is something like 'c:/program files/interfaceware/iguana/temp/myfile.txt (Windows), or '/Users/julianmuir/Downloads/temp/myfile.txt' (Mac/Linux). You can also specify an absolute path.

Required Parameters

Optional Parameters

Returns

For More Information

net.sftp.rename

Example Usage of SftpConn:rename{remote_path=<value>, new_remote_path=<value>, ...}

local SftpConn = net.sftp.init{server='example', username='user', password='password'}
-- recommended usage:
SftpConn:rename{remote_path='old_name.txt', new_remote_path='new_name.txt'}
-- which is shorthand for:
net.sftp.rename(SftpConn, {remote_path='old_name.txt', new_remote_path='new_name.txt'})
-- move a file to a 'processed' directory
SftpConn:rename{
remote_path='/fox_out/test.txt',
new_remote_path='/fox_processed/test'..os.date()..'.txt'
}
-- use the 'live' parameter to rename a file in the editor

-- cache the connection parameters, set live = true
local SftpConn = net.sftp.init{server='foxton_sftp', username='test_sftp',password='secret', live=true}

-- rename the file
SftpConn:rename{remote_path='/fox_out/test.txt', new_remote_path='/fox_processed/test_old'.txt'}

Usage

SftpConn:rename{remote_path=<value>, new_remote_path=<value>, ...}

Renames a single file or directory on the server.

Required Parameters

Optional Parameters

Returns

For More Information

net.smtp

net.smtp.send

Example Usage of net.smtp.send{server=<value>, from=<value>, header=<value>, body=<value> [, username=<value>] [, ...]}

local Header = {To = 'adam@smith.com'; -- bcc to jane@smith.com 
From = 'will@smith.com'; -- show a different name as sender
Date = 'Thu, 23 Aug 2001 21:27:04 -0400';
Subject = 'Test Subject';
}

local Results = net.smtp.send{
server='smtp://mysmtp.com:25',
username='john', password='password',
from='john@smith.com',
to={'adam@smith.com', 'jane@smith.com'},
header=Header,
body='Test Email Body',
use_ssl='try'
}

Usage

net.smtp.send{server=<value>, from=<value>, header=<value>, body=<value> [, username=<value>] [, ...]}

Sends an email using the SMTP protocol.

Note: The header fields are for display only, the "To" param contains the actual email recipient(s). Therefore to do Bcc you just add the recipient address in the "To" param, but omit it from the header (so it is not displayed).

Some common header fields include: "From:" (mandatory), "To:", "Subject:", "Date:" (mandatory, "Message-ID:", "Bcc:", " Cc:", "Content-Type:" (non-standard), "In-Reply-To:", "Precedence:" (non-standard), "Received:", "References:", "Reply-To:", "Sender:", "Return-Path:", "Errors-To:" (non-standard), "X-*" (recommended for custom fields)

Note: Though "X-*" is recommended for custom header fields, in fact, any header not expressly defined in the RFC, is allowed, and ignored by most e-mail systems. For example there are three (common) non-standard fields in the list above: "Content-Type:", "Precedence:" and "Errors-To:"

Required Parameters

Optional Parameters

For More Information

net.tcp

net.tcp.close

Example Usage of Socket:close()

local s = net.tcp.connect('hostname:8086')
s:send(Data)
local Ack = s:recv()
s:close()

Usage

Socket:close()

Close an open socket.

For More Information

net.tcp.connect

Example Usage of net.tcp.connect('hostname:port') alternatively: net.tcp.connect{host=<value>, port=<value>}

local s = net.tcp.connect('hostname:8086')
s:send(Data)
local Ack = s:recv()
s:close()
local s = net.tcp.connect{host=hostname, port=8086}
s:send(Data)
local Ack = s:recv()
s:close()

Usage

net.tcp.connect('hostname:port') alternatively: net.tcp.connect{host=<value>, port=<value>}

Connect to a remote host with TCP/IP.

Note: you can specify hostname and port as single parameter or in a table (see examples below).

Required Parameters

Optional Parameters

Returns

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()

Usage

Socket:recv()

Receive data from a remote host via an open socket.

Returns

For More Information

net.tcp.send

Example Usage of Socket:send(Data [, Start [, Stop]])

local s = net.tcp.connect('hostname:8086')
s:send(Data)
local Ack = s:recv()
s:close()

Usage

Socket:send(Data [, Start [, Stop]])

Send data to a remote host via an open socket.

Required Parameters

Optional Parameters

Returns

For More Information

node

node.append

Example Usage of Node:append(Type, Value)

-- recommended usage:
local node = Node:append(Type, Value)
-- which is shorthand for:
local node = node.append(Node, Type, Value)

Usage

Node:append(Type, Value)

Create and append a new node (works with XML only).

Required Parameters

Returns

For More Information

node.child

Example Usage of Node:child(Name [, Repeat])

-- recommended usage:
local name = Node:child(Name)
-- which is shorthand for:
local name = node.child(Node, Name)
-- local name = Node:child(Name, Repeat)

Usage

Node:child(Name [, Repeat])

Find a child with a specific name.

Required Parameters

Optional Parameters

Returns

For More Information

node.childCount

Example Usage of Node:childCount([Name])

-- recommended usage:
local cnt = Node:childCount()
-- which is shorthand for:
local cnt = node.childCount(Node)
-- count named children only
local cnt = Node:childCount(Name)

Usage

Node:childCount([Name])

Determine the number of children a node has.

Required Parameters

Optional Parameters

Returns

For More Information

node.insert

Example Usage of Node:insert(Index, Type, Value)

-- recommended usage:
local node = Node:insert(Index, Type, Value)
-- which is shorthand for:
local node = node.insert(Node, Index, Type, Value)

Usage

Node:insert(Index, Type, Value)

Create and insert a new node (works with XML only).

Required Parameters

Returns

For More Information

node.isKey

Example Usage of Node:isKey()

-- recommended usage:
local iskey = Node:isKey()
-- which is shorthand for:
local iskey = node.isKey(Node)

Usage

Node:isKey()

Determine if a column is the primary key for the table.

Note: This function only works with table node trees.

Required Parameters

Returns

For More Information

node.isLeaf

Example Usage of Node:isLeaf()

-- recommended usage:
local isleaf = Node:isLeaf()
-- which is shorthand for:
local isleaf = node.isLeaf(Node)

Usage

Node:isLeaf()

Determine if a node is a leaf.

Required Parameters

Returns

For More Information

node.isNull

Example Usage of Node:isNull()

-- recommended usage:
local isnull = Node:isNull()
-- which is shorthand for:
local isnull = node.isNull(Node)

Usage

Node:isNull()

Determine if a node is null.

Required Parameters

Returns

For More Information

node.mapRange

Example Usage of Node:mapRange(Source, Start [, End])

-- recommended usage:
local Node:mapRange(Source, Start)
-- which is shorthand for:
local node.mapRange(Dest, Source, Start)
-- local Node:mapRange(Source, Start, End)

Usage

Node:mapRange(Source, Start [, End])

Maps a range of fields from a source node to a destination node.

Required Parameters

Optional Parameters

For More Information

node.mapTree

Example Usage of Node:mapTree(Source)

-- recommended usage:
Node:mapTree(Source)
-- which is shorthand for:
node.mapTree(Dest, Source)

Usage

Node:mapTree(Source)

Maps fields from a source node to a destination node.

Required Parameters

For More Information

node.nodeName

Example Usage of Node:nodeName()

-- recommended usage:
local name = Node:nodeName(Name)
-- which is shorthand for:
local name = node.nodeName(Node, Name)

Usage

Node:nodeName()

Determine the name of a node.

Required Parameters

Returns

For More Information

node.nodeType

Example Usage of Node:nodeType()

-- recommended usage:
local type = Node:nodeType()
-- which is shorthand for:
local type = node.nodeType(Node)

Usage

Node:nodeType()

Determine the type and category of a node.

Required Parameters

Returns

For More Information

node.nodeValue

Example Usage of Node:nodeValue()

-- recommended usage:
local value = Node:nodeValue()
-- which is shorthand for:
local value = node.nodeValue(Node)

Usage

Node:nodeValue()

Determine the value of a node.

Required Parameters

Returns

For More Information

node.remove

Example Usage of Node:remove(Index)

-- recommended usage:
local isleaf = Node:remove(Index)
-- which is shorthand for:
local isleaf = node.remove(Node, Index)

Usage

Node:remove(Index)

Removes a child node.

Required Parameters

For More Information

node.setInner

Example Usage of Node:setInner(Content)

-- recommended usage:
local node = Node:setInner(Content)
-- which is shorthand for:
local node = node.setInner(Node, Content)

Usage

Node:setInner(Content)

Sets the contents of an XML node (works with XML only).

Required Parameters

Returns

For More Information

node.setNodeValue

Example Usage of Node:setNodeValue(Value)

MyNode:setNodeValue(os.date('%Y%m%H%m'))
-- which is equivalent to
node.setNodeValue(MyNode, os.date('%Y%m%H%m'))
local Msg = hl7.message{vmd='demo.vmd', name='ADT'}

-- you want to set the Time in the MSH segment:
Msg.MSH[7][1] = os.date('%Y%m%H%m') -- works: assigns value to the child node
Msg.MSH[7][1]:setNodeValue(os.date('%Y%m%H%m')) -- works: set the node value

-- if you decide to use a variable then:
local MsgTime = Msg.MSH[7][1]
MsgTime = os.date('%Y%m%H%m') -- fails: assigns the date to the variable (try it)
MsgTime:setNodeValue(os.date('%Y%m%H%m')) -- works: set the node value
-- a useful function to empty/clear nodes with or without children
function node:clearNode()
trace(self)
if self:isLeaf() then
self:setNodeValue('') -- usng setNodeValue() is the only way to clear leaf nodes
else
for nChild = self:childCount(), 1 , -1 do
self:remove(nChild)
end
trace(self)
end
end

Usage

Node:setNodeValue(Value)

Updates the value of this node with the value provided in the parameter.

Required Parameters

Returns

For More Information

os

os.clock

Example Usage of os.clock()

local duration = os.clock()
trace(duration)

-- the sub-second portion of the clock time can be useful
local _,subsec = math.modf(os.clock())
local msec=tostring(subsec):sub(3,5)

trace (subsec) -- as a number
trace (msec) -- as a millisecond string

Usage

os.clock()

Returns an approximation of the amount in seconds of CPU time used by the program.

Returns

For More Information

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

Returns

For More Information

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

Returns

For More Information

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

Returns

For More Information

os.fs

os.fs.abspath

Example Usage of os.fs.abspath(path)

local FullPath = os.fs.abspath('..\\docs\\')

Usage

os.fs.abspath(path)

Convert a relative path to an absolute one.

Required Parameters

Returns

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

Optional Parameters

Returns

For More Information

os.fs.chmod

Example Usage of os.chmod(path, mode)

-- grant full access
os.fs.chmod('temp', '777') -- mode must be octal
os.fs.chmod('temp', '0777') -- can use 3 or 4 digits

os.fs.chmod('temp', '-rwxrwxrwx') -- mode using symbolic format does not work

Usage

os.chmod(path, mode)

Change the permission mode of a file.

Note: the mode must be in octal format, i.e., to apply full permissions use '0777' or '777' (the symbolic form '-rwxrwxrwx' does not work)

Required Parameters

For More Information

os.fs.chown

Example Usage of os.chown(path, uid, gid)

-- change user and group
os.fs.stat('temp') -- identfy current uid and gid
os.fs.chown('temp', 503, 504) -- change user and group

os.fs.stat('temp') -- change back
os.fs.chown('temp', 501, 80) -- confirm

Usage

os.chown(path, uid, gid)

Change the owner and group IDs of a file.

Required Parameters

For More Information

os.fs.glob

Example Usage of os.fs.glob(pattern)

for FileName, FileInfo in os.fs.glob('logs/*.log') do
   print(FileName)
   print(FileInfo)
end

Usage

os.fs.glob(pattern)

Iterate over files matching a pattern. The pattern must contain wildcards such as * and ?. E.g., 'input/*.hl7'.

Required Parameters

Returns

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

Optional Parameters

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

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:

FieldDescription
ctimeCreate timestamp
mtimeLast modified timestamp
atimeLast accessed timestamp
modePermission flags for the file
sizeSize of the file in bytes
isdirIs this file a directory?
isregIs this a regular file

Required Parameters

Returns

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

Optional Parameters

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

Returns

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

Returns

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

Returns

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

Returns

For More Information

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

For More Information

os.ts

os.ts.date

Example Usage of os.ts.date([format [, time]])

-- today's date and time 
local todayDateTime = os.ts.date('%c')
-- today's date and time (default format = '%c') 
local todayDateTime = os.ts.date()
-- today's UTC date returned in a table 
local todayDateTime = os.ts.date('!*t')
--  using Unix Epoch Time input generated from os.ts.time()
os.ts.date('%c',os.ts.time{year=1999, month=12, day=1}) -- date returned as formatted string
os.ts.date('*t',os.ts.time{year=1999, month=12, day=1}) -- date returned as a table
os.ts.date(_,os.ts.time{year=1999, month=12, day=1}) -- date returned as formatted string
os.ts.date('',os.ts.time{year=1999, month=12, day=1}) -- returns '' (an empty string)

Usage

os.ts.date([format [, time]])

Returns a string or a table containing date and time, formatted according to the given string format.

Note: os.ts.date is identical to os.date, except that os.date takes a custom time format (userdata) returned from os.time for the "time" parameter.

If the time argument is present, this is the Unix Epoch time as an integer. Otherwise, os.ts.date formats the current time.

If format starts with '!', then the date is formatted in Coordinated Universal Time (UTC).

If format starts with '*t', then os.ts.date returns a table with the following fields: year (four digits), month (1--12), day (1--31), hour (0--23), min (0--59), sec (0--61), wday (weekday, Sunday is 1), yday (day of the year), and isdst (daylight saving flag, a boolean).

If format is not '*t', then os.ts.date returns the date as a string, formatted according to the same rules as the C function strftime.

Note: '!' + '*t' can be combined as '!*t' to return Coordinated Universal Time (UTC) in a table.

When called without arguments, os.ts.date returns a reasonable date and time representation that depends on the host system and on the current locale (that is, os.ts.date() is equivalent to os.ts.date('%c')).

This table gives the strftime codes that are accepted.

Code Replaced by Example
%a Abbreviated weekday name  Thu
%A Full weekday name  Thursday
%b Abbreviated month name  Aug
%B Full month name  August
%c Date and time representation  Thu Aug 23 14:55:02 2001
%d Day of the month (01-31) 23
%H Hour in 24h format (00-23) 14
%I Hour in 12h format (01-12) 02
%j Day of the year (001-366) 235
%m Month as a decimal number (01-12) 08
%M Minute (00-59) 55
%p AM or PM designation PM
%S Second (00-61) 02
%U Week number with the first Sunday as the first day of week one (00-53) 33
%w Weekday as a decimal number with Sunday as 0 (0-6) 4
%W Week number with the first Monday as the first day of week one (00-53) 34
%x Date representation * 08/23/01
%X Time representation * 14:55:02
%y Year, last two digits (00-99) 01
%Y Year 2001
%% A % sign %
 

Required Parameters

Optional Parameters

Returns

For More Information

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

Returns

For More Information

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

Returns

For More Information

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

Returns

For More Information

os.ts.time

Example Usage of os.ts.time([table])

get the current date/time
os.ts.time()
specify date/time in a table (mandatory fields)
os.ts.time{year=1999, month=12, day=01}
specify date/time in a table (all fields)
os.ts.time{year=1999, month=12, day=1, hour=22, min=23, sec=24}

Usage

os.ts.time([table])

Returns the current time when called without arguments, or a time representing the date and time specified by the given table.

Note: os.ts.time is identical to os.time, except that os.time returns a custom time format (userdata).

If specified the table must have fields year, month, and day, and may have fields hour, min, sec, and isdst (for a description of these fields, see the os.ts.date function). The value returned by os.ts.time is a Unix Epoch time as an integer, which can be used as an argument to os.ts.date and os.ts.difftime.

Note: To find the difference duration between two times use os.ts.difftime, which takes into account time zones and daylight saving. Subtracting Unix Epoch time values directly does not work, because it doesn't take into account time zones and daylight saving.

Optional Parameters

Returns

For More Information

package

package.loadlib

Usage

package.loadlib(libname, funcname)

Dynamically links the host program with the C library libname. Inside this library, looks for a function funcname and returns this function as a C function. (So, funcname must follow the protocol (see lua_CFunction)).

This is a low-level function. It completely bypasses the package and module system. Unlike require, it does not perform any path searching and does not automatically adds extensions. libname must be the complete file name of the C library, including if necessary a path and extension. funcname must be the exact name exported by the C library (which may depend on the C compiler and linker used).

This function is not supported by ANSI C. As such, it is only available on some platforms (Windows, Linux, Mac OS X, Solaris, BSD, plus other Unix systems that support the dlfcn standard).

Required Parameters

Returns

For More Information

package.seeall

Example Usage of package.seeall(module)

module('foo', package.seeall)

Usage

package.seeall(module)

Sets a metatable for module with its __index field referring to the global environment, so that this module inherits values from the global environment. To be used as an option to function module.

Generally speaking we advise not using the module keyword for defining your own modules.

Required Parameters

For More Information

queue

queue.push

Example Usage of queue.push{data=<value>} or queue.push(<value>)

local Id = queue.push{data=Data}
iguana.logInfo('Message queued', Id)
-- split a large message into several parts and queue them separately
queue.push('Message part one')
queue.push('Message part two')
queue.push('Message part three')

Usage

queue.push{data=<value>} or queue.push(<value>)

Pushes a message for the channel into the Iguana queue when the channel is running. Be aware that queue.push() does not push messages into the queue when using the editor (test mode).

queue.push() works in three types of component: Filter, From Translator, and From HTTPS. You can call queue.push() multiple times in any of these components, an example where this is useful is when splitting a complex message into several smaller messages.

The queue.push() function returns the message ID of the current message being processed. This is a unique message ID from Iguana's internal logging system, formatted as a string containing today's date followed by seven digits "YYYYMMDD-NNNNNNN". See the iguana.messageId help for more information.

Note: When being used in the editor (test mode) a return of "0-0" is displayed in annotations as a placeholder (IDs are only generated when a channel is running).

Required Parameters

Returns

For More Information

string

The string module contains all the string utility functions.

string.byte

Example Usage of string:byte([i [, j]])

local A,B,C = string.byte('ABC', 1,3)
local A,B,C = AString:byte(1,3)

Usage

string:byte([i [, j]])

Returns the internal numerical codes of the characters s[i], s[i+1], ···, s[j]. The default value for i is 1; the default value for j is i.

Note: that numerical codes are not necessarily portable across platforms.

Required Parameters

Optional Parameters

Returns

For More Information

string.char

Example Usage of string.char(code, ...)

local ABC = string.char(65,66,67)

Usage

string.char(code, ...)

Receives zero or more integers. Returns a string with length equal to the number of arguments, in which each character has the internal numerical code equal to its corresponding argument. Note that numerical codes are not necessarily portable across platforms.

Required Parameters

Returns

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

Returns

For More Information

string.find

Example Usage of string:find(pattern [, init [, plain]])

local s= 'Hello Lua user are you enjoying Lua?'
local ix1, ix2=s:find('Lua') --> 7,9
local s= 'Hello Lua user are you enjoying Lua?'
local ix1, ix2=s:find('Lua', 10) --> 33,35
-- start search 5 characters from the end of the string
local s= 'Hello Lua user are you enjoying Lua?'
local ix1, ix2=s:find('Lua', -5) --> 33,35
-- capture the "pair" but not "=" sign
pair = 'name = Anna'
_, _, key, value = pair:find('(%a+)%s*=%s*(%a+)')
print(key, value)  --> name  Anna

Usage

string:find(pattern [, init [, plain]])

Looks for the first match of pattern in the string s. If it finds a match, then find returns the indices of s where this occurrence starts and ends; otherwise, it returns nil. A third, optional numerical argument init specifies where to start the search; its default value is 1 and can be negative. A value of true as a fourth, optional argument plain turns off the pattern matching facilities, so the function does a plain "find substring" operation, with no characters in pattern being considered "magic".

Note: if plain is given, then init must be given as well. If the pattern has captures, then in a successful match the captured values are also returned, after the two indices.

Required Parameters

Optional Parameters

Returns

For More Information

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 \
new line"
The options 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

Returns

For More Information

string.gfind

string.gmatch

Example Usage of string:gmatch(pattern)

-- This loop iterates over all the words from string s, printing one per line:
s = "hello world from Lua"
for w in s:gmatch("%a+") do
   print(w)
end
-- The next example collects all pairs key=value from the given string into a table:
t = {}
   s = "from=world, to=Lua"
for k, v in s:gmatch("(%w+)=(%w+)") do
   t[k] = v
end

Usage

string:gmatch(pattern)

Returns an iterator function that, each time it is called, returns the next captures from pattern over string s. If pattern specifies no captures, then the whole match is produced in each call.

For this function, a '^' at the start of a pattern does not work as an anchor, as this would prevent the iteration.

Note: string.gfind is a alias for string.gmatch (string.gfind was renamed string.gmatch in Lua 5.1).

Required Parameters

Returns

For More Information

string.gsub

Example Usage of string:gsub(pattern, repl [, n])

local s = "hello world"
x = s:gsub( "(%w+)", "%1 %1")
--> x="hello hello world world"
local s = "hello world"
x = s:gsub("%w+", "%0 %0", 1)
--> x="hello hello world"
local s = "hello world from Lua"
x = s:gsub("(%w+)%s*(%w+)", "%2 %1")
--> x="world hello Lua from"
local s = "home = $HOME, user = $USER"
x = s:gsub("%$(%w+)", os.getenv)
--> x="home = /home/roberto, user = roberto"
x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
      return loadstring(s)()
    end)
--> x="4+5 = 9"
local t = {name="lua", version="5.1"}
   x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t)
--> x="lua-5.1.tar.gz"

Usage

string:gsub(pattern, repl [, n])

Returns a copy of s in which all (or the first n, if given) occurrences of the pattern have been replaced by a replacement string specified by repl, which can be a string, a table, or a function. gsub also returns, as its second value, the total number of matches that occurred.

If repl is a string, then its value is used for replacement. The character % works as an escape character: any sequence in repl of the form %n, with n between 1 and 9, stands for the value of the n-th captured substring (see below). The sequence %0 stands for the whole match. The sequence %% stands for a single %. If repl is a table, then the table is queried for every match, using the first capture as the key; if the pattern specifies no captures, then the whole match is used as the key.If repl is a function, then this function is called every time a match occurs, with all captured substrings passed as arguments, in order; if the pattern specifies no captures, then the whole match is passed as a sole argument.If the value returned by the table query or by the function call is a string or a number, then it is used as the replacement string; otherwise, if it is false or nil, then there is no replacement (that is, the original match is kept in the string).

Required Parameters

Optional Parameters

Returns

For More Information

string.len

Example Usage of string:len()

local s = 'abcd'
trace(#s, s:len(), string.len(s), s.len(s))
--> trace(4,4,4,4)

Usage

string:len()

Receives a string and returns its length. The empty string "" has length 0. Embedded zeros are counted, so "a\000bc\000" has length 5.

Note: string:len() is equivalent to #string (the # operator will also return the length of a table).

Required Parameters

Returns

For More Information

string.lower

Usage

string:lower()

Receives a string and returns a copy of this string with all uppercase letters changed to lowercase. All other characters are left unchanged. The definition of what an uppercase letter is depends on the current locale.

Required Parameters

Returns

For More Information

string.match

Example Usage of string:match(pattern [, init])

local s='hello Lua user are you enjoying Lua today'
s:match('Lua%s(%a+)') --> "user"
s:match('Lua%s(%a+)',20) --> "today"
s:match('Lua%s(%a+)',-10) --> "today"

Usage

string:match(pattern [, init])

Looks for the first match of pattern in the string s. If it finds one, then match returns the captures from the pattern; otherwise it returns nil. If pattern specifies no captures, then the whole match is returned. A third, optional numerical argument init specifies where to start the search; its default value is 1 and can be negative.

Required Parameters

Optional Parameters

Returns

For More Information

string.rep

Usage

string:rep(n)

Returns a string that is the concatenation of n copies of the string s.

Required Parameters

Returns

For More Information

string.reverse

Usage

string:reverse()

Returns a string that is the string s reversed.

Required Parameters

Returns

For More Information

string.rxmatch

Example Usage of string:rxmatch(regex [, mods])

-- This loop iterates over all the words from string s, printing one per line:
s = "hello world from Lua"
for w in s:rxmatch("\\S*") do
   print(w)
end
-- The next example collects all pairs key=value from the given string into a table:
t = {}
s = "from=world, to=Lua"
for k, v in s:rxmatch("(\\w*)=(\\w*)") do
   t[k] = v
end

Usage

string:rxmatch(regex [, mods])

Returns an iterator function that, each time it is called, returns the next captures from regex over string s. If regex specifies no captures, then the whole match is produced in each call.

For this function, any Perl-Compatible Regular Expression may be used, including the start-of-string anchor ^ and the end-of-string anchor $. Common token shorthands like \s for whitespace and \D for non-digits are also supported.

An additional optional argument can be specified as a string of modifier characters to enable additional Regular Expression behaviour:

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

Optional Parameters

Returns

For More Information

string.rxsub

Example Usage of string:rxsub(regex, sub [, n ] [, mods])

local s = "hello world"
x = s:rxsub("(\\w+)", "$1 $1")
--> x="hello hello world world"
local s = "hello world"
x = s:rxsub("(\\w+)", "$0 $0", 1)
--> x="hello hello world"
local s = "hello world from Lua"
x = s:rxsub("(\\w+)\\s*(\\w+)", "\\2 \\1")
--> x="world hello Lua from"
local s = "home = $HOME, user = $USER"
x = s:rxsub("\\$(\\w+)", os.getenv)
--> x="home = /home/roberto, user = roberto"
local s = "4 + 5 = $return 4 + 5$"
x = s:rxsub("\\$(.*?)\\$", function (s)
   return loadstring(s)()
end)
--> x="4 + 5 = 9"
local t = {name="lua", version="5.1"}
local x = string.rxsub("$name-$version.tar.gz", "\\$(\\w+)", t)
--> x="lua-5.1.tar.gz"

Usage

string:rxsub(regex, sub [, n ] [, mods])

This function behaves almost identically to string.gsub. It accepts the same substitution values along with the maximum match count, and it returns the same values. The only difference is that the first argument can be any Perl Compatible Regular Expression.

Similarly, if the substitution pattern is a string, back substitutions are supported in the form $n or \n where n references the value of a specific match group. For regular expressions, back substitution indices may exceed 9. Any index with a valid corresponding match group is supported.

An additional optional argument can be specified as a string of modifier characters to enable additional Regular Expression behaviour:

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

Optional Parameters

Returns

For More Information

string.split

Example Usage of string:split(separator)

local s = "one two three"
local items = s:split(" ")
trace(items[1], items[2], items[3])
-->trace('one','two','three')

Usage

string:split(separator)

Returns a table of values in the string s separated by the delimiter string. If delimiter is not found in the string, the resulting table consists of only the single value s.

If delimiter appears multiple times in a row, the resulting table will contain empty strings as the values in between these segments.

Required Parameters

Returns

For More Information

string.sub

Example Usage of string:sub(i [, j])

local AString = 'Fred'
local ASubString=AString:sub(1,1)
-- which is equivalent to 
local ASubString=string.sub(AString,1,1)

Usage

string:sub(i [, j])

Returns the substring of s that starts at i and continues until j; i and j can be negative. If j is absent, then it is assumed to be equal to -1 (which is the same as the string length). In particular, the call string.sub(s,1,j) returns a prefix of s with length j, and string.sub(s, -i) returns a suffix of s with length i.

The most convenient way to invoke sub is using the method syntax like MyString:sub(1,3).

Required Parameters

Optional Parameters

Returns

For More Information

string.upper

Usage

string:upper()

Receives a string and returns a copy of this string with all lowercase letters changed to uppercase. All other characters are left unchanged. The definition of what a lowercase letter is depends on the current locale.

Required Parameters

Returns

For More Information

table

table.concat

Example Usage of table.concat(table [, sep [, i [, j]]])

t = {'A','B','C'}
result = table.concat(t)
trace(result) --> 'ABC'
-- using separator and start/end
t = {'junk','A','B','C','more junk'}
result = table.concat(t,',',2,4)
trace(result) --> 'A,B,C'

Usage

table.concat(table [, sep [, i [, j]]])

Given an array where all elements are strings or numbers, returns table[i]..sep..table[i+1] ··· sep..table[j]. The default value for sep is the empty string, the default for i is 1, and the default for j is the length of the table. If i is greater than j, returns the empty string.

Required Parameters

Optional Parameters

Returns

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

Optional Parameters

For More Information

table.maxn

Example Usage of table.maxn(table)

t = {[-10]='A',[-1]='B',[33]='C'}
value = table.maxn(t)
trace(value) --> 33
t = {[-10]='A',[-1]='B',[0]='C'}
value = table.maxn(t)
trace(value) --> 0
t = {['x']='A',['y']='B',['z']='C'}
value = table.maxn(t)
trace(value) --> 0

Usage

table.maxn(table)

Returns the value of the largest positive numerical index of the given table, or zero if the table has no positive numerical indices. (To do its job this function does a linear traversal of the whole table.)

Required Parameters

Returns

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

Optional Parameters

Returns

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

Optional Parameters

For More Information

util

util.guid

Example Usage of util.guid(Size)

local guid = util.guid(Size)

Usage

util.guid(Size)

Generate a GUID (Globally Unique ID).

Note: Size argument must be an integer of at least 128, and divisible by 8.

Required Parameters

Returns

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

Returns

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

For More Information

x12

x12.message

Example Usage of x12.message{vmd=<value>, name=<value>}

local Msg = x12.message{vmd='example.vmd', name='841 Claim'}

Usage

x12.message{vmd=<value>, name=<value>}

Create an empty X12 data tree to populate with data.

Required Parameters

Returns

For More Information

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

Returns

For More Information

xml

xml.parse

Example Usage of xml.parse{data=<value>} or xml.parse(<value>)

local Msg = xml.parse{data=Data}

Usage

xml.parse{data=<value>} or xml.parse(<value>)

Parses an XML document.

Required Parameters

Returns

For More Information