Kognitio Console Scripting Guide
-
Upload
paresh-morker -
Category
Documents
-
view
58 -
download
0
description
Transcript of Kognitio Console Scripting Guide
-
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:
[ ; ] [ ; ]
Where:
= continue, stop, debug or exit, default=continue
= rollback, commit or none,
default=none
=success, failure or failure=n,
default=success
On Console the 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.
$[ ( ) ] [ | ' | $ | ;|, ]
Where: ::= ', ' | '\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 ( ) .
$( ) [ ]
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.Atkinson\.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\wx2console\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//lib/lua/?.lua;/opt/Kognitio/wx2//lib/kog?.kog;
to the search path.
Standard Library Location
Linux server install ( linux-install-.sfx ):
/opt/Kognitio/wx2//lib/lua/std
Linux client tools install ( wx2-linux-clients.tar.gz ):
/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 [ ]
Convert 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_mode='exit;failure='
-
Console Scripting Guide xxv
Convert 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 (3rd, 4th) 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 (-251,+251); each argument is normalized to the remainder of its division by 232 and truncated to an integer (in some unspecified way), so that its final value falls in the range [0,232 - 1]. Similarly, all results are in the range [0,232 - 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