Anda di halaman 1dari 109

Kognitio Console Scripting Guide

Version 8.1.0
March 2014
Public

Notices
This document contains proprietary information that should not be reproduced in whole or in part, nor released to third parties nor
used for purposes other than those for which it has been expressly provided without the prior written agreement of Kognitio
Limited.
Kognitio Limited tries to ensure that the information in this document is correct and fairly stated, but does not accept liability for
any error or omission.
Kognitio Console Macro Guide, November 2013
Kognitio Technology Centre
Kognitio Limited, 2014
3A Waterside Park, Cookham Road
BRACKNELL, Berks, RG12 1RB
United Kingdom


















Public
Public Preface
Console Scripting Guide iii
About this Manual
This manual is part of a series that describes how Kognitio Console can enhance the
productivity of your interactive Kognitio Analytical Platform database applications.
The manual assumes that the reader is familiar with relational concepts and SQL.
Kognitio Scripts (Kog Scripts) are an extension of Lua 5.2 which makes Lua easier
to use for the purpose of SQL access of a database.

Console Scripting Guide v
Contents
About this Manual ................................................................................ iii
Contents .............................................................................................. v
1 Kog Scripting ................................................................................................... xiii
1.1 Getting Started .......................................................................................... xiii
1.2 Naked SQL................................................................................................ xiv
Global Variables .................................................................................. xv
SQL statements returning a table ........................................................ xvii
Using $ substitution within SQL statements ......................................... xviii
1.3 KogScript command line tool ..................................................................... xviii
1.4 Using require in Kog scripts ....................................................................... xx
Package Path ...................................................................................... xxi
LUA_PATH .......................................................................................... xxii
Standard Library Location .................................................................... xxii
1.5 What Happens under the hood ............................................................... xxii
1.6 Other Kognitio Extensions ......................................................................... xxiii
Shell .................................................................................................... xxiii
Table __toString() ................................................................................ xxiv
Mixed Lua and Kog scripts .................................................................. xxiv
Lua Lanes............................................................................................ xxiv
1.7 Compatibility with SQL Script .................................................................... xxiv
Whenever ............................................................................................ xxiv
Loops .................................................................................................. xxv
Jump to error exit ................................................................................. xxv
Move large chunks of code into functions ............................................ xxvi
Use functions with parameters for similar SQL .................................... xxvii
2 Kog Script Libarary .......................................................................................... 28
2.1 Lua builtin library constants ....................................................................... 28
math.pi ................................................................................................ 28
2.2 Lua builtin library functions ........................................................................ 28
_G ....................................................................................................... 29
_VERSION .......................................................................................... 29
assert .................................................................................................. 29
collectgarbage ..................................................................................... 29
Preface
Console Scripting Guide vi
dofile .................................................................................................... 30
error ..................................................................................................... 31
getmetatable ........................................................................................ 31
ipairs .................................................................................................... 32
load ..................................................................................................... 32
loadfile ................................................................................................. 33
next ..................................................................................................... 33
pairs .................................................................................................... 34
pcall ..................................................................................................... 35
print ..................................................................................................... 35
rawequal .............................................................................................. 36
rawget ................................................................................................. 36
rawlen .................................................................................................. 36
rawset .................................................................................................. 37
require ................................................................................................. 37
selectfrom ............................................................................................ 37
select ................................................................................................... 38
setmetatable ........................................................................................ 38
shell ..................................................................................................... 39
sql ........................................................................................................ 39
tonumber ............................................................................................. 40
tostring ................................................................................................ 40
type ..................................................................................................... 41
xpcall ................................................................................................... 41
Bitwise operations ............................................................................... 41
bit32.arshift .......................................................................................... 41
bit32.band ............................................................................................ 42
bit32.lshift ............................................................................................ 42
bit32.bxor ............................................................................................. 42
bit32.extract ......................................................................................... 42
bit32.lrotate .......................................................................................... 43
bit32.rshift ............................................................................................ 43
bit32.rrotate ......................................................................................... 43
bit32.bnot ............................................................................................. 44
bit32.replace ........................................................................................ 44
bit32.bor .............................................................................................. 44
bit32.btest ............................................................................................ 44
The Debug Library ............................................................................... 45
debug.debug ....................................................................................... 45
debug.gethook ..................................................................................... 45

Console Scripting Guide vii
debug.getinfo ....................................................................................... 45
debug.getlocal ..................................................................................... 46
debug.getmetatable ............................................................................. 46
debug.getregistry ................................................................................. 47
debug.getupvalue ................................................................................ 47
debug.getuservalue ............................................................................. 47
debug.sethook ..................................................................................... 47
debug.setlocal ..................................................................................... 48
debug.setmetatable ............................................................................. 48
debug.setupvalue ................................................................................ 48
debug.setuservalue ............................................................................. 49
debug.traceback .................................................................................. 49
debug.upvalueid .................................................................................. 49
debug.upvaluejoin ............................................................................... 49
os.clock ............................................................................................... 50
os.date ................................................................................................ 50
os.difftime ............................................................................................ 50
os.execute ........................................................................................... 51
os.exit .................................................................................................. 51
os.getenv ............................................................................................. 52
os.remove............................................................................................ 52
os.rename ........................................................................................... 52
os.setlocale ......................................................................................... 52
os.time ................................................................................................. 53
os.tmpname ......................................................................................... 53
math.modf ........................................................................................... 53
math.asin ............................................................................................. 54
math.tan .............................................................................................. 54
math.exp ............................................................................................. 54
math.atan ............................................................................................ 54
math.acos ............................................................................................ 55
math.max............................................................................................. 55
math.min ............................................................................................. 55
math.deg ............................................................................................. 55
math.randomseed ................................................................................ 56
math.pow ............................................................................................. 56
math.ceil .............................................................................................. 56
math.floor ............................................................................................ 56
math.abs ............................................................................................. 56
math.cosh ............................................................................................ 57
Preface
Console Scripting Guide viii
math.sin ............................................................................................... 57
math.frexp ........................................................................................... 57
math.random ....................................................................................... 57
math.sinh ............................................................................................. 58
math.tanh ............................................................................................ 58
math.ldexp ........................................................................................... 58
math.cos .............................................................................................. 58
math.log............................................................................................... 59
math.atan2 .......................................................................................... 59
math.fmod ........................................................................................... 59
math.sqrt ............................................................................................. 60
math.rad .............................................................................................. 60
Input / output library ............................................................................. 60
io.flush ................................................................................................. 61
io.lines ................................................................................................. 61
io.popen............................................................................................... 61
io.stderr ............................................................................................... 61
io.open ................................................................................................ 61
io.input ................................................................................................. 62
io.stdout ............................................................................................... 62
io.stdin ................................................................................................. 62
io.output............................................................................................... 63
io.close ................................................................................................ 63
io.read ................................................................................................. 63
io.tmpfile .............................................................................................. 63
io.type .................................................................................................. 63
io.write ................................................................................................. 64
file:close .............................................................................................. 64
file:flush ............................................................................................... 64
file:lines ............................................................................................... 64
file:read() ............................................................................................. 65
file:seek ............................................................................................... 65
file:setvbuf ........................................................................................... 66
file:write ............................................................................................... 66
String manipulation functions ............................................................... 67
string.format ........................................................................................ 67
string.byte ............................................................................................ 67
string.gmatch ....................................................................................... 67
string.char ............................................................................................ 68
string.lower .......................................................................................... 68

Console Scripting Guide ix
string.upper ......................................................................................... 69
string.len .............................................................................................. 69
string.sub ............................................................................................. 69
string.dump .......................................................................................... 69
string.reverse ....................................................................................... 69
string.rep ............................................................................................. 70
string.match ......................................................................................... 70
string.gsub ........................................................................................... 70
string.find ............................................................................................. 71
Table Manipulation functions ............................................................... 71
table.__tostring .................................................................................... 71
table.concat ......................................................................................... 71
table.insert ........................................................................................... 72
table.pack ............................................................................................ 72
table.sort ............................................................................................. 72
table.remove ........................................................................................ 73
table.unpack ........................................................................................ 73
coroutine.create ................................................................................... 73
coroutine.resume ................................................................................. 73
coroutine.running ................................................................................. 74
coroutine.status ................................................................................... 74
coroutine.wrap ..................................................................................... 74
coroutine.yield ..................................................................................... 74
package.config .................................................................................... 75
package.cpath ..................................................................................... 75
package.loaded ................................................................................... 75
package.loadlib ................................................................................... 76
package.path ....................................................................................... 76
package.preload .................................................................................. 76
package.searchers .............................................................................. 77
package.searchpath ............................................................................ 78
2.3 Kog Script std library ................................................................................. 78
string.format ........................................................................................ 78
2.4 std.base .................................................................................................... 79
std.assert ............................................................................................. 79
std.bind ................................................................................................ 79
std.collect ............................................................................................ 79
std.compose ........................................................................................ 80
std.concat ............................................................................................ 80
std.curry .............................................................................................. 80
Preface
Console Scripting Guide x
std.die .................................................................................................. 81
std.eval ................................................................................................ 81
std.filter ................................................................................................ 82
std.fold ................................................................................................. 82
std.id .................................................................................................... 82
std.ileaves ........................................................................................... 83
std.inodes ............................................................................................ 83
std.leaves ............................................................................................ 83
std.map................................................................................................ 84
std.memoize ........................................................................................ 84
std.metamethod ................................................................................... 84
std.nodes ............................................................................................. 84
std.op .................................................................................................. 85
std.pack ............................................................................................... 85
std.pickle ............................................................................................. 86
std.prettytostring .................................................................................. 86
std.render ............................................................................................ 87
std.ripairs ............................................................................................. 87
std.tostring ........................................................................................... 88
std.totable ............................................................................................ 88
std.warn ............................................................................................... 88
std.class .............................................................................................. 89
std.list .................................................................................................. 90
2.5 std.strbuf ................................................................................................... 90
__concat .............................................................................................. 90
__tostring ............................................................................................. 90
2.6 std.string.................................................................................................... 90
.. .......................................................................................................... 91
[ ] ......................................................................................................... 91
caps ..................................................................................................... 91
chomp ................................................................................................. 91
escapePattern ..................................................................................... 91
escapeShell ......................................................................................... 92
find_as_list .......................................................................................... 92
finds ..................................................................................................... 92
gsubs ................................................................................................... 93
ltrim ..................................................................................................... 93
numbertosi ........................................................................................... 93
ordinalSuffix ......................................................................................... 94
pad ...................................................................................................... 94

Console Scripting Guide xi
rep ....................................................................................................... 94
rtrim ..................................................................................................... 94
trim ...................................................................................................... 94
wrap .................................................................................................... 95
2.7 std.Table ................................................................................................... 95
clone .................................................................................................... 95
clone_rename ...................................................................................... 96
empty .................................................................................................. 96
indices ................................................................................................. 96
insert ................................................................................................... 97
invert ................................................................................................... 97
merge .................................................................................................. 97
pack..................................................................................................... 98
remove ................................................................................................ 98
sort ...................................................................................................... 98
values .................................................................................................. 99
3 Using Old Style SQL Scripts In Macros ......................................................... 100
Variables ............................................................................................. 100
Assignment .......................................................................................... 101
Connect statement .............................................................................. 101
Describe Command ............................................................................. 101
Disconnect Statement ......................................................................... 101
Edit Command ..................................................................................... 101
Errorcode Command ........................................................................... 101
Errorcodenot Command ...................................................................... 102
Export Command ................................................................................. 102
Goto Command ................................................................................... 102
Help Command ................................................................................... 102
If Statement ......................................................................................... 102
Include Command ............................................................................... 103
Results Command ............................................................................... 103
Returncode Command......................................................................... 103
Set Statement ...................................................................................... 103
Setvar Command ................................................................................. 104
Shell Command ................................................................................... 104
Show Command .................................................................................. 105
Whenever Statement ........................................................................... 105
Quit Command .................................................................................... 105
Preface
Console Scripting Guide xii
Script variables .................................................................................... 106
Example 1: .......................................................................................... 107
A............................................................................................................................108
Index .....................................................................................................................108

Console Scripting Guide xiii
1

Kog Scripting
In this Chapter we describe the Kognitio Scripting language (shortened to Kog Script). It is
based on Lua 5.2, but has a number of extensions
1.1 Getting Started
Kog scripting is turned off by default in Console. It may be turned on in the
Configuration dialog.

Preface
Console Scripting Guide xiv
Then the SQL Script button will create a Kog script. Now a Kog script may be
entered and run with similar debugging facilities to the old SQL scripts.

Pure Lua scripts (i.e. without any Kognitio extensions) may be created by changing
the Script: combo box to Lua.
1.2 Naked SQL
The main way that Kog scripts differ from Lua is that they may contain SQL
statements, without having to be enclosed in quotation marks. This Naked SQL
may also include Lua variables and expressions.
SQL Statements return a Lua table holding the statement status and resultset from
select statements. A few Lua global variables are also set, mainly for compatibility
with old style SQL scripts. Let us start with a simple one line Kog script containing
naked SQL.
select * from sys.ipe_user;

This performs the select statement and sets some global variables. Note that all
naked SQL must end with a ;, this is different from Lua where terminating
statements with ; is optional. Unlike Lua statements, SQL statements are case-
insensitive. So the above script could have been written:
SELECT * FROM sys.ipe_user;
Or
select * from SYS.IPE_USER;

Click here to
create a Kog
script
This Combo box
allows the script type
to be changed.

Console Scripting Guide xv
As well as select the following SQL keywords may also start SQL statements in Kog
scripts: alter, commit, connect, create, defrag, delete, diagnose, disconnect, drop,
explain, export, external, grant, insert, import, lock, merge, picture, reclaim,
recreate, redistribute, rename, repack, revoke, rollback, set, truncate, update and
with.
Global Variables
When a naked SQL statement is executed the following global variables are set:
variable value
cliver String, client version e.g.7.09.01-s121122
sysver String, system version e.g. 07.09.0002
SQLState OK, or error string
WCSerror OK or error string
CompileTime Integer, milli-seconds
ExecuteTime Integer, milli-seconds
FirstRowTime Integer, milli-seconds
TotalTime Integer, milli-seconds
NumRows Integer, number of rows returned
NumColumns Integer, number of columns returned
QueryNumber Integer, number of queries performed in this script run.
Col1 String, Contents of row=1, column=1
Col2 String, Contents of row=1, column=2
Col3 String, Contents of row=1, column=3
Col4 String, Contents of row=1, column=4
Col5 String, Contents of row=1, column=5
Col6 String, Contents of row=1, column=6
Col7 String, Contents of row=1, column=7

Preface
Console Scripting Guide xvi
There are also some global variables that are used to control how scripts are run, and
what to do when errors are encountered.
Variable Contents
error_mode String, made up of three parts:
<onerror> [ ; <transaction> ] [ ; <exitcode> ]
Where:
<onerror> = continue, stop, debug or exit,
default=continue
<transaction> = rollback, commit or none,
default=none
<exitcode> =success, failure or failure=n,
default=success
On Console the <onerror> value is set to the contents of
On server error combo box.
Set this to change the action when an SQL error is
encountered.
e.g error_mode=exit;rollback;failure=9
script_error_mode String, contents of On script fail combo box. Set this to
continue, debug, stop to change the action when a
script fails.
fail_mode String. Set this to continue, debug, stop to change
the action when an error is encountered during testing.
NOTE: for Kognitio testing purposes, may change in
future releases.
history_mode String, contents of the History mode: combo box.
history_group String, contents of the History group text box. Controls
the section in the query history following statements are
placed in.
sqldebug Integer: Controls output to Console logs pane:
nil => no output
0 => no output
1 => OK, or error + error string, rows affected
2 => + times

Console Scripting Guide xvii
3 => + resultset

SQL statements returning a table
Naked SQL Statements may also return a Lua table containing data about the query.
t = select * from sys.ipe_user;

This table contains several values:
Table Variable Value
numRows Integer, Number of rows in the resultset.
numCols Integer, Number of columns in the resultset.
status Integer, 0=OK
colNames Table
rows Table

The colNames table contains an array of the column names, Lua uses tables indexed
from 1 and so t.colnames[1] is the name of the first column.
The rows table contains an array of rows (which are tables), Lua uses tables indexed
from 1 and so t.rows[1] is contents of the first row.
Each row is a Lua table which is indexed by the column names. So t.rows[1].id is the
user id in the first row.
Here is a script to show all the output from a query:
t = select * from ipe_user;

print("table\n")
for i,v in pairs(t) do
print(" ", i, v, " \n");
end;

print("column names\n")
for i,v in pairs(t.colNames) do
print(" ", i, v, " \n");
end;

print("rows\n")
for i,row in pairs(t.rows) do
Preface
Console Scripting Guide xviii
print(" row "..i, " \n")
for j, k in pairs(row) do
print(" ", j, "=", k, " \n");
end;
end;

print("globals\n")
for i,v in pairs(_G) do
print(" ", i, v, " \n");
end;
Using $ substitution within SQL statements
Kog scripts use $ to perform substitution with Lua variables and expressions
within naked SQL.
$<variable>[ ( <some text> ) ] [ <space> | ' | $ | ;|, ]
Where: <space> ::= ', ' | '\t' | '\r' | '\n'
A variable or Lua function call may end with a space, a single or double quote or a $
More complex Lua expressions need to be enclosed in matching ( ) .
$( <expression> ) [ <any> ]
Example 1:
names = {'ipe_user', 'ipe_schema'}
for i,v in pairs(names) do
select * from sys.$v;
end;

Example 2:
function name() return 'ipe_user' end
t = select * from sys.$name();

Example 3:
name = 'ipe_user'
t = select * from $('sys.' .. name);
1.3 KogScript command line tool


Console Scripting Guide xix
This is installed by the Kognitio Console installer on Windows, and is found in
C:\Program Files (x86)\Kognitio Ltd\wx2clients32\kogscript.exe (32 bit)
C:\Program Files\Kognitio Ltd\wx2clients64\kogscript.exe (64 bit)
The usage is:
kogscript.exe [options] [script [args]]
Available options are:
-e stat execute string stat
-i enter interactive mode after executing stat
-l name require library name
-v show version information
-E ignore environment variables
-s server connect to server
-s { str } connect using the connection string str
-u user connect as user
-p password use password for connection
-- stop handling options
- stop handling options and execute stdin

On windows kogscript includes line editing and line history.
As for the Console version a variable called sqldebug controls the amount of info
which is output after each SQL statement.
Kogscript may be exited by either ctrl-z or using os.exit().
Example 1:
>"C:\Program Files (x86)\Kognitio Ltd\wx2clients32\kogscript.exe"
Kog Scripting - version: 7.02.01-s120808-michaela1 (32 bit)
Lua 5.2.1 Copyright (C) 1994-2012 Lua.org, PUC-Rio
> connect to latest user sys using albatros;
> t = select * from
>> ipe_user;
> for i,v in pairs(t.rows) do print(v.name) end
SYS
GRP_DBG
GRP_DISKUSAGE
GRP_MONITOR
GRP_LOG
ODBC
MIKE
PUBLIC
> ^Z

Preface
Console Scripting Guide xx
Example 2:
The following example runs the script listusers.kog:
print("Finding Users:")
connect to latest user sys using albatros;
t = select * from ipe_user;
for i,v in pairs(t.rows) do print(v.name) end

Using kogscript like this:
>"C:\Program Files (x86)\Kognitio Ltd\wx2clients32\kogscript.exe" i
listusers.kog
Kog Scripting - version: 7.02.01-s120808-michaela1 (32 bit)
Lua 5.2.1 Copyright (C) 1994-2012 Lua.org, PUC-Rio
Finding Users:
SYS
GRP_DBG
GRP_DISKUSAGE
GRP_MONITOR
GRP_LOG
ODBC
MIKE
PUBLIC
> os.exit()

1.4 Using require in Kog scripts
Kog scripting is based on Lua 5.2 which has changed the way that require works
from previous Lua versions. When a statement like:
require 'called'

is used then the package path is searched for *.kog and *.lua files, so either
called.kog or called.lua may match.
So if we had created a file C:\Users\Michael.Atkinson\.wxconsole\lua\called.lua
with the single line:
print('hello mike')

Then that statement would have been executed and "hello mike" output to the log.


Console Scripting Guide xxi
Package Path
The package path may be seen by
print(_G.package.path);

Which will have contents like:
;C:\Users\Michael.Atkinson\.wxconsole\kog\?.kog;C:\Users\Michael.Atkin
son\.wxconsole\lua\?.lua;C:\wc2c\src\wx2console\build\wxconsole\debug
\lua\?.lua;C:\wc2c\src\wx2console\build\wxconsole\debug\lua\?\init.lua;
C:\wc2c\src\wx2console\build\wxconsole\debug\?.lua;C:\wc2c\src\wx2co
nsole\build\wxconsole\debug\?\init.lua;.\?.kog;.\?.lua
It is possible to alter the package path to add more locations and then require script
from those locations. So suppose there is a file C:\kogscripts\queries\
getmytable.kog
local t= select * from mytable;
return t;
Then
_G.package.path = "C:/kogscripts/?.kog;" .. _G.package.path;
contents = require "queries.getmytable"

will load that file and set the contents table to the result of the select, so that
contents.rows[1] will be the first row of the resultset.
In the above example the getmytable.kog file is executed once when it is first
required. Subsequently it may be required again but the value returned will be the
same table. In the example below both contents and contents2 are the same table.
_G.package.path = "C:/kogscripts/?.kog;" .. _G.package.path;
contents = require "queries.getmytable"
contents2 = require "queries.getmytable"

Lua is very flexible and there are several ways to be able to create libraries that
contain queries that may be run several time, the following example shows one
method. Say we have a file C:\kogscripts\queries\ getview.kog
local t = {}
function t.getView()
mydata = select * from myview;
return mydata
end
return t

now if we call it with:
Preface
Console Scripting Guide xxii
_G.package.path = "C:/kogscripts/?.kog;" .. _G.package.path;
getter = require "queries.getview"
v1 = getter.getView()
v2 = getter.getView()

v1 and v2 will be different Lua tables, holding the results of two queries.
LUA_PATH
The LUA_PATH environment variable may be used to add extra elements to the
search path for *.lua and *.kog files.
This is used for the Linux server installation to add
/opt/Kognitio/wx2/<version>/lib/lua/?.lua;/opt/Kognitio/wx2/<version>/li
b/kog?.kog;

to the search path.
Standard Library Location
Linux server install ( linux-install-<version>.sfx ):
/opt/Kognitio/wx2/<version>/lib/lua/std

Linux client tools install ( wx2-linux-clients.tar.gz ):
<install path>/lib/lua/std

Windows install:
C:\Program Files (x86)\Kognitio Ltd\wx2clients32\lua\std
C:\Program Files\Kognitio Ltd\wx2clients64\lua\std
1.5 What Happens under the hood
The Kognitio extension for naked SQL is implemented by the sql(String, )
function. This takes one or more strings and executes them one at a time as SQL
statements.
When the Lua parser encounters a SQL keyword (case insensitive) it checks if it is in
Kog script mode, if it is then it does several things.
1. Reads the script text up to the next ; (outside of quotes).

Console Scripting Guide xxiii
2. It interprets the text using the rules of SQL and builds up a string.
3. When it encounters a $ it tries to interpret the following text as a Lua variable or
expression. The expression is concatenated with the string encountered up to the
$.
4. When the text is fully read it compiles the code to place the string (with
concatenation) onto the stack and call the sql(String,..) function.
This means that an SQL expression like:
x = 'name'
y = 'hello'
z = 2
select $x, '$y ', $(z+1) from sys.ipe_user;

Will compile to :
sql([[select ]] .. x .. [[,']] .. y .. [[', ]] .. (z+1) .. [[ from sys.ipe_user]])

where the Lua [[ ]] string operator is used to enclose strings ensuring that single and
double quotes within the naked SQL are handled correctly.


1.6 Other Kognitio Extensions
Although Naked SQL is the major extension, Kognitio have added a few other
features.
Note: Lua scripts (files with extension .lua) are pure 5.2 Lua - the select keyword has
the standard Lua select meaning.
Shell
The shell function has been added to call out into the operating system command
shell. Within Console this uses a Qt Process object.

Preface
Console Scripting Guide xxiv
Table __toString()
Standard Lua does not have a __toString() method defined for tables. This makes it
impossible to override to add more functionality (e.g. pretty printing nested tables).

Mixed Lua and Kog scripts
It is possible to call Kog scripts from Lua scripts and call Lua scripts from Kog
scripts.

Lua Lanes
An experimental version of Lua Lanes is built in. It shows up in the global variables
as lanes.core, Lua Lanes is not usable at the current time.

1.7 Compatibility with SQL Script
Whenever
whenever sqlerror <perform-action> [ <transaction-behaviour> ]
Convert <perform-action> as
continue success => error_mode='continue;success'
continue failure => error_mode='continue;failure'
continue => error_mode='continue;failure'
exit success => error_mode='exit;success'
exit failure => error_mode='exit;failure'
exit => error_mode='exit;success'
exit <error-code> => error_mode='exit;failure=<error-code>'

Console Scripting Guide xxv
Convert <transaction-behaviour> as
commit => 'commit'
rollback => 'rollback'
none => 'none' or ''
So
whever sqlerror continue success rollback => error_mode='continue;success;rollback'
whever sqlerror exit failure commit => error_mode='exit;commit;failure'
Loops
SQL scripts have no easy way to perform loops. This idiom is sometimes used:
set var x 0; -- initialise loop variable
loop:
-- body of loop
select $x+1; -- perform a query to increment loop variable, yuck!
set var x $col1; -- set loop variable from results of query
if $x < 10 goto loop; -- use goto to loop back to label loop.

With Kog Script loops are just one of the Lua control structures.
for i = 0,9 do
-- body of loop
end
Jump to error exit
SQL scripts often have an error exit code similar to:
-- Final Commit
COMMIT;
GOTO SCRIPT_OK;

SCRIPT_ERR:
COMMIT;
QUIT 1;

SCRIPT_OK:

On detection of errors elsewhere in the script there is a GOTO SCRIPT_ERR like:
Preface
Console Scripting Guide xxvi
IF $vCount = 0 GOTO NEXT_PART;
-- vCount > 0 means error
-- do something
GOTO SCRIPT_ERR;

NEXT_PART:

With Lua it is better to use a function for the error
function errorExit()
commit;
os.exit(1)
end

Then call it with
if vCount > 0 then
-- do something
errorExit()
end

Move large chunks of code into functions
SQL scripts often have code like
IF vStatus = 0 GOTO LABEL1;
-- lots of SQL
GOTO LABEL2
LABEL1:
-- more SQL
LABEL2:

In Kog script this may be converted into an if statement, but also it is often
advantageous to put the blocks of SQL into their own functions.
function LotsOfSQL()
-- lots of SQL
end
function MoreSQL()
-- more SQL
end

if vStatus == 0 then
LotsOfSQL()
else
MoreSQL()
end

Console Scripting Guide xxvii
Use functions with parameters for similar SQL
Often SQL scripts will have recurring sections of SQL with minor changes, perhaps
different values in an INSERT statement.
SET VAR id 5;
INSERT INTO sometable (id, ts, name) VALUES ($id, TIMESTAMP, 'dave');
INSERT INTO sometable (id, ts, name) VALUES ($id, TIMESTAMP, 'john');
INSERT INTO sometable (id, ts, name) VALUES ($id, TIMESTAMP, 'sue');

These may be converted into functions
function writeName(name)
INSERT INTO sometable (id, ts, name) VALUES ($id, TIMESTAMP, $name);
end
id = 5
writeName("'dave'")
writeName("'john'")
writeName("'sue'")



Console Scripting Guide 28
2

Kog Script Libarary
In this Chapter we describe the Kog Script standard library (shortened to std).
Note that this library is currently EXPERIMENTAL, and modules and functions may
change over the next few releases.
2.1 Lua builtin library constants
math.pi
The constant 3.1415926535898

2.2 Lua builtin library functions

Kog script uses a small library of built-in functions, mainly from the Lua language
(version 5.2). As well as these there are a wider set of functions which may be loaded
by the require mechanism these are documented in the next few sections.
Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 29
_G
This is the Lua global variable that holds the global environment.

_VERSION
This is a Lua variable that holds the version number. Its value depends whether a
Kog script is being run.
Example
-- Lua scipt
print( _G._VERSION) -- Lua 5.2

-- Kog script
print( _G._VERSION) -- Kog Script 1.0 (Lua 5.2
assert
assert( v [, message] )

This is a Lua builtin function that issues an error when the value of its v argument is
false, that is false or nil, otherwise it returns all its arguments. If the message
parameter is present it prints that, otherwise it prints assertion failed!.

collectgarbage
collectgarbage( opt, [, arg] )

This is a Lua builtin function which provides a generic interface to the garbage
collector. The function it performs depends on the first argument opt:
Opt Function
stop Stop the garbage collector
restart Restart the garbage collector
collect Perform a full garbage collection
count Returns the total amount of memory used by this Kog
Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 30
script instance. Note there may be multiple Kog script
instances running concurrently in Console.
step Perform a garbage collection step. The arg parameter
controls the size of the step in an unspecified way.
If this step finished a garbage collection cycle then
return true.
setpause Sets arg/100 as the new value of the collector pause.
A value of 100 or less means there will be no pause;
values over 100 mean that the garbage collector waits
for the memory to increase to that % from the previous
collection before starting a new collection. So a value of
200 means that the garbage collector waits for the
memory to double.
setstepmul Sets arg/100 as the new value of the collector step
multiplier.
Values below 100 make the collector too slow to be
useful. Larger values make the collector more
aggressive at each step.
isrunning Returns a Boolean which indicates whether the garbage
collector is running.
incremental Default Mode. Run the collector in incremental mode.
generational Use an experimental generational garbage collector.

dofile
dofile( [filename] )

This Lua builtin function opens the named file and executes its conents as a chunk of
Lua or Kog script code. If the filename parameter ends with .kog then the chunk is run
as Kog script, otherwise as Lua. When called with no arguments Lua would
normally take input from stdin, however Console has currently no way of feeding
input to stdin, so dofile() just hangs.
As chunks behave as the body of Lua functions, values returned by the chunk are
returned by dofile. Errors in the chunk are propagated by dofile to its caller.
Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 31
error
error( message [, level] )

This is a Lua builtin function which terminates the last protected function called and
returns an error message based on the message parameter. error() never returns.
Level Function
0 No additional information is added to the error message
parameter.
1 Default. The position where the error function was called is
prepended to the error message parameter.
2 The position where the function that called error function is called
is prepended to the error message parameter.
3,4, Higher positions in the call stack (3
rd
, 4
th
) positions.

getmetatable
getmetatable( object )

This is a Lua builtin function to find the metatable of the object parameter.
Object has Function returns
No metatable nil
__metatable field value of the __metatable field.
metatable metatable

Example
t = {'a','b'}
print(getmetatable(t),' \n') -- no metatable for tables by default
m = {1,2,'ab'}
setmetatable(t,m) -- add a metatable to t
print(getmetatable(t), ' \n')
m.__metatable = {3}
print(getmetatable(t),' \n') -- set the __metatable field
print(m, m.__metatable, ' \n');
-- output is:
Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 32
--nil
--table: 15E0B6E0
--table: 169F1128
--table: 15E0B6E0 table: 169F1128
ipairs
ipairs( t )

This is a Lua builtin function to get an iterator of a table as { index, value } pairs.
If t has a metamethod __ipairs, then it calls __ipairs(t) and returns the first three
results from the call.
Otherwise ipairs(t) returns three values: an iterator function, the table t and 0, so that
the code:
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.
Note that non-integer keys will not be iterated over and t[1] = a; t[3]=c will only
iterate over the first element.
Example
t = {'a','b','c', e='e', 'f'}
for i,v in ipairs(t) do print(i,v,' \n') end
--Output is (note e is missing):
--1 a
--2 b
--3 c
--4 f
load
load(ld, [, source [, mode [, env]]])

This is a Lua builtin function to load a chunk of Lua code.
If ld is a string then the chunk is that string. If ld is a function then load calls it
relatedly to get the chunk pieces. Each call to ld must return a string that
concatenates with previous results to create the chunk. A return or no value, value of
nil or the empty string signals the end of the chunk.
If there are no syntactiv errors then load returns the compiled chunk as a function;
otherwise load returns nil plus the error message.
Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 33
The source parameter is used for error messages and debugging information as the
source of the chunk. When absent the default for ld strings is ld, and for ld functions
=(load).
The mode control whether the chunk can be text or precompiled binary. It may be b
(binary chunks), t (text chunks), or to the default bt (both binary or text).
If the resulting function has upvalues, the first upvalue is set to the env parameter (or
the global environment _G if env is absent). When loading main chunks the first
upvalue will be set to the _ENV variable.
Example
i=0;
function x() i=i+1; if i>5 then return nil; end; return "print( 'call='..tostring(" .. i ..
")..'\\n')" end;
y = load(x)
y()
--output is:
--call=1
--call=2
--call=3
--call=4
--call=5

See also string.dump
loadfile
loadfile( [filename [, mode [, env] ] ] )

This is a Lua builtin function to load a chunk from a file.
It is similar to load() but only loads from files (or stdin).
next
next( table [, index] ] )
This is a Lua builtin function to traverse all fields of a table.
Its table argument is a table and its index argument is an index into this table. The next
function returns the next index of the table and its associated value. When called
with nil as its second argument or with a single argument next returns an initial index
and its associated value.
Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 34
When called with the last index or with nil for an empty table, next returns nil.
You may use next to check if a table is empty (see second example)
The order in which the indices are enumerated is not specified, even for numeric
indices.
The behavior of next is undefined if during the traversal a value is assigned to a non-
existent fields in the table. Pre-existent fields may be modified, including being set to
nil.
Example
t = { 1, a='A', 3 }
i,v = next(t)
print(i, v, ' \n')
i,v = next(t,i)
print(i, v, ' \n')
i,v = next(t,i)
print(i, v, ' \n')
-- output is:
-- 1 1
-- 2 3
-- a A

Example
t = {1}
print(next(t) == nil, ' \n')
t = {}
print(next(t) == nil, ' \n')
-- Output is:
--false
--true
pairs
pairs(t)

This is a Lua builtin function which allows iteration over a table.
If the table t has a metamethod __pairs, then __pairs is called with t as its argument
and returns the first three results from the __pairs call.
Otherwise it returns three values the next function, the table t and nil. Then the code
for i,v in pairs(t) do body end

iterates over all key value pairs (i,v) of table t.
Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 35
The behavior of this construct is undefined if during the traversal a value is assigned
to a non-existent fields in the table. Pre-existent fields may be modified, including
being set to nil.
Example
t = { 1, a='A', 3 }
for i,v in pairs(t) do print(i,v, ' \n') end
-- output is:
-- 1 1
-- 2 3
-- a A

pcall
pcall( f [, arg1, ] )

This is a Lua builtin function to run a function f with its arguments in protected mode.
Any error generated by f is not propagated; instead pcall catches the error and
returns a status code.
The first result from pcall is the boolean status code which is true if the f function does
not generate an error. In that case pcall also returns all results from the call. If f
generates any error pcall returns false plus the error message.
Example
function x(a) print(a..'\n'); error("this is an error") end;
a, b = pcall(x, 5)
print(a, b, ' \n')
-- Output is:
--5
--false [string "script"]:1: this is an error
print
print( )

This is a Lua builtin function to output to stdout.
The print is intended as a quick and simple way of showing values, for instance for
debugging. It uses tostring to convert each argument to a string and then prints them
to stdout.
For complete control over output use String manipulation functions
Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 36
This library provides generic functions for string manipulation, such as finding and
extracting substrings, and pattern matching. When indexing a string in Lua, the first
character is at position 1 (not at 0, as in C). Indices are allowed to be negative and are
interpreted as indexing backwards, from the end of the string. Thus, the last
character is at position -1, and so on.
The string library provides all its functions inside the table string. It also sets a
metatable for strings where the __index field points to the string table.
Therefore, you can use the string functions in object-oriented style. For
instance, string.byte(s,i) can be written as s:byte(i).
The string library assumes one-byte character encodings.
string.byte (s [, 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. These indices are corrected
following the same rules of function string.sub.
Numerical codes are not necessarily portable across platforms.

string.format and io.write
rawequal
rawequal( v1, v2 )

This is the Lua builtin function for equality.
It checks whether v1 is equal to v2 without invoking any metamethods, returning
true if the are equal and false if not.
Tables are equal if they are the same table, not if their contents are the same.
User data is equal if they are the same object.
Example
t1 = {1}
t2 = {1}
print(rawequal(t1,t1)) -- true
print(rawequal(t1,t2)) -- false
Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 37
rawget
rawget( table, index )
This Lua builtin function finds the value at index in the table. No metamethods are
invoked.
Example
t1 = {1,2,3, b='B', 4 }
print(rawget(t1, 1)) -- 1
print(rawget(t1, 4)) -- 4
print(rawget(t1, 'b')) -- B
rawlen
rawlen( v )

This Lua builtin function finds the length of a table or string
Example
t1 = {1,2,3}
t2 = {1, 2, 3, b='b', 4 }
print(rawlen(t1)) -- 3
print(rawlen(t2)) -- 4, Note only counts integer indexed
print(rawlen("12345")) -- 5
rawset
rawset( table, index, value)

This Lua builtin function to assign a value to table[index]. No metamethods are
invoked .
Example
t1 = {1,2,3, b='B', 4 }
rawset(t1, 'b', 'C')
rawset(t1, 2, -2)
rawset(t1, 5, 5)
print(rawget(t1, 'b')) -- C
print(rawget(t1, 2)) -- -2
print(rawget(t1, 5)) -- 5
require
require( modname )
Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 38

This is a Lua builtin function to load a module.
The require function starts by looking to see whether there is an entry in the
package.loaded table, if there is the module is already loaded and require returns the
value of package.loaded[modname].
If not present in package.loaded then require tries to find a loader by following the
package.searchers sequence. It is possible to change how require looks for a module
by changing this sequence.
Using the default configuration of the package.searchers sequence require first sees if
package.preload[modname] has a value. If it has then the (it must be a function)
function value is the loader. Otherwise require searches for a Kog script (Lua) loader
in using the package.path path. If that also fails package.cpath is used to find a C
loader. If that also fails it tries an all-in-one loader.
Once a loader is found require calls it with two arguments:

selectfrom
selectfrom( index, )

This is a Kog script builtin function to replace the select() function. The select
keyword is used by SQL.
If index is a positive number ( greater than 0) then return all arguments after
argument number index. Negative numbers return that number of arguments from
the end, so -1 returns the last argument. If index is the string # then return the
number of extra arguments received.
Example
print( selectfrom(3, 1,2,3,4,5,6,7) ) -- 3 4 5 6 7
print( selectfrom(-3, 1,2,3,4,5,6,7) ) -- 5 6 7
-- print( selectfrom(0, 1,2,3,4,5,6,7) ) -- gives an error
print( selectfrom(8, 1,2,3,4,5,6,7) ) -- no output
print( selectfrom('#', 1,2,3,4,5,6,7) ) -- 7
print( selectfrom(3.5, 1,2,3,4,5,6,7) ) -- 4 5 6 7

select
select( index, )
This is a Lua builtin function, do not use in Kog scripts use selectfrom instead.
Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 39
Example
-- In Lua code
print( select(3, 1,2,3,4,5,6,7) ) -- 3 4 5 6 7
print( select(-3, 1,2,3,4,5,6,7) ) -- 5 6 7
-- print( selectfrom(0, 1,2,3,4,5,6,7) ) -- gives an error
print( select(8, 1,2,3,4,5,6,7) ) -- no output
print( select('#', 1,2,3,4,5,6,7) ) -- 7
print( select(3.5, 1,2,3,4,5,6,7) ) -- 4 5 6 7
setmetatable
setmetatable( table, metatable )

This is a Lua builtin function to set the metatable of a table.
If metatable is nil then remove the metatable. If the original has a __metatable field then
raise an error.
Example
t = {'a','b'} -- no metatable for tables by default
m = {1,2,'ab'}
setmetatable(t,m) -- add a metatable to t
setmetatable(t, nil) -- remove the metatable from t
m.__metatable = {3}
setmetatable(t,m) -- add a __metatable to t
setmetatable(t, nil) -- causes error
shell
shell( command )

This is a Kog script builtin function to execute a command in an operating system
shell. Note that unlike 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 POSIX systems, 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).
When possible, you may prefer to use read( )

Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 40
Equivalent to io.input():read().
io.tmpfile, which automatically removes the file when the program ends.
this runs the command within a QT QProcess.
On MS Windows each command has to be in a separate shell command like:
shell('cmd.exe /C help')
shell('cmd.exe /C pwd')

On MS Windows it is not possible to change the working directory by:
shell('cmd.exe /C cd C:\somepath') -- does not work
shell('cmd.exe /C pwd') -- working directory unchanged

Instead use:
shell_dir = [[C:\somepath]] -- [[ ]] string used to avoid \ escape
shell('cmd.exe /C pwd') -- working directory set to c:\somepath

Example:
shell('cmd.exe /C pwd')
shell_dir = [[C:\cygwin]]
shell('cmd.exe /C pwd')

shell_dir = [[C:\program files]]
shell('cmd.exe /C pwd')
sql
sql( s )

This is a Kog script builtin function used to execute SQL. The string s is executed as
SQL.
Example
connect to latest user sys using password;
sqldebug=2
sql("select * from ipe_user" )
-- Output is:
--Connect statement.
--
--Connecting :
--DSN=latest;UID=sys;PWD= password
--DSN=latest;UID=sys;PWD= password
Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 41
--OK60 rows (118 ms)
--60 rows buffered
--Execute time: 0:00.1
--First row time: 0:00.1
--All rows time: 0:00.1

tonumber
tonumber( e, [, base] )

This is a Lua builtin function to convert the e argument to a number.
When called with one argument then if that argument is a string convertible to a
number that number is returned. If it is a number then that number is returned. Base
10 is assumed.
When called with a base parameter (a number between 2 and 36), the number is
interpreted in that base. In bases above 10 letters are interpreted as digits with a or
A being 10, b or B being 11, etc.
Failed conversions return nil
Example
print( tonumber(1), ' \n' ) -- 1
print( tonumber('2'), ' \n' ) -- 2
print( tonumber('2.5'), ' \n' ) -- 2.5
print( tonumber('2b'), ' \n' ) -- nil
print( tonumber('2b', 16), ' \n' ) -- 43
print( tonumber(111, 2), ' \n' ) -- 7
a=111; print( tonumber(a, 2), ' \n' ) -- 7
tostring
tostring( v )

This is a Lua builtin function to convert the v argument to a string.
It converts arguments of any type into strings of a reasonable format. If the
metastable of v has a __tostring field then this __tostring is called with v as an
argument and returns __tostring return value.
For complete control of how numbers are converted use string.format.
Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 42
type
type( v )

This is a Lua builtin function to find the type of its v argument as a string. Possible
values are:
nil
number
string
boolean
table
function
thread
userdata

xpcall
xpcall( fn msghandler, [, arg1, ] )

This is a Lua builtin function similar to pcall, except that it also sets a new message
handler msghandler.
Bitwise operations
This library provides bitwise operations. It provides all its functions inside the
table bit32.
Unless otherwise stated, all functions accept numeric arguments in the range (-
2
51
,+2
51
); each argument is normalized to the remainder of its division by 2
32
and
truncated to an integer (in some unspecified way), so that its final value falls in the
range [0,2
32
- 1]. Similarly, all results are in the range [0,2
32
- 1]. Note
that bit32.bnot(0) is0xFFFFFFFF, which is different from -1.
bit32.arshift
arshift(x,disp)

This is a Lua builtin function which returns the number x shifted disp bits to the
right (arithmetic right shift). The number disp may be any integer. Negative
displacements shift to the left.
Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 43
The vacant bits on the left are filled with copies of the high bit of x; vacant bits on the
right are filled with zeros. When disp is greater than 31 the value zero (x +ve) or
0xFFFFFFFF (x ve) are returned; when disp is less than -31 the value zero is
returned.
bit32.band
band( )

Lua builtin function returns the bitwise and of its operands.

print( bit32.band(5,7)); -- 5
print( bit32.band(3,5,15)); -- 1
print( bit32.band(-1,5,15)); -- 5
bit32.lshift
lshift(x,disp)

This is a Lua builtin function which returns the number x shifted disp bits to the left
(logical left shift). The number disp may be any integer. Negative displacements
shift to the right.
In both directions vacant bits are filled with zeros. Displacements with absolute
values greater than 31 result in zero as all bits have been shifted out.
For positive displacements the following equality is true:
assert( bit32.lshift(x,disp) == (x * 2^disp) % 2^32)
bit32.bxor
bxor( )

This is a Lua builtin function which returns the bitwise exclusive or of its operands.
print( bit32.bxor(5,7)); -- 2
print( bit32.bxor(3,5,15)); -- 9
print( bit32.bxor(-1,5,15)); -- 4292967285
bit32.extract
extract(n, field [, width] )

Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 44
This is a Lua builtin function which returns the unsigned number formed by the bits
from field to field + width -1 extracted from n. Bits are numbered from 0 (least
significant) to 31 (most significant). All accessed bits must be in the range [0,31]. The
default for width is 1.
print( bit32.extract(-1, 7)); -- 1 (bit 7)
print( bit32.extract(-1, 7, 4)); -- 15 (bits 7-10)
print( bit32.extract(1+4+8+32, 2, 3)); -- 3 (bits 2-4)
bit32.lrotate
lrotate(x,disp)

This is a Lua builtin function which returns the number x rotated disp bits to the left
(logical left shift). The number disp may be any integer. Negative displacements
shift to the right.
The following identity holds true:
assert( bit32.lrotate(x, disp) == bit32.lrotate(x, disp%32) )
bit32.rshift
rshift(x,disp)

This is a Lua builtin function which returns the number x shifted disp bits to the
right (logical right shift). The number disp may be any integer. Negative
displacements shift to the left.
In both directions vacant bits are filled with zeros. Displacements with absolute
values greater than 31 result in zero as all bits have been shifted out.
For positive displacements the following equality is true:
assert( bit32.rshift(x,disp) == math.floor(x % 2^32 / 2^disp) )
bit32.rrotate
rrotate(x,disp)

This is a Lua builtin function which returns the number x rotated disp bits to the
right (logical left shift). The number disp may be any integer. Negative
displacements shift to the left.
The following identity holds true:
assert( bit32.rrotate(x, disp) == bit32.rrotate(x, disp%32) )
Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 45
bit32.bnot
bnot( x )

This is a Lua builtin function which returns the bitwise negation of x. for any integer
x the following holds:
assert( bit32.bnot(x) == (-1 - x ) % 2^32)
bit32.replace
replace(n, v, field [, width] )

This is a Lua builtin function which returns a copy of n with the bits from v in the bit
positions field to field + width -1. Bits are numbered from 0 (least significant) to 31
(most significant). All accessed bits must be in the range [0,31]. The default for width
is 1.
print( bit32.replace(-1, 0, 7)); -- 4294967167 (bit 7 set to 0, other bits 1)
print( bit32.replace(0, -1, 7, 4)); -- 1920 (bits 7-10 set to 1, other bits 0)
print( bit32.replace(1+4+8+32, 6, 2, 3)); -- 57 (bits 2-4 =011 replaced with 110 )
bit32.bor
bor( )

This is a Lua builtin function which returns the bitwise or of its operands.
print( bit32.bor(5,7)); -- 7
print( bit32.bor(3,5,15)); -- 15
print( bit32.bor(-1,5,15)); -- 4292967295
bit32.btest
btest( )

This is a Lua builtin function which returns a Boolean indicating if the bitwise and
of its operands is not zero.
print( bit32.btest(1+4+8+32, 8+16) ) -- true
print( bit32.btest(1+4+8+32, 2+16) ) -- false
print( bit32.btest((1+4+8+32, -1) ) -- true (are any bits set?)
Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 46
The Debug Library
This library provides the functionality of the debug interface to Lua programs. You
should exert care when using this library. Several of its functions violate basic
assumptions about Lua code (e.g., that variables local to a function cannot be
accessed from outside; that userdata metatables cannot be changed by Lua code; that
Lua programs do not crash) and therefore can compromise otherwise secure code.
Moreover, some functions in this library may be slow.
All functions in this library are provided inside the debug table. All functions that
operate over a thread have an optional first argument which is the thread to operate
over. The default is always the current thread.

debug.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.
debug.gethook
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).
debug.getinfo
getinfo( [thread,] f [, what] )

Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 47
This Lua built in function returns a table with information about a function. You can
give the function directly or you can give a number as the value of f, which means
the function running at level f of the call stack of the given thread: level 0 is the
current function (getinfo itself); level 1 is the function that
called getinfo (except for tail calls, which do not count on the stack); and so on.
If f 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
namedactivelines 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
expressiondebug.getinfo(print) returns a table with all available
information about the print function.
debug.getlocal
getlocal( [thread, ] f, local)

This function returns the name and the value of the local variable with
index local of the function at level f of the stack. This function accesses not only
explicit local variables, but also parameters, temporaries, etc.
The first parameter or local variable has index 1, and so on, until the last active
variable. Negative indices refer to vararg parameters; -1 is the first vararg parameter.
The function returns nil if there is no 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 parenthesis) represent internal variables (loop
control variables, temporaries, varargs, and C function locals).
The parameter f may also be a function. In that case, getlocal returns only the
name of function parameters.
debug.getmetatable
getmetatable( value )

Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 48
This is a Lua builtin function that returns the metatable of the given value or nil if
it does not have a metatable.
debug.getregistry
getregistry()

Lua builtin function that returns the registry table.
debug.getupvalue
getupvalue( f, up )

This is a Lua builtin function that returns the name and the value of the upvalue
with index up of the function f. The function returns nil if there is no upvalue with
the given index.
debug.getuservalue
getuservalue( u )

Lua builtin function that returns the Lua value associated to u. If u is not a userdata,
returns nil.
debug.sethook
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:
'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.
Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 49
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" (or "tail call"), "return", "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).
debug.setlocal
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.
See debug.getlocal for more information about variable indices and names.
debug.setmetatable
setmetatable( value, table )

This is a Lua builtin function that sets the metatable for the given value to the
given table (which can be nil). Returns value.
debug.setupvalue
setupvalue(f, u, value)

This function assigns the value value to the upvalue with index up of the
function f. The function returns nil if there is no upvalue with the given index.
Otherwise, it returns the name of the upvalue.
Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 50
debug.setuservalue
setuservalue( udata, value)

This Lua builtin function sets the given value as the Lua value associated to the
given udata. value must be a table or nil; udata must be a full userdata.
Returns udata.

debug.traceback
traceback( [thread, ] message [, level] )

If message is present but is neither a string nor nil, this function
returns message without further processing. Otherwise, it 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).
debug.upvalueid
upvalueid( f, n)

This Lua builtin function returns an unique identifier (as a light userdata) for the
upvalue numbered n from the given function.
These unique identifiers allow a program to check whether different closures share
upvalues. Lua closures that share an upvalue (that is, that access a same external
local variable) will return identical ids for those upvalue indices.
debug.upvaluejoin
upvaluejoin( f1, n1, f2, n2 )

Make the n1-th upvalue of the Lua closure f1 refer to the n2-th upvalue of the
Lua closure f2.
Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 51

os.clock
clock()

Returns an approximation of the amount in seconds of CPU time used by the
program.
os.date
date( [format [, time] ] )

Returns a string or a table containing date and time, formatted according to the
given string format.
If the time argument is present, this is the time to be formatted (see
the os.time function for a description of this value). Otherwise, date formats the
current time.
If format starts with '!', then the date is formatted in Coordinated Universal Time.
After this optional character, if format is the string "*t", then date returns a table
with the following fields: year (four digits), month (112), day (131), hour (0
23), min (059), sec (061), wday (weekday, Sunday is 1), yday (day of the year),
andisdst (daylight saving flag, a boolean). This last field may be absent if the
information is not available.
If format is not "*t", then date returns the date as a string, formatted according
to the same rules as the ANSI C function strftime.
When called without arguments, 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")).
On non-Posix systems, this function may be not thread safe because of its reliance on
C function gmtime and C function localtime.
os.difftime
difftime( t2, t1 )

Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 52
Returns the number of seconds from time t1 to time t2. In POSIX, Windows, and
some other systems, this value is exactly t2-t1.
t1 = os.time();
select * from ipe_command;
print(os.difftime(os.time(), t1));
os.execute
execute( [command] )

This function is equivalent to the ANSI C function system. It passes command to
be executed by an operating system shell. Its first result is true if the command
terminated successfully, or nil otherwise. After this first result the function returns a
string and a number, as follows:
"exit": the command terminated normally; the following number is the exit status
of the command.
"signal": the command was terminated by a signal; the following number is the
signal that terminated the command.
When called without a command, os.execute returns a boolean that is true if a
shell is available.
print(os.execute(), " \n"); -- true
a,b,c = os.execute("dir");
if a then
if b=="exit" then
print("exited normally with return code " .. c .. "\n");
else
print("signal return code " .. c .. "\n");
end
end
os.exit
exit( [code [, close]] )

Within Console it causes a os.exit() error to be generated and the script stopped.
Within the KogScript command line tool calls the ANSI C function exit(int) to
terminate the host program. If code is true, the returned status is EXIT_SUCCESS;
if code is false, the returned status is EXIT_FAILURE; if code is a number, the
returned status is this number. The default value for code is true.
If the optional second argument close is true, closes the Lua state before exiting.
Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 53
os.exit(); --

os.getenv
getenv( varname )

Returns the value of the process environment variable varname, or nil if the
variable is not defined.
print(os.getenv("PATH"));
os.remove
remove( filename )

Deletes the file (or empty directory, on POSIX systems) with the given name. If this
function fails, it returns nil, plus a string describing the error and the error code.
os.rename
rename( oldname, newname )
Renames file or directory named oldname to newname. If this function fails, it
returns nil, plus a string describing the error and the error code.
os.setlocale
setlocale( locale, category )

Sets the current locale of the program. locale is a system-dependent string
specifying a locale; category is an optional string describing which category to
change:"all", "collate", "ctype", "monetary", "numeric", or "time";
the default category is "all". The function returns the name of the new locale,
or nil if the request cannot be honored.
If locale is the empty string, the current locale is set to an implementation-defined
native locale. If locale is the string "C", the current locale is set to the standard C
locale.
Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 54
When called with nil as the first argument, this function only returns the name of
the current locale for the given category.
This function may be not thread safe because of its reliance on
C function setlocale.
os.time
time( [table] )

Returns the current time when called without arguments, or a time representing the
date and time specified by the given table. This table must have
fields year, month, andday, and may have fields hour (default is
12), min (default is 0), sec (default is 0), and isdst (default is nil). For a
description of these fields, see the os.date function.
The returned value is a number, whose meaning depends on your system. In POSIX,
Windows, and some other systems, this number counts the number of seconds since
some given start time (the "epoch"). In other systems, the meaning is not specified,
and the number returned by time can be used only as an argument
to os.date and os.difftime.
os.tmpname
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 POSIX systems, 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).
When possible, you may prefer to use read( )

Equivalent to io.input():read().
io.tmpfile, which automatically removes the file when the program ends.
Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 55
math.modf
modf( x )

Lua builtin function which returns two numbers, the integral part of x and the
fractional part of x.
a,b = math.modf( 3.14 )
print(a, b, "\n"); -- 3 0.14
math.asin
asin( x )

Lua builtin function which returns the arc sine of x (in radians).
a = math.asin( 1 )
b = math.sin( a );
print(math.pi/2, a, b, "\n"); -- 1.5707963267949 1.5707963267949 1
math.tan
tan( x )

Lua builtin function which returns the tangent of x (assumed to be in radians).
a = math.atan( 1 )
b = math.tan( a );
print(math.pi/4, a, b, "\n"); -- 0.78539816339745 0.78539816339745 1
math.exp
exp( x )

Lua builtin function which returns the value e
x
.
a = math.exp( 3)
b = math.log( a )
print(a, b, "\n"); -- 20.085536923188 3
Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 56
math.atan
atan( x )

Lua builtin function which returns the arc tangent of x (in radians).
a = math.atan( 1 )
b = math.tan( a );
print(math.pi/4, a, b, "\n"); -- 0.78539816339745 0.78539816339745 1
math.acos
acos( x )

Lua builtin function which returns the arc cosine of x (in radians).
a = math.cos( 0 )
b = math.acos( a )
print(a, b, "\n"); -- 1 0
math.max
max( x, )

Lua builtin function which returns the maximum value among its arguments.
a = math.min( 1, 2.1, 0.55 )
b = math.max( 1, 2.1, 0.55 )
print(a, b, "\n"); -- 0.55 2.1
math.min
min( x, )

Lua builtin function which returns the minimum value among its arguments.
a = math.min( 1, 2.1, 0.55 )
b = math.max( 1, 2.1, 0.55 )
print(a, b, "\n"); -- 0.55 2.1
Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 57
math.deg
deg( x )

Lua builtin function
a = math.rad( 55 )
b = math.deg( a )
print(a, b, "\n"); -- 0.95993108859688 55
math.randomseed
randomseed( x )

Lua builtin function which sets x as the "seed" for the pseudo-random generator:
equal seeds produce equal sequences of numbers.
math.pow
pow( x, y )

Lua builtin function which returns x
y
. (You can also use the expression x^y to
compute this value.)
a = math.pow( 3, 5 )
b = 3^5
print(a, b, "\n"); -- 243 243
math.ceil
ceil( x )

Lua builtin function which returns the smallest integer larger than or equal to x.
a = math.ceil( 3.14)
b = math.ceil( -3.14)
print(a, b, "\n"); -- 4 -3
math.floor
floor( x )
Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 58

Lua builtin function which returns the absolute value of x.
a = math.floor( 3.14)
b = math.floor( -3.14)
print(a, b, "\n"); -- 3 -4
math.abs
abs( x )

Lua builtin function
a = math.abs( 3.14)
b = math.abs( -3.14)
print(a, b, "\n"); -- 3.14 3.14
math.cosh
cosh( x )

Lua builtin function which returns the hyperbolic cosine of x.
math.sin
sin( x )

Returns the sine of x (assumed to be in radians).
a = math.asin( 1 )
b = math.sin( a );
print(math.pi/2, a, b, "\n"); -- 1.5707963267949 1.5707963267949 1

math.frexp
frexp( x )

Lua builtin function which returns m and e such that x = m2
e
, e is an integer and the
absolute value of m is in the range [0.5, 1) (or zero when x is zero).
Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 59
m, e = math.frexp( 5.5 )
a = math.ldexp( m, e )
print(m, e, a, "\n"); -- 0.6875 3 5.5
math.random
random( [ m [, n] ] )
This function is an interface to the simple pseudo-random generator
function rand provided by Standard 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].
math.sinh
sinh( x )

Lua builtin function which returns the hyperbolic sine of x.
math.tanh
tanh( x )

Lua builtin function which returns the hyperbolic tangent of x.
math.ldexp
cos( m, e )

Lua builtin function which returns m2
e
(e should be an integer).
a = math.ldexp( 5, 2 )
b = math.ldexp( -1, 8 )
print(a, b, "\n"); -- 20 -256
Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 60
math.cos
cos( x )

Lua builtin function which r eturns the cosine of x (assumed to be in radians).
a = math.cos( 0 )
b = math.acos( a )
print(a, b, "\n"); -- 1 0

math.log
log( x [, base] )

Lua builtin function which returns the logarithm of x in the given base. The default
for base is e (so that the function returns the natural logarithm of x).
a = math.exp( 3)
b = math.log( a )
e = math.exp( 1 )
c = math.log( a, e )
d = math.log( 100, 10)
print(a, b, c, d, "\n"); -- 20.085536923188 3 3 2

math.atan2
atan2( x )

Returns the arc tangent of y/x (in radians), but uses the signs of both parameters to
find the quadrant of the result. (It also handles correctly the case of x being zero.)
a = math.atan2( -1, 0 )
b = math.atan2( 1, 0 )
c = math.atan2( 0, -1 )
print(a, b, c, "\n"); -- -1.5707963267949 1.5707963267949 3.1415926535898
math.fmod
fmod( x, y )

Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 61
Lua builtin function which Returns the remainder of the division of x by y that
rounds the quotient towards zero.
a = math.fmod( 5, 2 )
b = math.fmod( -5, 2 )
print(a, b, "\n"); -- 1 -1
math.sqrt
sqrt( x )

Lua builtin function which returns the square root of x. (You can also use the
expression x^0.5 to compute this value.)
a = math.sqrt( 2 )
b = 2^0.5
c = a * a
print(a, b, c, "\n"); -- 1.4142135623731 1.4142135623731 2
math.rad
rad( x )

Lua builtin function which returns the angle x (given in degrees) in radians.
a = math.rad( 90 )
print(math.pi/2, a, "\n"); -- 1.5707963267949 1.5707963267949
Input / output library
The I/O library provides two different styles for file manipulation. The first one uses
implicit file descriptors; that is, there are operations to set a default input file and a
default output file, and all input/output operations are over these default files. The
second style uses explicit file descriptors.
When using implicit file descriptors, all operations are supplied by table io. When
using explicit file descriptors, the operation io.open returns a file descriptor and
then all operations are supplied as methods of the file descriptor.
The table io also provides three predefined file descriptors with their usual
meanings from C: io.stdin, io.stdout, and io.stderr. The I/O library
never closes these files.
Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 62
Unless otherwise stated, all I/O functions return nil on failure (plus an error
message as a second result and a system-dependent error code as a third result) and
some value different from nil on success. On non-Posix systems, the computation of
the error message and error code in case of errors may be not thread safe, because
they rely on the global C variable errno.
io.flush
flush()

Equivalent to io.output():flush().
io.lines
lines( [filename ] )

Opens the given file name in read mode and returns an iterator function that works
like file:lines() over the opened 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.
In case of errors this function raises the error, instead of returning an error code.
io.popen
popen( prog [, mode] )

This function is system dependent and is not available on all platforms.
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").
io.stderr
Lua builtin function
Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 63
io.open
flush( 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:
"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.
io.input
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.
io.stdout
Lua builtin function
Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 64
io.stdin
Lua builtin function
io.output
output( [file] )

Similar to io.input, but operates over the default output file.
io.close
close()

Equivalent to file:close(). Without a file, closes the default output file.
io.read
read( )

Equivalent to io.input():read().
io.tmpfile
tmpfile()

This is a Lua builtin function which returns a handle for a temporary file. This file is
opened in update mode and it is automatically removed when the program ends.
io.type
type( obj )

Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 65
This is a Lua builtin function which checks whether obj is a valid file handle. It
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.
io.write
write( )

Equivalent to io.output():write().
file:close
close()

Closes file. Note that files are automatically closed when their handles are
garbage collected, but that takes an unpredictable amount of time to happen.
When closing a file handle created with io.popen, file:close returns the
same values returned by os.execute.

file:flush
flush()

Saves any written data to file.

file:lines
lines( )

Returns an iterator function that, each time it is called, reads the file according to the
given formats. When no format is given, uses "*l" as a default. As an example, the
construction
Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 66
for c in file:lines(1) do body end
will iterate over all characters of the file, starting at the current position.
Unlike io.lines, this function does not close the file when the loop ends.
In case of errors this function raises the error, instead of returning an error code.

file:read()
read( )

Reads the file file, according to the given formats, 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 next line (see below).
The available formats are:
"*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.
"*L": reads the next line keeping the end of line (if present), returning nil on
end of file.
number: reads a string with up to this number of bytes, returning nil on end
of file. If number is zero, it reads nothing and returns an empty string,
or nil on end of file.

file:seek
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:
Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 67
"set": base is position 0 (beginning of the file);
"cur": base is current position;
"end": base is end of file;
In case of success, seek returns the final file position, measured in bytes from the
beginning of the file. If seek 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
callfile: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.

file:setvbuf
setvbuf( mode [, size ] )

Sets the buffering mode for an output file. There are three available modes:
"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 io.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.

file:write
write( )

Writes the value of each of its arguments to file. The arguments must be strings or
numbers.
Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 68
In case of success, this function returns file. Otherwise it returns nil plus a string
describing the error.

String manipulation functions
This library provides generic functions for string manipulation, such as finding and
extracting substrings, and pattern matching. When indexing a string in Lua, the first
character is at position 1 (not at 0, as in C). Indices are allowed to be negative and are
interpreted as indexing backwards, from the end of the string. Thus, the last
character is at position -1, and so on.
The string library provides all its functions inside the table string. It also sets a
metatable for strings where the __index field points to the string table.
Therefore, you can use the string functions in object-oriented style. For
instance, string.byte(s,i) can be written as s:byte(i).
The string library assumes one-byte character encodings.
string.byte (s [, 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. These indices are corrected
following the same rules of function string.sub.
Numerical codes are not necessarily portable across platforms.

string.format
Lua builtin function
string.byte
byte(s [, I [, j] ] )

This is a Lua builtin function to return the byte codes of characters s[i], s[i+i], , s[j].
The default value for i is 1; he default value for j is i. These indices are corrected
following the same rules as string.sub().
a = "abc";
Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 69
print( string.byte(a, 1, 5) ) -- 97 98 99 163
string.gmatch
gmatch( s, pattern )

Returns an iterator function that, each time it is called, returns the next captures
from pattern over the string s. If pattern specifies no captures, then the whole
match is produced in each call.
As an example, the following loop will iterate over all the words from string s,
printing one per line:
s = "hello world from Lua"
for w in string.gmatch(s, "%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 string.gmatch(s, "(%w+)=(%w+)") do
t[k] = v
end
For this function, a caret '^' at the start of a pattern does not work as an anchor, as
this would prevent the iteration.
string.char
char( )

This is is builtin Lua function that returns a string with length equal to the number
of (integer) arguments, in which each character has the internal numerical code
equal to its corresponding argument.
The following identity is true:
assert( string.char( string.byte(a,1, #a) ) == a)

Example:
print(string.char(97, 98, 99, 163) ) -- "abc";
string.lower
lower( s )

Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 70
This is a Lua builtin function to convert a string to lower case. The definition of
lower case depends on the locale.
a = "aBc"
print( string.lower(a) ) -- "abc"
string.upper
upper( s )

This is a Lua builtin function to convert a string to upper case. The definition of
upper case depends on the locale.
a = "aBc"
print( string.upper(a) ) -- "ABC"
string.len
len( s )

This is a Lua builtin function that returns the length of a string. It receives a string
and returns its length. The empty string "" has length 0. Embedded zeros are
counted, so "a\000bc\000" has length 5.
string.sub
Lua builtin function
string.dump
dump( function )

This is a Lua builtin function that returns a binary representation of the function, so
that a subsequent load() on this string returns a copy of the function (but with new
upvalues).
function sq(a) return a*a end -- a function to square numbers
x = string.dump( sq ); -- create a string representation of sq()
sq = nil; -- remove sq()
a = load(x) -- use the string representation of sq() to
-- create a new function a().
print(a(3) ) -- call a() to get 9

Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 71
See also load
string.reverse
reverse( s )

This is a Lua builtin function to reverse a string
a = "123"
print( string.reverse(a) ) -- 321
string.rep
Lua builtin function
string.match
Lua builtin function
string.gsub
gsub( s, 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. The name gsub comes from Global SUBstitution.
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 %d, with d between 1 and 9,
stands for the value of the d-th captured substring. 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 repl is a function, then this function is called every time a match occurs, with all
captured substrings passed as arguments, in order.
In any case, if the pattern specifies no captures, then it behaves as if the whole
pattern was inside a capture.
Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 72
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).
Here are some examples:
x = string.gsub( "hello world", "(%w+)", "%1 %1") -- "hello hello world world"

x = string.gsub( "hello world", "%w+", "%0 %0", 1) -- "hello hello world"

x = string.gsub( "hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
-- "world hello Lua from"

x = string.gsub( "home = $HOME, user = $USER", "%$(%w+)", os.getenv)
-- "home = /home/roberto, user = mikea"

x = string.gsub( "4+5 = $return 4+5$", "%$(.-)%$", function (s)
return load(s)()
end)
-- "4+5 = 9"

local t = {name= "lua", version= "5.2"}
x = string.gsub( "$name-$version.tar.gz", "%$(%w+)", t)
-- "lua-5.2.tar.gz"
string.find
Lua builtin function
Table Manipulation functions
This library provides generic functions for table manipulation. It provides all its
functions inside the table table.
Remember that, whenever an operation needs the length of a table, the table should
be a proper sequence or have a __len metamethod. All functions ignore non-
numeric keys in tables given as arguments.
For performance reasons, all table accesses (get/set) performed by these functions
are raw.
table.__tostring
__tostring( table )

Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 73
This ia a Lua builtin function which converts a table to a standard string
representation
table.concat
concat ( list [, sep [, i [, j] ] ] )

This is a Lua builtin function which given a list where all elements are strings or
numbers, returns the string list[i]..sep..list[i+1] sep..list[j]. The default value
for sep is the empty string, the default for i is 1, and the default for j is #list. If i is
greater than j, returns the empty string.
table.insert
insert ( list, [pos,] value )

This is a Lua builtin function that inserts element value at position pos in list,
shifting up the elements list[pos], list[pos+1], , list[#list]. The default value
for pos is #list+1, so that a call table.insert(t,x) inserts x at the end of list t.
table.pack
pack ( )

A Lua builtin function which returns a new table with all parameters stored into
keys 1, 2, etc. and with a field "n" with the total number of parameters. Note that the
resulting table may not be a sequence.
table.sort
sort ( list [, comp] )

A Lua builtin function which sorts list elements in a given order, in-place,
from list[1] to list[#list]. If comp is given, then it must be a function that
receives two list elements and returns true when the first element must come before
the second in the final order (so that not comp(list[i+1],list[i]) will be
true after the sort). If comp is not given, then the standard Lua operator < is used
instead.
Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 74
The sort algorithm is not stable; that is, elements considered equal by the given order
may have their relative positions changed by the sort.

table.remove
remove ( list [, pos] )

Removes from list the element at position pos, returning the value of the
removed element. When pos is an integer between 1 and #list, it shifts down the
elements list[pos+1], list[pos+2], , list[#list] and erases
element list[#list]; The index pos can also be 0 when #list is 0, or #list
+ 1; in those cases, the function erases the element list[pos].
The default value for pos is #list, so that a call table.remove(t) removes
the last element of list t.
table.unpack
unpack ( list [, i [, j] ] )

Returns the elements from the given table. This function is equivalent to
return list[i], list[i+1], , list[j]
By default, i is 1 and j is #list.
coroutine.create
create ( f )

A Lua builtin function which creates a new coroutine, with body f. f must be a Lua
function. Returns this new coroutine, an object with type "thread".
coroutine.resume
resume ( co [, val1, ] )

Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 75
A Lua builtin function which starts or continues the execution of coroutine co. The
first time you resume a coroutine, it starts running its body. The values val1, ... are
passed as the arguments to the body function. If the coroutine has
yielded, resume restarts it; the values val1, ... are passed as the results from the
yield.
If the coroutine runs without any errors, resume returns true plus any values
passed to yield (if the coroutine yields) or any values returned by the body
function (if the coroutine terminates). If there is any
error, resume returns false plus the error message.

coroutine.running
running ()

A Lua builtin function which returns the running coroutine plus a boolean, true
when the running coroutine is the main one.
coroutine.status
status ( co )

Returns the status of coroutine co, as a string: "running", if the coroutine is
running (that is, it called status); "suspended", if the coroutine is
suspended in a call toyield, or if it has not started running yet; "normal" if
the coroutine is active but not running (that is, it has resumed another coroutine);
and "dead" if the coroutine has finished its body function, or if it has stopped
with an error.
coroutine.wrap
wrap( f )

A Lua builtin function which creates a new coroutine, with body f. f must be a Lua
function. Returns a function that resumes the coroutine each time it is called. Any
arguments passed to the function behave as the extra arguments to resume. Returns
the same values returned by resume, except the first boolean. In case of error,
propagates the error.
Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 76
coroutine.yield
yield ( )

A Lua builtin function which Suspends the execution of the calling coroutine. Any
arguments to yield are passed as extra results to resume.
package.config
This is a Lua builtin string describing some compile-time configurations for
packages. This string is a sequence of lines:
The first line is the directory separator string. Default is '\' for Windows and
'/' for all other systems.
The second line is the character that separates templates in a path. Default is
';'.
The third line is the string that marks the substitution points in a template.
Default is '?'.
The fourth line is a string that, in a path in Windows, is replaced by the
executable's directory. Default is '!'.
The fifth line is a mark to ignore all text before it when building
the luaopen_ function name. Default is '-'.

package.cpath
A Lua builtin string which is the path used by require to search for a C loader.
Lua initializes the C path package.cpath in the same way it initializes the Lua
path package.path, using the environment variable LUA_CPATH_5_2 or the
environment variable LUA_CPATH or a default path defined in Kognitio
Console.

Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 77
package.loaded
A Lua builtin table used by require to control which modules are already loaded.
When you require a module modname and package.loaded[modname] is not
false, require simply returns the value stored there.
This variable is only a reference to the real table; assignments to this variable do not
change the table used by require.

package.loadlib
This is a Lua builtin function which dynamically links the host program with the
C library libname.
If funcname is "*", then it only links with the library, making the symbols exported
by the library available to other dynamically linked libraries. Otherwise, it looks for
a function funcname inside the library and returns this function as a C function.
So, funcname must follow the lua_CFunction prototype
(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 an 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 Standard 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).

package.path
The path used by require to search for a Lua loader.
At start-up, Lua initializes this variable with the value of the environment
variable LUA_PATH_5_2 or the environment variable LUA_PATH or with a default
path defined in Kognitio Console, if those environment variables are not
defined. Any ";;" in the value of the environment variable is replaced by the default
path.
Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 78
package.preload
This is a Lua builtin table to store loaders for specific modules (see require).
This variable is only a reference to the real table; assignments to this variable do not
change the table used by require.

package.searchers
A Lua builtin table used by require to control how to load modules.
Each entry in this table is a searcher function. When looking for a
module, require calls each of these searchers in ascending order, with the module
name (the argument given to require) as its sole parameter. The function can
return another function (the module loader) plus an extra value that will be passed to
that loader, or a string explaining why it did not find that module (or nil if it has
nothing to say).
Lua initializes this table with four searcher functions.
The first searcher simply looks for a loader in the package.preload table.
The second searcher looks for a loader as a Lua library, using the path stored
at package.path. The search is done as described in
function package.searchpath.
The third searcher looks for a loader as a C library, using the path given by the
variable package.cpath. Again, the search is done as described in
functionpackage.searchpath. For instance, if the C path is the string
"./?.so;./?.dll;/usr/local/?/init.so"
the searcher for module foo will try to open the files ./foo.so, ./foo.dll,
and /usr/local/foo/init.so, in that order. Once it finds a C library, this
searcher first uses a dynamic link facility to link the application with the library.
Then it tries to find a C function inside the library to be used as the loader. The name
of this C function is the string "luaopen_" concatenated with a copy of the module
name where each dot is replaced by an underscore. Moreover, if the module name
has a hyphen, its prefix up to (and including) the first hyphen is removed. For
instance, if the module name is a.v1-b.c, the function name will
be luaopen_b_c.
Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 79
The fourth searcher tries an all-in-one loader. It searches the C path for a library for
the root name of the given module. For instance, when requiring a.b.c, it will
search for a C library for a. If found, it looks into it for an open function for the
submodule; in our example, that would be luaopen_a_b_c. With this facility, a
package can pack several C submodules into one single library, with each
submodule keeping its original open function.
All searchers except the first one (preload) return as the extra value the file name
where the module was found, as returned by package.searchpath. The first
searcher returns no extra value.
package.searchpath
This is a Lua builtin function which searches for the given name in the given path.
A path is a string containing a sequence of templates separated by semicolons. For
each template, the function replaces each interrogation mark (if any) in the template
with a copy of name wherein all occurrences of sep (a dot, by default) were
replaced by rep (the system's directory separator, by default), and then tries to open
the resulting file name.
For instance, if the path is the string
"./?.lua;./?.lc;/usr/local/?/init.lua"
the search for the name foo.a will try to open the
files ./foo/a.lua, ./foo/a.lc, and /usr/local/foo/a/init.lua, in
that order.
Returns the resulting name of the first file that it can open in read mode (after
closing the file), or nil plus an error message if none succeeds. (This error message
lists all file names it tried to open.)

2.3 Kog Script std library
string.format
This has been extended to work better with one argument, i.e. no formatting is
attempted and it returns that argument.
Example
Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 80
--print(string.format("%#.2e").."\n") -- gives an error
print(string.format("%#.2e",12.34567).."\n")
require 'std.string'
print(string.format("%#.2e").."\n")
2.4 std.base
This library adds useful functions to Kog scripts.
Example
std = require 'std.base'
std.assert
Extend to allow formatted arguments.

std.assert(v, f, ...)
v value to assert
f format
arguments to format
returns value v

Example
std = require 'std.base'
std.assert(5 == fn(1), 'expected 5, got %d', fn(1));
function fn(a,b,c) return a*100+b*10+c; end
std.bind
Partially apply a function.
std.bind(f, ...)
f function to apply partially
arguments to bind
returns function with arguments already bound

Example
std = require 'std.base'
function fn(a,b,c) return a*100+b*10+c; end
fn1 = std.bind(fn, 1)
fn2 = std.bind(fn, 1,2)
fn3 = std.bind(fn, 1,2,3)
print(fn1(2,3).. '\n') -- 123
print(fn2(3).. '\n') -- 123
Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 81
print(fn3().. '\n') -- 123
std.collect
Collect the results of an iterator.
std.collect(x, i, ...)
x table to hold results
i iterator
parameters to iterator
returns results of running the iterator on its arguments

Example
std = require 'std.base'
t = { { { 'a', e='b' }, {'c'} }, 'd' }
print(std.tostring(std.collect({}, std.leaves, t)) .. '\n') -- {1=a,2=b,3=c,4=d}
std.compose
Compose functions (fn applied first).
std.compose(...)
functions f1 fn to compose
returns composition of f1 fn

Example
std = require 'std.base'
fn1 = function(a) return a*a; end
fn2 = function(a) return a+a; end
fn3 = function(a) return a..a; end
print(std.compose(fn1,fn1)(2) .. "\n") -- 16
print(std.compose(fn1,fn2)(3) .. "\n") -- 36 = (3+3) * (3+3)
print(std.compose(fn3,fn3)("ab") .. "\n") -- abababab
std.concat
Concatenate lists.
std.concat(...)
lists
returns table containing concatenated lists

Example
std = require 'std.base'
print(std.tostring(std.concat({1,'a'},{3},{4}))) -- {1=1,2=a,3=3,4=4}
Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 82
std.curry
Curry a function.
std.curry(f, n)
f function to curry
n number of arguments
returns curried version of f

Example
std = require 'std.base'
function fn(a,b,c) return a*100+b*10+c; end
fn1 = std.curry(fn, 1)
fn2 = std.curry(fn, 2)
fn3 = std.curry(fn, 3)
fn2a = fn2(1)
fn3a = fn3(1)
fn3b = fn3a(2)
print(fn1(1,2,3) .. '\n' ) -- 123
print(fn2(1)(2,3) .. '\n') -- 123
print(fn2a(2,3) .. '\n') -- 123
print(fn3(1)(2)(3) .. '\n') -- 123
print(fn3a(2)(3) .. '\n') -- 123
print(fn3b(3) .. '\n') -- 123
std.die
Print out warning with the name of program and file (if any), then die.
std.die(...)
arguments for warning

Example
std = require 'std.base'
std.die('Error: ', 'should not occur' )
std.eval
Evaluate a string. The opposite of std.pickle().
std.eval(s)
s string
returns value of string

Example
Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 83
std = require 'std.base'
print(std.eval("1+2+3") .. "\n") -- 6
std.filter
Filter an iterator with a predicate.
std.filter(x, p, i, ...)
x table to hold results
p predicate
i iterator
parameters to iterator
returns results of running the iterator on its arguments

Example
std = require 'std.base'
t = { { { 'a', e='b' }, {'c'} }, 'd' }
function fn1(a) return a=='b' end
print(std.tostring(std.filter({}, fn1, std.leaves, t)) .. '\n') -- {1=b}
std.fold
Fold a binary function into an iterator.
std.fold(f, d, i, ...)
f function
d initial value
i iterator
parameters to iterator
returns results of running the iterator on its arguments

Example
std = require 'std.base'
t = { { { 'a', e='b' }, {'c'} }, 'd' }
function fn1(a,b) return a..b end
print(std.tostring(std.fold(fn1, '', std.leaves, t)) .. '\n') -- 'abcd'
std.id
Identity function
std.id(...)
tuple
returns tuple

Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 84
std.ileaves
Tree iterator which returns just numbered leaves, in order.
std.ileaves(tr)
tr tree to iterate over
returns iterator function
returns tree

Example
std = require 'std.base'
t = { { { 'a', e='b' }, {'c'} }, 'd' }
for n in std.ileaves(t) do print(n .. ' ') end -- a c d
std.inodes
Tree iterator over numbered nodes, in order.
std.inodes (tr)
tr tree to iterate over
returns iterator function
returns tree

Example
std = require 'std.base'
t = { { { 'a', e='b' }, {'c'} }, 'd' }
for x,p,n in std.inodes(t) do
if x == 'leaf' then
print(n .. " " )
end
end
-- a c d
std.leaves
Tree iterator which returns all leaves.
std.leaves(tr)
tr tree to iterate over
returns iterator function
returns tree

Example
std = require 'std.base'
t = { { { 'a', e='b' }, {'c'} }, 'd' }
for n in std.leaves(t) do print(n .. ' ') end -- a b c d
Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 85
std.map
Map a function over an iterator.
std.map(x, f, i, ...)
x table to hold results
f function
i iterator
parameters to iterator
returns results of running the iterator on its arguments

Example
std = require 'std.base'
t = { { { 'a', e='b' }, {'c'} }, 'd' }
function fn1(a) return a..a end
print(std.tostring(std.map({}, fn1, std.leaves, t)) .. '\n') -- {1=aa,2=bb,3=cc,4=dd}
std.memoize
Memoize a function, by wrapping it in a functable.
std.memoize(fn)
fn function that returns a single result
returns memoized function

Example
std = require 'std.base'
t = std.memoize( function(a) return a*a; end )
print(t(3) .. "\n" ) -- 9
std.metamethod
Return given metamethod, if any, or nil.

std.metamethod(x, n)
x object to get metamethod of
n name of metamethod to get
returns metamethod function or nil if no metamethod or not a function
std.nodes
Tree iterator; return all the nodes in a tree
std.nodes(tr)
tr tree to iterate over
Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 86
returns iterator function
returns tree

Example
std = require 'std.base'
t = { { { 'a', e='b' }, {'c'} }, 'd' }
for x,p,n in std.nodes(t) do
if x == 'leaf' then
print(n .. " " )
end
end
-- a b c d
std.op
Array containing various operators.
std.op ["[]"] -- index
std.op ["+"] -- Addition
std.op ["-"] -- Subtraction
std.op ["*"] -- Multiplication
std.op ["/"] -- Division
std.op ["and"] -- Boolean and
std.op ["or"] Boolean or
std.op ["not"] -- Boolean negation
std.op ["=="] -- Equality
std.op ["~="] -- Not equals

Example
std = require 'std.base'
print(std.op["[]"]({1,2,3},2) .. '\n') -- 2
std.pack
Turn a tuple into a list.
std.pack(...)
tuple
returns table containing tuple values

Example
std = require 'std.base'
t = std.pack(1, 'a') -- t = { 1, a }
Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 87
std.pickle
Convert a value to a string.
The string can be passed to std.eval to retrieve the value.
std.pickle(x)
x object to pickle
returns string such that eval (s) is the same value as x

Example
std = require 'std.base'
s = std.pickle({ 1, 'a' })
v = std.eval(s) -- v = { 1, a }
std.prettytostring
Pretty-print a table.
std.prettytostring(t, indent, spacing)
t table to print
indent indent between levels ["\t"]
spacing space before every line
returns pretty printed string representation of t

Example
std = require 'std.base'
t = { 1, { 2, 3} }
t2 = { t, { 4}, t }
table.insert(t, t2)
print(std.prettytostring(t)) pretty printed table over several lines
-- {
-- [1] = 1,
-- [2] =
-- {
-- [1] = 2,
-- [2] = 3,
-- },
-- [3] =
-- {
-- [1] = table: 02E7E430,
-- [2] =
-- {
-- [1] = 4,
-- },
-- [3] = table: 02E7E430,
-- },
-- }
Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 88
std.render
Turn tables into strings with recursion detection.
std.render(x, open, close, elem, pair, sep, roots)
x object to convert to string
open open table renderer
close close table renderer
elem element renderer
pair pair renderer
sep separator renderer
returns string representation

Example
std = require 'std.base'
t = { 1, { 2, 3} }
t2 = { t, { 4}, t }
table.insert(t, t2)
print(std.render (t,
function () return "{" end,
function () return "}" end,
_G.tostring,
function (t, _, _, i, v) return i .. "=" .. v end,
function (_, i, _, j)
if i and j then return "," end
return ""
end))
-- {1=1,2={1=2,2=3},3={1=table: 02E7ABF0,2={1=4},3=table: 02E7ABF0}}
std.ripairs
Turn tables into strings with recursion detection.
std.ripairs(t)
t table to iterate over
returns iterator function
returns the table, as above
returns #t + 1
Example
std = require 'std.base'
t = {'a','b','c'}
t2= {}
for i,v in std.ripairs(t) do table.insert(t2,v) end -- t2 = {'c', 'b', 'a'}
Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 89
std.tostring
Extend tostring to work better on tables.
std.tostring(x)
x object to convert to string
returns string representation

Example
std = require 'std.base'
t = { 1, { 2, 3} }
t2 = { t, { 4}, t }
table.insert(t, t2)
print(std.tostring(t))
-- {1=1,2={1=2,2=3},3={1=table: 02E7AE48,2={1=4},3=table: 02E7AE48}}
std.totable
Turn an object into a table according to __totable metamethod.
std.totable(x)
x object to turn into a table
returns table or nil

Example
std = require 'std.base'

getmetatable("").__totable = function (s)
t = {}
for i = 1,#s do
table.insert(t, s[i])
end
return t;
end

t = std.totable("hello")
print( std.tostring(t)) -- {1=h,2=e,3=l,4=l,5=o}
std.warn
Give warning with the name of program and file (if any).
std.warn(...)
arguments for warning

Example
Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 90
std = require 'std.base'
std.warn('Warning: ', 'should not occur' )


std.class
This enables classes to be created
Example
require 'std.class'

Animal = class(function(a,name)
a.name = name
end)

function Animal:__tostring()
return self.name..': '..self:speak()
end

Dog = class(Animal)

function Dog:speak()
return 'bark'
end

Cat = class(Animal, function(c,name,breed)
Animal.init(c,name) -- must init base!
c.breed = breed
end)

function Cat:speak()
return 'meow'
end

Lion = class(Cat)

function Lion:speak()
return 'roar'
end

fido = Dog('Fido')
felix = Cat('Felix','Tabby')
leo = Lion('Leo','African')

if leo:is_a(Cat) then
print ("lions are big Cats\n")
end
print(fido:speak() .. "\n")
print(felix:speak() .. "\n")
print(leo:speak() .. "\n")
Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 91
std.list
2.5 std.strbuf
This module is used to add string buffer functionality for performance. Using a
string buffer may avoid lots of string concatenations, giving a performance
improvement.
Constructor
Constructor StrBuf(param)
Create a Table.
param a string, or value which is converted to a string
return new StrBuf

__concat
Concatenation operation
Example
require 'std.strbuf'
buf = StrBuf( "this" )
buf = buf .. " is" .. " a" .. " strbuf" .. " string" -- each .. is call to __concat()
print(buf)
__tostring
Converts the concatenation buffer into a string
Example
require 'std.strbuf'
buf = StrBuf("this")
buf = buf .. " is" .. " a" .. " strbuf" .. " string"
print(buf) - call to __tostring()
2.6 std.string
This module adds extra string functions to _G.string
Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 92
..
Concat method, this converts the second parameter to a string.
Example
require 'std.string'
t = {1, 'a'}
print("table= " .. t.. "\n " )
[ ]
Concat method, this converts the second parameter to a string.
Example
require 'std.string'
s = "abc"
print("b= " .. s[2].. "\n ")
caps
Capitalise each word in a string
Example
require 'std.string'
s = "a string to capitalise"
print(s:caps())
chomp
Remove any final newline from a string.
Example
require 'std.string'
s = "remove newline\n"
print(s:chomp()=="remove newline ", " \n")

escapePattern
Escape a string to be used as a pattern.
Example
Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 93
require 'std.string'
s = "%me"
print(s:escapePattern() .. "\n" )

escapeShell
Escape a string to be used as a shell token.
Quotes spaces, parentheses, brackets, quotes, apostrophes and whitespace.
Example
require 'std.string'
s = [[% in mike's "string" indexed by [] is (very) complex]]
print(s:escapeShell(), " \n")
find_as_list
Do find, returning captures as a list.
Where:
s target string
p pattern
init start position (default: 1)
plain inhibit magic characters (default: nil)

returns: start of match, end of match, table of captures
Example
require 'std.string'
require 'std.table'
from,to,t = string.find_as_list("a string to pack", "(%w+)", 4)
print(from, to, std.tostring(t))
finds
Do find, returning captures as a list.
Where:
s target string
p pattern
init start position (default: 1)
plain inhibit magic characters (default: nil)

returns: list of {from, to, capt = {captures}}
Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 94
Example
require 'std.string'
require 'std.table'
t = string.finds("a string to pack" , "(%w+)", 4)
print(std.tostring(t).. "\n")
for i,v in pairs(t) do print(v.capt[1].."\n") end
gsubs
Perform multiple calls to gsub.
Where:
s string to call gsub on
sub {pattern1=replacement1 ...}
n upper limit on replacements (default: infinite)

returns: result string, number of replacements made
Example
require 'std.string'
s = "abcdabebabc"
print(s:gsubs({ab='xx', c='yy'} ) )
ltrim
Trims of leading whitespace from the left of a string
Example
require 'std.string'
s = " string with trailing "
print('"' .. s:ltrim() .. '"\n')
numbertosi
Write a number using SI suffixes. The number is always written to 3 significant
figures.
Example
require 'std.string'
print(string.numbertosi(1.23456))
Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 95
ordinalSuffix
Return the English suffix for an ordinal.
Example
require 'std.string'
for i=1,30 do print(i .. string.ordinalSuffix(i) .. "\n" ); end
pad
Justify a string.
When the string is longer than w, it is truncated (left or right according to the sign of
w).
Example
require 'std.string'
s = "y"
print( '"' .. s:pad(5) .. '"' ..string.pad("1234567" ,3) .. s:pad(5, '.') .. s:pad(-5,'-') .. "\n")
rep
Repeat a string
Example
require 'std.string'
print(string.rep("abc",5) .. "\n")
rtrim
Trims of trailing whitespace from the right of a string
Example
require 'std.string'
s = " string with trailing "
print('"' .. s:rtrim() .. '"\n')
trim
Trims of leading and trailing whitespace from a string
Example
Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 96
require 'std.string'
s = " string with trailing "
print('"' .. s:trim() .. '"\n')
wrap
Wrap a string into a paragraph
Example
require 'std.string'
s = "Wrap a string into a paragraph. string.wrap(s, w, ind, ind1). Where s string
to wrap, w width to wrap to (default: 78), ind indent (default: 0) and ind1 indent
of first line (default: ind) returning the wrapped paragraph"
print(string.wrap(s, 50, 5, 10))

2.7 std.Table
Table extends built-in table support with a few common functions. These are both class
based (Table) and part of the table package

Constructor
Constructor Table(param)
Create a Table.
param a Table, table or value
return new Table with values set to those of the Table or table or the
value

clone
function Table:clone() function table.clone(t)
Returns a new table (with the same metadata) containing the same index, value pairs
as the original table.
t table
return table containing a cloned version of t

Example
Table = require 'std.table'
t = { a=1, b='x', c='zz'}
x = Table(t)
t2 = table.clone(t)
x2 = x:clone()
Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 97
print("t=" .. t .. ", t2=" .. t2 .. "\n")
print("x=" .. x .. ", x=" .. x2 .. "\n")

clone_rename
function Table:clone_rename(map) function table.clone(t,map)
Returns a new Table (with the same metadata) containing the same index, value
pairs as the original table, except that the map is used to rename values to new
indexes.

Example
Table = require 'std.table'
map = { 1=2, 2=3, 3=4, 4=1 }
x = Table({'a', 'b', 'c', 'd'})
print("x=" .. x .. ", x=" .. x:clone_rename(map) .. "\n")

map = { p='w', q='x', r='y', s='z'}
x = Table({ p='a', q='b', r='c', s='d'})
print("x=" .. x .. ", y=" .. x:clone_rename(map) .. "\n")

empty
function Table:empty() function table.empty(t)
Returns true if the table contains no entries
t table
return boolean true if table is empty

Example
Table = require 'std.table'
t = { 3, 2, 3, 5, 1}
t2 = { }
x = Table(t)
print("t empty=" .. table.empty(t) .. ", t2 empty=" .. table.empty(t2) .. "\n")
print("x empty=" .. x:empty() .. "\n")
indices
function Table:indices() function table.indices(t)
Returns a new table (with the same metadata) containing the indices of the original
table.
t table
return table containing indices of table parameter

Example
Table = require 'std.table'
t = { a=1, b='x', c='zz'}
Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 98
x = Table(t)
print("t indices=" .. table.indices(t) .. "\n")
print("x indices=" .. x:indices() .. "\n")
insert
function Table:insert(v) function table.insert(t,v)
Returns the table with the value
t table
v value to insert into table t
return table t

Example
Table = require 'std.table'
t = { 1, 2, 3 }
x = Table(t)
print("t.insert(4)=" .. table.insert(t,4) .. "\n")
print("x.insert(4)=" .. x:insert(4) .. "\n")

invert
function Table:invert() function table.invert(t)
Returns a new table (with the same metadata) containing v=i, for all i=v in the
original table.
t table
return table containing inverted t

Example
Table = require 'std.table'
t = { a=1, b='x', c='zz'}
x = Table(t)
print("t invert=" .. table.invert(t) .. "\n")
print("x invert=" .. x:invert() .. "\n")
merge
function Table:merge(u) function table.merge(t, u)
Merge the values of table u into table t, if the index of a value in u exists in t then the
value in t is overwritten.
t table
u second table
return first table

Example
Table = require 'std.table'
t = { 3, 2, 3, 5, 1}
Public Chapter 2 - Error! Reference source not found.
Console Scripting Guide 99
t2 = {6, 5, 'b'}
x = Table(t)
x2 = Table(t2)
print("merged table=" .. table.merge(t,t2) .. "\n")
print("merged table=" .. x:merge(x2) .. "\n")
pack
function Table:pack() function table.pack(t,)
Returns a new table (with the same metadata) containing v=i, for all i=v in the
original table.
t table
more tables
return table containing all the table parameters and n the number of
tables

Example
Table = require 'std.table'
t = { a=1, b='x', c='zz '}
t2 = { a=1, b='x', c='zz'}
x = Table(t)
print("pack(t,t2,t2)=" .. table.pack(t,t2,t2) .. "\n")
print("x:pack(t2,x)=" .. x:pack(t2,x) .. "\n")
remove
function Table:remove(i) function table.remove(t,i)
Returns the table with the value at index i removed.
t table
i index to remove
return table t with index i removed.

Example
Table = require 'std.table'
t = { 'a', 'b', 'c'}
x = Table(t)
print("remove(t,2)=" .. table.remove(2) .. "\n")
print("x:remove(2)=" .. x:remove(2) .. "\n")
sort
function Table:sort(c) function table.sort(t, c)
Sort the Table
t table
c comparator function
return sorted table

Chapter 2 - Error! Reference source not found. Public
Console Scripting Guide 100
Example
Table = require 'std.table'
t = { 3, 2, 3, 5, 1}
x = Table(t)
print("sorted table=" .. table.sort(t) .. "\n")
print("sorted table=" .. x:sort() .. "\n")
print("rsorted table=" .. x:sort(function(a,b) return a > b end) .. "\n")
values
function Table:values() function table.values(t)
Returns a new table (with the same metadata) containing the values of the original
table.
t table
return table containing values of table parameter

Example
Table = require 'std.table'
t = { a=1, b='x ', c='zz '}
x = Table(t)
print("t values=" .. table.values(t) .. "\n")
print("x values=" .. x:values() .. "\n")




Console Scripting Guide 101
3

Using Old Style SQL Scripts In Macros
Up until October 2012 old style SQL scripts where the only script implemented in Kognitio
Console. Since then Kognitio Scripts (based on Lua) are also implemented and are now the
default in future as they are much more powerful.
SQL scripts as implemented by Kognitio Console have a sub-set of the commands which are
implemented in WxSubmit command line tool. The KogScript command line tool is primarily
designed to run Kognitio Scripts (based on Lua), but may also be used to run SQL scripts as
well, it uses the same scripting engine as Kognitio Console.
The old style SQL script commands are given below. Within old style XML macros these
may be run in the <script> tag.
Variables

A sequence of non-space characters starting with a letter.
Variables are substituted when preceded by a $

<variable>
script variable name
<varref>
'$'<variable>

Examples:
set var x 10;
if $x <20 goto loop;
Chapter 3 - Using Old Style SQL Scripts In Macros Public
Console Scripting Guide 102
set var schema sys;
set var tbl ipe_user;
select * from $schema.$tbl

Assignment
<variable> '=' <value> ';'

Not implemented


Connect statement
'connect' 'to' <server> 'user' <username> [ 'using' | 'password' ] <password>

Examples:
connect to kog_10 user sys using mySecretPassword;
connect to kog_5 user john password wibble54;


Describe Command
Executes Kognitio analytics platform SQL describe syntax.

Disconnect Statement
'disconnect'


Edit Command
Not implemented, this is only useful for WxSubmit.

Errorcode Command
Not implemented, only relevant for WxSubmit

Public Chapter 3 - Using Old Style SQL Scripts In Macros
Console Scripting Guide 103
Errorcodenot Command
Not implemented, only relevant for WxSubmit
Export Command
'export' 'from' <something>
'export' <anything else> -- not implemented

Executes Kognitio analytics platform SQL export from syntax.

Goto Command
'goto' <label> [:] ;

Examples:
set var n 0
loop:
.
select $n + 1
set var n $col1
if $n < 10 goto loop;

Help Command
Not implemented

If Statement
'if' <varref> <cmp> <varref> <command>

<cmp>
'=': equality
'==': equality
'!=': not equals
'>': greater than
'<': less than
'>=': greater than or equals
'<=': less than or equals

If both variables are integers then do an integer comparison, otherwise treat both variables as
strings and do a string comparison

Chapter 3 - Using Old Style SQL Scripts In Macros Public
Console Scripting Guide 104
Include Command
'include' <filename>

<filename>
stringWithoutSpaces
string with spaces
string with spaces

Script variables which are set in the base script are passed to the included script. This allows
simple function-like behaviour.
NOTE: variables set in the included script are not visible to the base script.

Example:
base.scr
set var name 'john';
include included.scr;
set var name 'sue';
include included.scr;

included.scr
select * from sys.ipe_user where name=$name;

Results Command
Not implemented, only relevant for WxSubmit

Returncode Command
Not implemented, only relevant for WxSubmit

Set Statement
'set {'var' | 'variable'} <variable> [<value>] ';'
'set' 'prompt' <variable> <type> <prompt> ';'
'set' 'mode' {'transaction' | 'autocommit'} ';'
'set' 'schema' <schema name> ';'
'set' 'time' 'zone' { <interval> | 'local' }
'set' 'blanklineterm' <number> ';'


<value>
string (may include spaces, newlines) up to ';'
<type>
'NUMBER': only allow numbers in the variable
'CHAR': the variable can be any sequence of characters
Public Chapter 3 - Using Old Style SQL Scripts In Macros
Console Scripting Guide 105
<prompt>
String to show to the user

Set schema and set time zone are WX2 SQL commands all the rest are script commands
implemented in Kognitio Console.

NOTE: blanklineterm is not fully implemented, setting it to values other than 0 will not cause
SQL statements to be terminated by blank lines.

Examples
set var x 10; -- x == 10
set var schema sys; -- schema == sys
set var tbl ipe_user; -- tbl == ipe_user
set var n from sys.ipe_user; -- n == from sys.ipe_user
set var m from $schema.$tbl; -- m == from sys.ipe_user
set prompt x NUMBER Enter count; -- ask user to supply value for count
set prompt tbl CHAR Table to update;-- ask user to supply table name
set mode transaction; -- set the database into transaction mode
set mode autocommit; -- set the database into autocommit mode
set schema mike; -- set default schema to mike
set time zone local; -- set the time zone to the local timezone
set time zone -7:00; -- set the time zone to 7 hours behind UTC
set blanklineterm 0; -- blank lines do not terminate SQL statements

Setvar Command
Not implemented

Shell Command
'shell' <string> ';'
<string>
"char sequence not including double quote"
'char sequence not including single quite'

The shell command executes a string as an operating system shell script command.
On MS Windows each command has to be in a separate shell command like:
shell 'cmd.exe /C help';
shell 'cmd.exe /C pwd';

On MS Windows it is not possible to change the working directory by:
shell 'cmd.exe /C cd C:\somepath'; -- does not work
shell 'cmd.exe /C pwd'; -- working directory unchanged

Instead use:
set var shell_dir C:\somepath;
shell 'cmd.exe /C pwd'; -- working directory set to c:\somepath

Example:
Chapter 3 - Using Old Style SQL Scripts In Macros Public
Console Scripting Guide 106

base_cmd.sql
shell 'cmd.exe /C pwd';

set var shell_dir C:\cygwin;
set var shell_test 'test1';
include included_cmd.sql;

set var shell_dir C:\program files;
set var shell_test 'test2';
include included_cmd.sql;

include_cmd.sql
select $shell_test;
shell "cmd.exe /C pwd";

Show Command
Not implemented. There is no need to have a command show the value of variables in Kognitio
Console, the script variables pane does that.

Whenever Statement
'whenever' {'sqlerror'|'oserror'} <perform-action> [<transaction-behaviour>]

<perform-action>
'continue success': don't increment error count
'continue failure': increment the error count
'continue': as 'continue' failure which is the default.
'exit success': on error, exit with code 0.
'exit failure': on error, exit with code 1.
'exit <exit-code>': on error, exit with code <exit-code>.
'exit': as 'exit success'.
<transaction-behaviour> (only relevant in transaction mode)
'commit': commit the transaction.
'rollback': roll back the transaction.
'none': do not change the transaction state. this is the default if
the transaction behaviour is not specified

Examples

Quit Command
'quit'

Stop script execution

Public Chapter 3 - Using Old Style SQL Scripts In Macros
Console Scripting Guide 107
Examples
select * from sys.ipe_system
if $numrows <> 1 quit;

Script variables
The Kognitio script engine creates various variables automatically. These may be used in the
same places as script variables created by the set command.

"SQLState" default= "OK" set to on error
"WCSerror" default= "OK" Kognitio analytics platform error code
"NumRows" default= "" number of rows returned by last query
"NumColumns" default= ""
"Col1" default= "" column names of first five columns
"Col2" default= ""
"Col3" default= ""
"Col4" default= ""
"Col5" default= ""
"QueryNumber" default= "0"
"CompileTime" default= "0"
"ExecuteTime" default= "0"
"FirstRowTime" default= "0"
"TotalTime" default= "0"
"SQLStateStr" default= "'OK'" string versions of "SQLState
"WCSerrorStr" default= "'OK'" string version of WCSerror
"Col1Str" default= "''"
"Col2Str" default= "''"
"Col3Str" default= "''"
"Col4Str" default= "''"
"Col5Str" default= "''"

Server version variables:

"sysver"; e.g. 07.02.0001
"sysverStr"; e.g. 07.02.0001
"cliver"; client (Console) version, e.g. 07.02.02-s120531
"cliverStr"; e.g. 07.02.02-s120531

Script Variables used by console:

"history_mode values of "none, "all, "sql, "script";
"history_group" some string used for grouping queries in the query history tab
"error_mode" values of "stop, "continue, "debug"
What to do on encountering an error in a SQL statement

"script_fail_mode" values of "stop, "continue, "debug"
What to do on encountering an error in a script statement( if, goto,
etc.)

"fail_mode" values of "stop, "continue, "debug"
What to do on encountering an error in a script test command (
Chapter 3 - Using Old Style SQL Scripts In Macros Public
Console Scripting Guide 108
test commonada are not implemented in Console at present).

Example 1:
This example shows a SQL script being run from the menu My Scripts ->
Included Script
<?xml version="1.0" encoding="UTF-8"?>
<wx2macro type="objectaction">

<name>IncludedTest</name>
<menu position="2">My Scripts</menu>
<actiontext>Included Script</actiontext>

<script>
include "some-script.sql";
</script>

</wx2macro>

Console Scripting Guide 109

A
Index
No index entries found.

Anda mungkin juga menyukai