Main
Language
Runtime
Tools
FAQs
Changes
Download
Licence
cheesy

The Idle Runtime Library

This is the preliminary documentation for the Idle standard runtime library. All global variables, functions and other items fall into one of the following categories:

Note: if you find errors, omissions, obscurity or even simple typos... please send a short bug report to idle.script@gmail.com or idle.script@idle.thomaslauer.com. Getting the documentation up to scratch is high on my list of priorities!

Additional Library Modules
top of page

A few additional modules are not part of the Idle standard library. These modules are installed as separate packages (which means, among other things, that you have to explicitly require() them, unlike the modules in the Idle standard library). The additional modules include the following:

There's also the documentation for the Idle Language itself. And you can go back to the main documentation file.

Core Library
top of page

The Idle core library provides basic primitives. All functions and variables can be used 'right out of the box', without prefix and without require()ing other modules.

apairs(...)
top of page

Returns three values: an iterator function, the given arguments as a table, and 0, so that

for i,v in apairs(0,11,222,3333,44444) do print(i,v) end

will iterate over the given arguments. See also select().

assert(v[,message])
top of page

Issues an error when the value of its argument v is not true (i.e., nil or false); otherwise, returns all its arguments. message is an error message; when absent, the default is 'assertion failed!'

collectgarbage(opt[,arg])
top of page

This function is a generic interface to the garbage collector. It performs different functions according to its first argument, opt:

dofile(filename)
top of page

Opens the named file and executes its contents as an Idle chunk. When called without arguments, dofile() executes the contents of the standard input (stdin). Returns all values returned by the chunk. In case of errors, dofile() propagates the error to its caller (that is, dofile() does not run in protected mode; see pcall()).

error(message[,level])
top of page

Terminates the last protected function called and returns message as the error message. This function never returns.

Usually, error() adds some information about the error position at the beginning of the message. The level argument specifies how to get the error position. With level 1 (the default), the error position is where error() was called. Level 2 points the error to where the function that called error() was called; and so on. Passing a level of 0 avoids the addition of error position information to the message.

_G
top of page

A global variable (not a function) that holds the global environment (that is, _G._G is _G). Idle itself does not use this variable; changing its value does not affect any environment, nor vice-versa (use setfenv() to change environments).

getfenv([f])
top of page

Returns the current environment in use by a function. f can be either an Idle function or a number that specifies the function at that stack level: Level 1 is the function calling getfenv(). If the given function is not an Idle function, or if f is 0, getfenv() returns the global environment. The default for f is 1.

getmetatable(object)
top of page

If object does not have a metatable, returns nil. Otherwise, if the object's metatable has a '__metatable' field, returns the associated value. Otherwise, returns the metatable of the given object.

ipairs(t)
top of page

This function is equivalent to the function rawipairs(), but it will honour the metamethod __ipairs, if defined in t's metatable. With a suitable metamethod, this function can traverse userdata as well as tables.

load(func[,chunkname])
top of page

Loads a chunk using function func to get its pieces. Each call to func must return a string that is concatenated with previous results. A return of nil (or no value) signals the end of the chunk.

If there are no errors, returns the compiled chunk as a function (but does not run this function); otherwise, returns nil plus the error message. The environment of the returned function is the global environment.

chunkname is used as the chunk name for error messages and debug information.

loadfile([filename])
top of page

Similar to load(), but gets the chunk from file filename or from standard input, if no name is given.

loadstring(string[,chunkname])
top of page

Similar to load(), but gets the chunk from the given string. To load and run a given string, use this:

assert(loadstring(s))()

next(t[,index])
top of page

This function is equivalent to the function rawnext(), but it will call the metamethod __next, if defined in t's metatable.

NULL
top of page

A globally defined constant (not a function) that can be used as a placeholder for declared variables, table fields or function parameters whose value is yet undefined. Using nil for this purpose has the disadvantage that variables or fields which are set to nil are taken not to exist. Consider the following short program:

function NULL_or_nil(...)
  return {...}
end

local tnil=NULL_or_nil(1,nil,2,nil,3,nil,4,nil)
print('#tnil:',#tnil)
for k,v in pairs(tnil) do print(k,v) end
local tNULL=NULL_or_nil(1,NULL,2,NULL,3,NULL,4,NULL)
print('#tNULL:',#tNULL)
for k,v in pairs(tNULL) do print(k,v) end

which produces:

#tnil:  1
1       1
3       2
5       3
7       4
#tNULL: 8
1       1
2       NULL
3       2
4       NULL
5       3
6       NULL
7       4
8       NULL

(Using NULL instead of nil in these and similar circumstances is purely a convention, not a syntactical necessity.)

pairs(t)
top of page

This function is equivalent to the function rawpairs(), but it will honour the metamethod __pairs, if defined in t's metatable. With a suitable metamethod, this function can traverse userdata as well as tables.

pcall(f[,...])
top of page

Calls function f with the given arguments in protected mode. This means that any error inside f is not propagated; instead, pcall() catches the error and returns a status code. Its first result is the status code (a boolean), which is true if the call succeeded without errors. In this case, pcall() also returns all results from the call, after this first result. In case of any error, pcall() returns false plus the error message.

print([...])
top of page

Receives any number of arguments, and prints their values to stdout (separated by a tab), using tostring() to convert them to strings. print() is not intended for formatted output, but as a quick way to display a value, typically for debugging. For formatted output, use string.format().

printf(fmt,[...])
top of page

A global variable that is by default initialised with util.printf(). This variable can be initialised with one of a variety of printf-style functions (see debug.printf(), file:printf(), util.printf()) in order to quickly redirect formatted string output.

rawequal(v1,v2)
top of page

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

rawget(t,index)
top of page

Gets the value of t[index], without invoking metamethods. t must be a table; index may be any value.

rawipairs(t)
top of page

Returns three values: an iterator function, the table t, and 0, so that

for i,v in rawipairs(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. This function will not invoke the metamethod __ipairs.

rawnext(t[,index])
top of page

Allows a program to traverse all fields of a table t without invoking metamethod __next. Its first argument is a table; its second argument is an index into this table. rawnext() returns the next index of the table and its associated value. When called with nil as its second argument, rawnext() returns an initial index and its associated value. When called with the last index, or with nil on an empty table, rawnext() returns nil. If the second argument is absent, then it is interpreted as nil. In particular, you can use rawnext(t) to check whether table t is empty.

The order in which the indices are enumerated is not specified, even for numeric indices. (To traverse a table in numeric order, use a numerical for or the ipairs() function.)

The behavior of rawnext() is undefined if, during the traversal, you assign any value to a non-existent field in the table. You may however modify existing fields. In particular, you may clear existing fields.

rawpairs(t)
top of page

Returns three values: the rawnext() function, the table t, and nil, so that

for k,v in rawpairs(t) do body end

will iterate over all key/value pairs of table t. This function will not invoke the metamethod __pairs. See function next() for the caveats of modifying the table during its traversal.

rawset(t,index,value)
top of page

Sets the value of t[index] to value, without invoking metamethods. t must be a table, index any value different from nil, and value any Idle value. The function returns t.

rawtype(v)
top of page

Returns the type of its argument, coded as a string. The possible results of this function are 'nil' (as a string, not the value nil), 'number', 'string', 'boolean', 'table', 'function', 'thread', and 'userdata'.

select(index,...)
top of page

If index is a number, returns all arguments after argument number index. Otherwise, index must be the string '#', and select() returns the total number of extra arguments it received.

setfenv(f,t)
top of page

Sets the environment to be used by the given function to table t. f can be an Idle function or a number that specifies the function at that stack level: level 1 is the function calling setfenv(). setfenv() returns the given function. As a special case, when f is 0, setfenv() changes the environment of the running thread. In this case, setfenv() returns no values.

setmetatable(t,metatable)
top of page

Sets the metatable for the given table. (You cannot change the metatables of other types from Idle, only from C.) If metatable is nil, removes the metatable of the given table. If the original metatable has a '__metatable' field, raises an error. The function returns t.

tonumber(e[,base])
top of page

Tries to convert its argument to a number. If the argument is already a number or a string convertible to a number, then tonumber() returns this number; otherwise, it returns nil.

The optional argument base specifies in which base to interpret the numeral. base may be any integer between 2 and 36, inclusive. In bases above 10, the letter 'A' (in either upper or lower case) represents 10, 'B' represents 11, and so forth, with 'Z' representing 35. In base 10 (the default), the number may have a decimal part, as well as an optional exponent part. For other bases, only unsigned integers are accepted.

tostring(e)
top of page

Receives an argument of any type and tries to convert it to a reasonably formatted string. If the metatable of e has a '__tostring' field, then tostring() calls the corresponding value with e as argument, and uses the result of the call as its result.

For complete control of how numbers are converted to strings, use string.format().

type(v)
top of page

This function is equivalent to the function rawtype(), but it will call the metamethod __type, if defined in v's metatable.

unpack(t[,i[,j]])
top of page

Returns elements from the table t. Calling unpack() is equivalent to

return t[i],t[i+1],...,t[j]

except that the above code can be written only for a fixed number of elements. By default, i is 1 and j is the size of the table, as defined by the length operator.

_VERSION, _VERSION2
top of page

Two global variables (not functions) that hold strings containing information about the current interpreter version. The contents of _VERSION is 'Idle 1.0.0'; _VERSION2 contains additional information in an unspecified format.

xpcall(f,err)
top of page

This function is similar to pcall(), except that you can set a new error handler. xpcall() calls function f in protected mode, using err as the error handler. Any error inside f is not propagated; instead, xpcall() catches the error, calls the err function with the original error object, and returns a status code. The first result is the status code (a boolean), which is true if the call succeeded without errors. In this case, xpcall() also returns all results from the call, after the first result. In case of any error, xpcall() returns false plus the result from err.

Module Class
top of page

This module offers a simple, yet powerful object-oriented facility. Class, as the base class for all derived classes, 'exports' its set of methods to all subclasses. Likewise, all instance variables based on Class or a subclass of Class can call those methods (although the result may not always be the same for an instance variable as for its base class).

New subclasses are created by calls to method Class:new() or subclass:new(), whereas instances variables are simply created by calling the subclass name. Here is an example:

-- create subclass Rect with two member fields, x and y
Rect=Class:new('Rect',{x=2,y=3})
-- create Rect r1, with r1.x=2 and r1.y=3
r1=Rect()
print(r1.x,r1.y)         --> 2       3
print(r1:class())        --> Rect
print(r1:isClass())      --> false
print(r1:isInstance())   --> true
print(Rect:isClass())    --> true
print(Rect:isInstance()) --> false

A subclass can provide implicit initialisation as shown above; it can also provide an explicit function (called init) for that purpose. It can even mix both approaches. Another example:

-- create subclass Rect with two member fields, x and y
Rect=Class:new('Rect',{x=2,y=3})
function Rect:init(x,y)
  if x!=nil then self.x=x end
  if y!=nil then self.y=y end
end
-- create Rect r1, with r1.x=2 and r1.y=3
r1=Rect()
print(r1.x,r1.y)  --> 2      3
-- create Rect r2, with r2.x=20 and r2.y=30
r2=Rect(20,30)
print(r2.x,r2.y)  --> 20     30
-- create Rect r3, with r3.x=2 and r3.y=30
r3=Rect(nil,30)
print(r2.x,r2.y)  --> 2      30

If defined, the init function of a subclass is called automatically upon creation of a new instance. Inside the init function, an instance variable can call the init function of its immediate superclass by simply invoking the superinit method:

NewAClass=Class:new('NewAClass')
function NewAClass:init(a)
  if a!=nil then self.a=a end
end

NewABClass=NewAClass:new('NewABClass')
function NewABClass:init(a,b)
  self:superinit(a)
  self.b=b
end

An instance variable can access its immediate superclass by referring to the predefined field self.super (and to the superclass of its superclass with self.super.super and so on):

NewABClass=New1Class:new('NewABClass')
function NewABClass:init(a,b)
  self.super.init(self,a)  -- same as above
  self.b=b
end

InstanceOrClass:class()
top of page

Returns a string with the name of the class an instance or class belongs to.

InstanceOrClass:isClass()
top of page

Returns true if called by a class, false if called by an instance.

InstanceOrClass:isInstance()
top of page

Returns true if called by an instance variable, false if called by a class.

Instance:isInstanceOf(c)
top of page

Returns true if the instance that calls this method has class name c.

Class:new(name,proto)
top of page

Creates a new subclass with the string name being the name of the class. If table proto is defined, its fields are used as a template to initialise new instances of the subclass.

Instance:superinit(...)
top of page

Calls the init function of the immediate superclass of the calling instance.

Class:tostring()
top of page

Returns a printable representation of the class (this invokes the __tostring metamethod if it is defined for the class).

Module coroutine
top of page

The coroutine library implements asymmetric coroutines, used for pipes, filters and iterators as well as non-pre-emptive multitasking. All functions are stored in table coroutine and calls need the couroutine prefix.

coroutine.create(f)
top of page

Creates a new coroutine, with body f (f must be an Idle function). Returns the new coroutine as an object with type 'thread'.

coroutine.resume(co[,val1,...])
top of page

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, this function resumes it; the values val1, ... are passed as the return values of the pending coroutine.yield() call.

If the coroutine runs without any errors, this function returns true plus any values passed to coroutine.yield() (if the coroutine yields) or any values returned by the body function (if the coroutine terminates). If there is any error, coroutine.resume() returns false plus the error message.

coroutine.running()
top of page

Returns the running coroutine, or nil when called by the main thread.

coroutine.status(co)
top of page

Returns the status of coroutine co as a string: 'running', if the coroutine is running (that is, it called coroutine.status() itself); 'suspended', if the coroutine is suspended in a call to coroutine.yield(), 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(f,...)
top of page

Creates a new coroutine, with body f (f must be an Idle function) and returns a function that resumes the coroutine each time it is called. Any arguments passed to the function behave as the extra arguments to coroutine.resume(). Returns the values returned by coroutine.resume(), except the first boolean. In case of error, propagates the error.

coroutine.yield([...])
top of page

Suspends the execution of the calling coroutine. The coroutine cannot be running a C function, a metamethod, or an iterator. Any arguments to coroutine.yield() are passed as extra results to coroutine.resume().

Module debug
top of page

This library provides a debug interface to Idle programs. The functions provided should be used exclusively for debugging and similar tasks, such as profiling. Please resist the temptation to use them as a usual programming tool: they can be very slow. Moreover, several functions violate some basic assumptions about Idle code (e.g., that variables local to a function cannot be accessed from outside or that userdata metatables cannot be changed by Idle code) and therefore can compromise otherwise secure code.

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.getfenv(o)
top of page

Returns the environment of object o.

debug.gethook([thread])
top of page

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 debug.sethook()).

debug.getinfo([thread,]function[,what])
top of page

Returns a table with information about a function. You can give the function directly, or you can give a number as the value of function, which means the function running at that level of the call stack of the given thread: level 0 is the current function (debug.getinfo() itself); level 1 is the function that called debug.getinfo(); and so on. If function is a number larger than the number of active functions, then debug.getinfo() returns nil.

The string what describes which fields to fill in the returned table. The default for what is to get all information available, except the table of valid lines. If present, the option 'f' adds a field named func with the function itself. If present, the option 'L' adds a field named activelines with the table of valid lines.

For instance, the expression debug.getinfo(1,'n').name returns the name of the current function, if a reasonable name can be found, and the expression debug.getinfo(print) returns a table with all available information about the print function.

debug.getlocal([thread,]level,local)
top of page

This function returns the name and value of the local variable with index local of the function at level level of the stack. (The first parameter or local variable has index 1, and so on, until the last active local variable.) The function returns nil if there is no local variable with the given index, and raises an error when called with a level out of range. (You can call debug.getinfo() to check whether the level is valid.)

Variable names starting with '(' (open parentheses) represent internal variables (loop control variables, temporaries, and C function locals).

debug.getmetatable(object)
top of page

Returns the metatable of the given object or nil if it does not have a metatable.

debug.getregistry()
top of page

Returns the registry table.

debug.getupvalue(func,up)
top of page

This function returns the name and value of the upvalue with index up of the function func. The function returns nil if there is no upvalue with the given index.

debug.ldb()
top of page

Starts the Idle debugger if it is enabled (see debug.setLevel()) and if the running script is not compiled. This call can also be used, similar to a breakpoint, to trigger the debugger prompt. The debugger has its own help system: just type 'help'.

debug.pauseProfiler()
top of page

Pauses the collection of profile data.

debug.printd(s)
top of page

Sends string s to the Windows debug output port. (A system level debugger or a debug output viewer, such as SysInternal's DbgView, must be up and runnning.)

debug.printf(fmt,...)
top of page

Formats a string according to the format specification in string fmt (for details of the supported formats see string.format()) and sends it on to debug.printd(). A debug level of 'none' disables this function.

debug.resumeProfiler()
top of page

Resumes the collection of profile data.

debug.setLevel(level)
top of page

Sets the debug level and loads the Idle debugger, if required. level has to be one of 'C', 'idle', 'both' or 'none'. With 'C' the debugger can only be called from C code, with 'idle' from Idle and with 'both' from both (in the latter two cases the Idle debugger is also triggered whenever Idle encounters a runtime error). A debug level of 'none' disables the Idle debugger and any output via debug.printf().

'none' is the default debug level.

debug.setfenv(object,t)
top of page

Sets the environment of the given object to table t and returns object.

debug.sethook([thread,]hook,mask[,count])
top of page

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:

With a count different from 0, 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 the call: 'call', 'return' (or 'tail return'), 'line', and 'count'. For line events, the hook gets the new line number as the second parameter. Inside a hook, you can call debug.getinfo() with level 2 to get more information about the running function (levels 0 and 1 are the call to debug.getinfo() and the hook function), unless the event is 'tail return'. In this case, Idle is only simulating the return, and a call to debug.getinfo() will return invalid data.

debug.setlocal([thread,]level,local,value)
top of page

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 debug.getinfo() to check whether the level is valid.) Otherwise, it returns the name of the local variable.

debug.setmetatable(object,t)
top of page

Sets the metatable for the given object to table t (which can be nil).

debug.setupvalue(func,up,value)
top of page

This function assigns the value value to the upvalue with index up of the function func. The function returns nil if there is no upvalue with the given index. Otherwise, it returns the name of the upvalue.

debug.startProfiler([fname])
top of page

Starts the collection of profiling data which will be written to a file. The optional string parameter fname gives the name for this file. If this is empty a randomly-generated name will be used.

debug.stopProfiler()
top of page

Stops the collection of profiling data and closes the output file. This file can then be further analysed with other tools (see also test\Goodies\analyseProfileOutput,idle).

debug.traceback([thread,][message][,level])
top of page

Returns a string with a traceback of the call stack. The optional message 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 debug.traceback()).

Module Idle
top of page

Idle._error(n,fmt,...)

Prints an error message and terminates the last (possibly protected) function called. This function never returns. The error message is formatted according to the description given in argument fmt (which must be a string) and the optional parameter list; for details see string.format(). The first parameter is the error level (see error()).

Idle._registerExit(f)
top of page

Registers function f as an exit function. If a script terminates normally, Idle calls all registered exit functions in the order they were registered. Terminating a script by calling error(), Idle._error() or os.exit() is considered abnormal.

Idle.isCompiled
top of page

A variable that is true if the running script is compiled and false if it is interpreted.

Module io
top of page

The I/O library provides functions for file manipulation. It supports two different calling styles: the first uses implicitly defined file descriptors; that is, there are operations to set a default input file and a default output file, and all input/output operations are performed over these default files. This is broadly similar to the stdin/stdout model of the C runtime library. When using implicit file descriptors, all operations are supplied by table io.

The second style uses explicitly created file descriptors. When using explicit file descriptors, the function io.open() returns a file descriptor; all further operations are supplied as methods of the file descriptor.

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.

The I/O functions support accessing large files (ie files larger than 2 GB). However, write access to large files requires that the files be opened in binary mode (read access does work for both text and binary mode); see function io.open(). For reasons of backward compatibility, the function file:seek() does not support offsets larger than 2 GB, use file:lseek() instead.

but for write access such files have to be opened in binary mode. See also file:lseek().

io.close([file])
top of page

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

io.flush()
top of page

Equivalent to file:flush() over the default output file.

io.input([file])
top of page

When called with a filename, it opens the named file (in text mode), and sets its handle as the default input file. When called with a file handle, it 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 an error, instead of returning an error code.

io.lines([filename])
top of page

Opens the given filename in read mode and returns an iterator function that, each time it is called, returns a new line from the file. Therefore, this

for line in io.lines(filename) do body end

will iterate over all lines of the file. When the iterator function detects the end of file, it returns nil (to finish the loop) and automatically closes the file.

The call io.lines() (with no filename) is equivalent to io.input():lines(); that is, it iterates over the lines of the default input file. In this case io.lines() does not close the file when the loop ends.

io.loadAsString(file,[,mode])
top of page

Returns the contents of a file as a (possibly binary) string. file can be either a string with the filename or an already opened file (for instance, io.stdin). The file is opened in mode mode (see io.open() for details).

io.loadAsTable(file[,mode])
top of page

Reads the contents of a file and returns them as a table of separate lines (separating newline characters are removed; see also string.split()). file can be either a string with the filename or an already opened file (for instance, io.stdin). The file is opened in mode mode (see io.open() for details).

io.open(filename[,mode])
top of page

This function opens a file, in the mode specified by 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:

The mode string may also have a 'b' at the end; this opens the file in binary mode. The mode string is exactly what is used in the standard C function fopen().

Note: this function works with files larger than 2 GB, but for write access such files have to be opened in binary mode. See also file:lseek().

io.output([file])
top of page

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

io.pipe()
top of page

Returns two file handles to be used in a pipe (first the read handle, then the write handle) or nil, nil in case of an error.

io.popen(prog[,mode])
top of page

Starts program prog in a separate 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'). See also os.spawnProcess().

io.read(...)
top of page

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

io.replaceInFile(filename,s,r[,name2])
top of page

Replaces all occurences of string s with string r in file filename. s and r can be regular expressions (see string.reGSub() for details). The result is saved to file name2, if given, or in place. Returns the number of replacements or nil in case of error.

io.save(file,sort[,mode])
top of page

Saves sort (a string or a table ) to a file . file can be either a string with the filename or an already opened file (for instance, io.stdout). The file is opened in mode mode (see io.open() for details).

io.stdin
top of page

The default file handle for standard input.

io.stdout
top of page

The default file handle for standard output.

io.stderr
top of page

The default file handle for standard error output.

io.tmpfile()
top of page

Returns a handle for a temporary file. This file is opened in update mode and it is automatically removed when the program ends.

io.truncate(filename,len) or file:truncate(len)
top of page

Truncates a file, given either by the filename (first form) or as an open file (second form; the file must have been opened with write access). len is the length of the file after truncation.

io.type(obj)
top of page

Checks whether obj is a valid file handle. Returns the string 'file' if obj is an open file handle, 'closed file' if obj is a closed file handle, or nil if obj is not a file handle.

io.write(...)
top of page

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

file:close()
top of page

Closes file. Note that files are automatically closed when their handles are garbage collected, but that takes an unpredictable amount of time to happen.

file:eof()
top of page

Returns true if the end of file on file has been reached.

file:flush()
top of page

Flushes buffered data, if any, to file.

file:lines()
top of page

Returns an iterator function that, each time it is called, returns a new line from the file. Therefore, this

for line in file:lines() do body end

will iterate over all lines of the file. (Unlike io.lines(), this function does not close the file when the loop ends.)

file:lock(start,len,mode)
top of page

Locks or unlocks a region in a file. The start of the region is start, its length is len. mode has to be set to true for locking and to false for unlocking. If unlocking, the region must be identical to a previously locked region.

file:lseek([whence][,offset])
top of page

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:

In case of success, file:lseek() returns the final file position, measured in bytes from the beginning of the file. If this function fails, it returns nil, plus a string describing the error.

The default value for whence is 'cur', and for offset it is 0. Therefore, the call file:lseek() returns the current file position, without changing it; the call file:lseek('set') sets the position to the beginning of the file (and returns 0); and the call file:lseek('end') sets the position to the end of the file, and returns its size.

Note: this function supports binary files with a size of more than 2 GB. Whenever possible, it should be used instead of file:seek() which does not support large files.

file:printf(fmt,...)
top of page

Formats a string according to the format specification in string fmt (for details of the supported formats see string.format()) and writes it to the file.

file:read([format[,format...]])
top of page

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 entire next line (see below).

The available formats are

file:seek([whence][,offset])
top of page

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:

In case of success, file:seek() returns the final file position, measured in bytes from the beginning of the file. If this function fails, it returns nil, plus a string describing the error.

The default value for whence is 'cur', and for offset it is 0. Therefore, the call file:seek() returns the current file position, without changing it; the call file:seek('set') sets the position to the beginning of the file (and returns 0); and the call file:seek('end') sets the position to the end of the file, and returns its size.

Note: this function doesn't support files with a size of more than 2 GB. It is included for backward compatibility and should, if possible, be replaced with file:lseek().

file:setvbuf(mode[,size])
top of page

Sets the buffering mode for an output file. There are three available modes:

For the last two cases, size specifies the size of the buffer, in bytes. The default is an appropriate size.

file:write(...)
top of page

Writes the value of each of its arguments to the file. The arguments must be strings or numbers. To write other values, use tostring() or string.format() before calling file:write().

Module jit
top of page

This library provides several functions to control the behaviour of the Idle just-in-time compiler (which is a modified version of Mike Pall's just-in-time compiler for Lua, LuaJIT: see Mike's website for more details).

jit.mode()
top of page

Returns a boolean with the current state of the JIT engine: true means turned on, false means off.

jit.off() or jit.off(func|true[,true|false])
top of page

The first form (without parameters) simply turns the JIT engine off.

The second form disables the JIT compilation for a function. The current function (the Idle function calling this library function) can be specified with true. If the second argument is true, JIT compilation is also disabled recursively for all subfunctions of a function. With false only the subfunctions are affected. Both library functions only set a flag which is checked when the function is executed for the first/next time. They do not trigger immediate compilation.

Typical usage is jit.off(true, true) in the main chunk of a module to turn off JIT compilation for the whole module. Note that require() already turns off compilation for the main chunk itself.

jit.on() or jit.on(func|true[,true|false])
top of page

The first form (without parameters) simply turns the JIT engine on (default).

The second form enables the JIT compilation for a function. The current function (the Idle function calling this library function) can be specified with true. If the second argument is true, JIT compilation is also enabled recursively for all subfunctions of a function. With false only the subfunctions are affected. Both library functions only set a flag which is checked when the function is executed for the first/next time. They do not trigger immediate compilation.

jit.compile(func[,args...])
top of page

Compiles function func and returns the compilation status. Successful compilation is indicated with a nil status. Failure is indicated with a numeric status (see jit.util.status).

The optimizer pass of the compiler tries to derive hints from the passed arguments. Not passing any arguments or passing untypical arguments (especially the wrong types) reduces the efficiency of the optimizer. The compiled function will still run, but probably not with maximum speed.

This library function is typically used for Ahead-Of-Time (AOT) compilation of time-critical functions or for testing/debugging.

jit.compilesub(func|true[,true])
top of page

Recursively compile all subfunctions of function func. The current function (the Idle function calling jit.compilesub()) can be specified with true. Note that the function itself is not compiled (use jit.compile()). If the second argument is true, compilation will stop when the first error is encountered. Otherwise compilation will continue with the next subfunction.

The returned status is nil, if all subfunctions have been compiled successfully. A numeric status (see jit.util.status) indicates that at least one compilation failed and gives the status of the last failure (this is only helpful when stop on error is true).

jit.debug([level])
top of page

Set the debug level for JIT compilation. If no level is given, the maximum debug level is set.

Note that some compiler optimizations are turned off when debugging is enabled. This function is typically used with the command line options -J debug or -J debug=level.

jit.util.status
top of page

This is a table with the possible status codes used or returned by the jit functions:

Module macro
top of page

Module macro adds textual macros and preprocessing facilities, similar to the C preprocessor, to Idle. It supports definition and replacement of macros, with or without parameters, and supports textually including source files (by contrast, require() and dofile() introduce separate compilation units with, among other things, a separate scope).

This module provides around a dozen functions to define and manipulate macros. However, using the predefined macros (see below) to define macros is much easier and more straightforward than calling these functions. Furthermore, some of the macro functions are still experimental and their usage may well change in future versions while the predefined macro calls should be rather stable. Because of this, the functions in module macro are currently not documented, although it is quite possible to use these functions for special cases or in circumstances where the predefined macros are not feasible; the enclosed example scripts do show some ways of doing so.

An important consideration to keep in mind while using macros is the fact that all macros are expanded at compile time and not at run-time (after all, these are textual macros). If Idle code has to be executed during compile time, the predefined macro __INLINE() can be used (see the predefined macro __INCLUDE() for an example).

Note: the macro module is based on Idle's built-in token filtering facility. A script which installs its own token filter will work but macro expansion will be disabled. However, in many (if not most) cases it should be possible to replace such a token filter with a macro or a set of macros.

Predefined Macros
top of page

The following macros are predefined by module macro. As all macros, both predefined or user-defined, have global scope, the names of predefined macros start with two underscores in order to minimise the risk of contaminating existing programs. It is trivial to define additional macros with less obtuse names:

__DEFINE(DEFINE,__DEFINE)
DEFINE(INCLUDE,__INCLUDE)
-- and so on

__DEFINE(mdef[(...)],repl)
top of page

Defines a macro. mdef is the macro name, optionally followed by a list of comma-separated argument names in parentheses. repl is the replacement text which is expanded each time the macro is used (this can be a sequence of Idle code or a string). Arguments, if any, are replaced with the actual parameters. Example:

__DEFINE(ATTRIBUTE_VALUE,0x0003)
__DEFINE(INC(n),n=n+1)
__DEFINE(IF2(cond,x,t,f),if cond then x=t else x=f end)
s=2
INC(s)
IF2(s==ATTRIBUTE_VALUE,s,'three','rubbish')
print(s)  --> prints 'three'

If the replacement text in repl contains commas, the whole text has to be put in single or double quotes (ie given as a string). Example:

__DEFINE(LOOP(t,val),'for i=1,#t do t[i]=val end')
local z=table.new({1,2,3,4})
LOOP(z,z[i]*z[i]+z[i]+10)
z:print()  -- z is now {16,22,30,40}

__FILE__
top of page

Expands to the current source file name.

__IF(m,v,t,f)
top of page

Allows conditional compilation. If argument m has value v, then t is compiled else f is compiled. If v is the empty string then __IF() checks whether m is defined as a macro: if yes, then t is compiled else f is compiled. Example:

__DEFINE(IFDEF(name,tru,fals),__IF(name,'',tru,fals))
-- DEBUG is not defined, uncomment next line to define
--__DEFINE(DEBUG,'')
IFDEF(DEBUG,
  __DEFINE(ASSERT(cond,msg),assert(cond,msg))
, -- ELSE
  __DEFINE(ASSERT(cond,msg),'')
)
print('Testing a few assertions:')
ASSERT(type(macro)=='table','macro ain\'t a table.')
print('Survived 1st')
ASSERT(1==1,'one is not one in this universe.')
print('Survived 2nd')
ASSERT(1==2,'one is not two in this universe.')
print('Survived 3rd')

__INCLUDE(fname)
top of page

Textually includes file fname. __INCLUDE() searches files along the path given in package.ipath. Idle initialises this with the content of environment variable IDLE_IPATH but package.ipath can be set to any semicolon-separated sequence of pathnames. However, the following naive attempt will not work as expected...:

package.ipath='.;..;c:\\Idle\\inc'
__INCLUDE('test.inc')

... as the __INCLUDE() macro is executed at compile time and the package.ipath assignment is performed at runtime, ie much later. The following works as it inlines the assignment to package.ipath:

__INLINE("package.ipath='.;..;c:\\Idle\\inc'")
__INCLUDE('test.inc')  -- searches test.inc in current, parent and c:\Idle\inc

__INLINE(str)
top of page

Executes the Idle source code in string str during compile time. See __INCLUDE() for an example.

__LINE__
top of page

Expands to the current line number.

__REQUIRE(fname)
top of page

Temporarily disables macro processing and calls require() to load file fname during compile time. This can be used to load modules with macro definitions.

__TOSTRING(arg)
top of page

Stringises its argument. Example:

__DEFINE(PRINT(n),print(__TOSTRING(n)..'='..n)
PRINT(math.sin(math.pi/4))  --> prints "math.sin(math.pi/4)=0.70710678118655"

Module math
top of page

This library provides many mathematical functions. All functions are accessible through table math.

math.abs(x)
top of page

Returns the absolute value of x.

math.acos(x)
top of page

Returns the arc cosine of x (in radians).

math.asin(x)
top of page

Returns the arc sine of x (in radians).

math.atan(x)
top of page

Returns the arc tangent of x (in radians).

math.atan2(x, y)
top of page

Returns the arc tangent of x/y (in radians), but uses the signs of both parameters to find the quadrant of the result. (It also handles correctly the case of y being 0.)

math.ceil(x)
top of page

Returns the smallest integer larger than or equal to x.

math.cos(x)
top of page

Returns the cosine of x (assumed to be in radians).

math.cosh(x)
top of page

Returns the hyperbolic cosine of x.

math.deg(x)
top of page

Returns the angle x (given in radians) in degrees.

math.exp(x)
top of page

Returns the value e^x.

math.floor(x)
top of page

Returns the largest integer smaller than or equal to x.

math.fmod(x,y)
top of page

Returns the remainder of the division of x by y.

math.frexp(x)
top of page

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 0 when x is 0).

math.huge
top of page

The value HUGE_VAL, a value larger than or equal to any other numerical value.

math.ldexp(m,e)
top of page

Returns m2^e (e should be an integer).

math.log(x)
top of page

Returns the natural logarithm of x.

math.log10(x)
top of page

Returns the base10 logarithm of x.

math.max(x,...)
top of page

Returns the maximum value among its arguments.

math.min(x,...)
top of page

Returns the minimum value among its arguments.

math.modf(x)
top of page

Returns two numbers, the integral part of x and the fractional part of x.

math.mtrandom([m[,n]])
top of page

Generates a Mersenne Twister random number. When called without arguments, returns a pseudo-random real number in the range [0,1). When called with a number m, math.mtrandom() returns a pseudo-random integer in the range [1,m]. When called with two numbers m and n, math.mtrandom() returns a pseudo-random integer in the range [m,n].

math.mtseed([x])
top of page

Seeds the Mersenne Twister random number generator with optional value x. Equal seeds produce equal sequences of numbers.

math.pi
top of page

Returns the value of pi.

math.pow(x,y)
top of page

Returns x^y. (You can also use the Idle expression x^y to compute this value.)

math.rad(x)
top of page

Returns the angle x (given in degrees) in radians.

math.random([m[,n]])
top of page

This function is an interface to the simple pseudo-random generator function provided by ANSI C (no guarantees can be given for its statistical properties). When called without arguments, returns a pseudo-random real number in the range [0,1). When called with a number m, math.random() returns a pseudo-random integer in the range [1,m]. When called with two numbers m and n, math.random() returns a pseudo-random integer in the range [m,n].

math.randomseed(x)
top of page

Sets x as the 'seed' for the pseudo-random generator: equal seeds produce equal sequences of numbers.

math.sin(x)
top of page

Returns the sine of x (assumed to be in radians).

math.sinh(x)
top of page

Returns the hyperbolic sine of x.

math.sqrt(x)
top of page

Returns the square root of x. (You can also use the expression x^0.5 to compute this value.)

math.tan(x)
top of page

Returns the tangent of x (assumed to be in radians).

math.tanh(x)
top of page

Returns the hyperbolic tangent of x.

Module os
top of page

This library implements many functions related to the underlying operating system, such as a dynamic link call facility or the ability to create hard or soft links on files and directories. All functions are called through table os.

os.allocDynMem(size[,proto])
top of page

This function allocates a block of memory with size size and returns it as userdata. Such a memory block can, among other things, be used by util.pack() and os.writeDynMem() to pack values and structures for os.getDynLink() calls (and to unpack them with os.readDynMem() and util.unpack(), of course). The optional string proto is a util.pack()-style string that describes the layout of the memory block. This string is not at all used by os.allocDynMem(), os.readDynMem() and os.writeDynMem(); it is simply stored inside the dynmem userdata for other function (see os.readDynStruct() and os.writeDynStruct()). A dynmem userdata has the following read-only fields:

os.chDir(dirname)
top of page

Changes current directory to dirname. Returns true on success and false and an error message in case of an error.

os.clock()
top of page

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

os.convertToLocalTime(t[,tolocal])
top of page

If tolocal is true or missing, this function converts a UTC file-time value t to a local-time value (i.e. adjusts for time zone and summer time) and returns the result. If tolocal is false, converts from local time to UTC file-time value. See also os.getFileInfo().

os.convertToTime(t[,totime])
top of page

If totime is true or missing, this function converts file-time value t (in 100-nanosecond intervals since 1.1.1601) to a time value (in seconds since 1.1.1970) and returns the result. If totime is false, converts from time value to file-time value. See also os.getFileInfo().

os.createHardLink(oldname,newname)
top of page

Creates an NTFS hardlink. The file newname is hardlinked to file oldname (this only works on NTFS volumes). Returns true on success and false and an error message in case of an error.

os.createSymLink(oldname,newname)
top of page

Creates an NTFS symlink (also called reparse point). The directory newname is symlinked to directory oldname (this only works on NTFS volumes). Returns true on success and false and an error message in case of an error.

os.date([format[,time]])
top of page

Returns a string or a table containing date and time, formatted according to the format given in 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, os.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 (1--12), day (1--31), hour (0--23), min (0--59), sec (0--61), wday (weekday, Sunday is 1), yday (day of the year), and isdst (daylight saving flag, a boolean).

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

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

os.difftime(t2,t1)
top of page

Returns the number of seconds from time t1 to time t2. In POSIX, Windows, and some other systems, this value is exactly t2-t1.

os.Dir(dirname)
top of page

Returns an non-recursive iterator function to walk a directory. dirname can be either the name of a directory (in which case all entries in that directory will be processed) or a directory name with a wildcard pattern appended (in which case only those specified by the pattern will be returned). This code

for name,isdir,size,attr in os.Dir('c:\\') do print(name) end

iterates over the c: root directory, returning information for one directory entry per iteration (the order of the entries is undefined). The iterator's four return values are the name, a boolean flag that is true for a directory, the size of the entry and its attributes. In subdirectories the entries for '.' and '..' are skipped. Individual attributes can be extracted by and'ing them with one or more of the following file attribute constants (these constants are fields with numerical values in table os.FA):

If you need a recursive directory traversal or more control over which entries are returned see os.walkDir().

os.DynStruct(packstr)
top of page

Allocates and returns a memory block (userdata dynmem, see os.allocDynMem()) big enough to hold a binary structure described by packstr (see util.pack() for details). The packstring is stored with the dynmem userdata and used in calls to os.readDynStruct() and os.writeDynStruct(). The function looks like this:

function DynStruct(t)
  return allocDynMem(g.util.pack(t),t)
end

Using this function with util.pack() codes 'a0' or 'A0' produces an error. All elements of packstr must have known lengths when the function is called.

os.ENV[varname]
top of page

This is a pseudo-table to access process environment variables. os.ENV[] can be read from and written to:

path=os.ENV['PATH']
os.ENV['PATH']=nil -- or ''

os.execute([command])
top of page

This function is equivalent to the C function system. It passes a command to be executed to the operating system shell and returns a status code which is system-dependent. If command is absent, then os.execute() returns nonzero if a shell is available and 0 otherwise.

os.exit([code])
top of page

Calls the C function exit, with an optional code, to terminate the host program. The default value for code is the success code. An Idle script terminated by a call to this function will not execute the normal library shutdown functions. This can leave open resources in an inconsistent state. if you simply want to return an error code, you can use a return statement in the main chunk of a script.

os.expandEnvStrings(str)
top of page

This function expands references to environment-variable strings of the form %variableName% and returns the result. For each such reference, the %variableName% portion is replaced with the current value of that environment variable. The replacement rules are the same as those used by the command interpreter, CMD.EXE. Case is ignored when looking up the environment-variable name. If the name is not found, the %variableName% portion is left undisturbed.

os.fullPath(partialpath)
top of page

Converts a partial path in partialpath into a fully qualified path and returns it.

os.getStreamInfo(fname)
top of page

Returns an array of tables with information about the streams connected with file fname. Each table in the returned array describes one stream with fields named type, name and size (in bytes). type can be any of the following strings:

os.getCwd()
top of page

Returns a string with the current working directory.

os.getDynLink(libname,funcname,prototype,opt)
top of page

This function creates and returns a callable proxy function into a dynamic link library. libname is the filename of the DLL; if this contains no path,, the DLL will be searched along the path (see os.searchPath()). funcname is the function inside the DLL to be called. This can be either the full name as exported by the DLL or the ordinal number of the function (for instance, MessageBoxA in USER32.DLL could also be located by its ordinal 452). prototype encodes the prototype of the function to be called as a list of character codes. This list starts with a single code for the return type of the function, followed by a '=', followed by the codes for the parameters. All parts are optional. The following character codes are defined (see also util.pack()):

A function that takes two ints, a string and a double and returns an unsigned integer would have a prototype of 'I=iiAd'. The prototype given has to be correct; otherwise the DLL function, if called, will probably crash the system or show some other undefined behaviour.

This is important enough to warrant a repeat: os.getDynLink() is an extremely powerful function. However, it cannot possibly check on its own whether its parameters make even remotely sense. Double-check the names and especially the prototypes you use or your system will misbehave. The function returns a userdatum that, if called with the correct parameters, will execute the DLL call.

Note: Most Windows DLL functions with string parameters exist in two versions: one that accepts ANSI strings (and carries an ...A suffix) and another for wide character (Unicode) strings (with a ...W suffix). For instance, GetModuleHandleA is the ANSI version of GetModuleHandle and GetModuleHandleW is the wide string version. os.getDynLink() does not automatically try to locate a DLL function if you omit the ...A or ..W suffix. You have to give the full and correct name of the function you want to call.

Here is a full example:

MessageBox=os.getDynLink("user32.dll","MessageBoxA","i=IAAI")  -- by name
-- MessageBox=os.getDynLink("user32.dll",452,"i=IAAI")  -- by ordinal, W2K
-- MessageBox=os.getDynLink("user32.dll",477,"i=IAAI")  -- by ordinal, WXP
print(MessageBox)
print(MessageBox.lib)    -- name of DLL
print(MessageBox.name)   -- name of function
print(MessageBox.proto)  -- prototype
print(MessageBox(0,"Call to MessageBox() succeeded...","getDynLink",0))

SetCursorPos=os.getDynLink("user32.dll","SetCursorPos","i=ii")
GetCursorPos=os.getDynLink("user32.dll","GetCursorPos","i=p")
ClipCursor=os.getDynLink("user32.dll","ClipCursor","i=p")

point=os.DynStruct("ii") -- see os.DynStruct()
rect=os.DynStruct("iiii")
print(#point,point.addr,point.proto)
print(#rect,rect.addr,rect.proto)

SetCursorPos(250,250)
os.writeDynStruct(rect,50,50,400,400)  -- initialise a rect structure
ClipCursor(rect)
while true do
  GetCursorPos(point)
  x,y=os.readDynStruct(point)
  util.printf("\r%4i %4i",x,y)
  if x<52 and y<52 then
    ClipCursor(0)
    break
  end
end

os.getenv(varname)
top of page

Returns the value of the process environment variable varname, or nil if the variable is not defined. Equivalent to reading os.ENV[varname].

os.getEnvBlock()
top of page

Returns a string with the current process environment. The string contains all environment variables, separated by a binary zero and terminated by two zeros.

os.getEnvTable()
top of page

Returns a table with the current process environment. The keys are the variables names.

os.getFileInfo(name,what)
top of page

Returns information about file or directory name. what is a string of characters that describe what to return. This can be any combination of the following nine characters (if what is empty or nil it is taken to be 'ACWsT'):

The function simply returns the requested file information in the order given by the characters in what. If what is '*i' or '*I' os.getFileInfo() returns a table, with five fields a, c, w, s, t (for ('*i') or A, C, W, s, T (for '*I'), instead of separate values.

Note: all time stamps are returned as UTC values. os.date() or os.convertToLocalTime() can be used to convert these values into local-time values.

os.getMSec(hiperf)
top of page

Returns a timer count in milliseconds. If hiperf is true the return value is based on relatively accurate high performance counters, else it is based on the system time. This is a highly system-dependent function and it should be used mostly to measure time differences. See also os.time().

os.getTimer(n)
top of page

Returns the value of one of five timers in milliseconds (n can be a value between 1 to 5). A call also resets timer n so that a sequence of calls to the same timer delivers the time differences between the calls. All five timers are initialised once when an Idle script begins execution.

os.getVersion()
top of page

This functions returns information about OS and version. Under Windows, it returns four values: the string 'windows', the major Version number, the minor Version number, and the build number.

os.isBinary(filename)
top of page

Returns true if file filename is a binary file. The heuristic to determine this is as follows: first the extension of filename is checked. If this is any of exe, dll, lib, obj, rar, 7z, zip, gz, jpg, jpeg, gif or png then the file is assumed to be binary. Otherwise, the first ~1000 bytes of filename are checked: if they contain non-whitespace values below 32, then filename is assumed to be binary. Almost needless to say, this function is not foolproof.

os.isDir(dirname)
top of page

Returns true if dirname is a directory (a symlink is also a directory).

os.isFile(filename)
top of page

Returns true if filename is a file (a hardlink is also a file).

os.killProcess(process) or process:killProcess()
top of page

Kills a spawned process (see os.spawnProcess()). Return true, if successful, or false and an error message.

os.makePath(drive,path,name,ext)
top of page

Constructs and returns a full path out of the arguments, any of which may be present or empty or nil.

os.mkDir(dirname)
top of page

Creates directory dirname. Returns true on success and false and an error message in case of an error.

os.prependWidePrefix(fname)
top of page

Adds prefix '\\?\' to string fname if the prefix is not already there and if fname is longer than 256 characters and returns the string. Adding this prefix allows the following functions in module os to support names longer than 260 characters:

os.readDir(dirname)
top of page

Returns two tables with the directories and files in directory dirname:

dirs,files=os.readDir('c:\\windows')

dirname can be either the name of a directory (in which case all entries in that directory will be returned) or a directory name with a wildcard pattern appended (in which case only those entries specified by the pattern will be returned). If there are no directories or files in dirname the respective tables are created but they will be empty.

os.readDynMem(dynmem)
top of page

Returns the content of memory block dynmem (which must have been allocated with a call to os.allocDynMem()) as a binary string. This string, in turn, can be used to unpack binary structures used for os.getDynLink() calls.

os.readDynStruct(dynmem)
top of page

This reads and unpacks a memory structure in dynmem (see os.DynStruct()) and returns all unpacked values. os.readDynStruct() can be used to decode binary structures received by a call to a dynamically linked function, in an external DLL (see os.getDynLink()). The function looks like this:

function readDynStruct(d)
  return util.unpack(readDynMem(d),d.proto)
end

os.remove(filename)
top of page

Deletes the file or directory with the given name. Directories must be empty to be removed. If this function fails, it returns nil, plus a string describing the error.

os.rename(oldname,newname)
top of page

Renames file or directory oldname to newname. If this function fails, it returns nil, plus a string describing the error.

os.rmDir(dirname)
top of page

Removes the (empty) directory dirname.

os.searchPath(name,path)
top of page

Searches the semicolon-separated path values in path for file name and returns the first match found or nil and an error message. If path is nil, name is searched for in the following order:

os.setenv(str)
top of page

Sets a process environment variable. str has to be a string in the format "varname=value". This is equivalent to writing value to os.ENV[varname].

os.setFileAttr(name,attr)
top of page

Sets the attributes for file or directory name. If attr is a string, it can contain one or more of the following characters, in any order (see os.Dir() for a description of file attributes):

If attr is a numerical value it has to be composed of the os.FA file attribute constants given in os.Dir(). This function returns true on success and false and an error message in case of an error.

os.setFileInfo(name,what,...)
top of page

This function sets access times and/or attributes on file or directory name; it is roughly the counterpart to os.getFileInfo(). what is a string that describes what items the function will set. The rest of the parameters are the actual times and/or atttributes values. what can be any combination of the following four characters (if what is empty or nil no values are set):

This function returns true on success and false and an error message in case of an error.

os.setFileTime(name,w[,a,c])
top of page

Sets access times on file or directory name. w gives time and date of last write; a (optional) gives time and date of last access and c (optional) gives time and date of creation. If the value in w, a or c is positive, it is taken to be the number of seconds since the epoch (1.1.1970, 00:00 UTC). If the value is negative, it is negated and taken to be the number of nanoseconds since 1.1.1601, 00:00 (see os.getFileInfo() for more details). A value of -1 for any of the three time values means that it will remain unchanged. To change the creation time of a file to now, use this call:

os.setFileTime(filename,-1,-1,os.time())

os.setlocale(locale[,category])
top of page

Sets the current locale of the program. locale is a 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 honoured.

If locale is the empty string, the current locate is set to an implementation-defined default locale. If locate is the string 'C', the current locate is set to the standard C locale. The locale is used for the definition of character classes for the pattern matching functions, see Simple Pattern and Regular Expressions.

When called with nil as the first argument, this function simply returns the name of the current locale for the given category.

os.setProcessPrio(process,prio) or process:setProcessPrio(prio)
top of page

Sets the priority class for a spawned process. prio is one of the four os.PF priority flags described for os.spawnProcess(). Returns true on success, false otherwise.

os.sleep(n)
top of page

Sleeps for n milliseconds.

os.spawnProcess(cmdname[,args])
top of page

Spawns a new process. The name of the executable is in cmdname. If cmdname does not contain a directory path, then os.spawnProcess() searches for the executable in the same order as os.searchPath() does for a nil path). All other parameters and options are in table args. Numerical fields in args (args[1] to args[#args]) are interpreted as command line arguments and simply appended to cmdname. If args contains a subtable env, then this will be the environment for the new process. If args contains any or all of the fields stdin, stdout or stderr and these fields hold handles to open files, then these file handles will be connected to the respective standard files of the newly created process. (Using the same handle for stdout and stderr does not always work as expected: some programs close the stderr handle upon startup. If both handles are identical closing one effectively closes the output channel altogether.) If args contains a field flags, this gives process creation flags. The following flags are defined (you can combine flags by ORing them):

If args contains a field show, this gives show window flags. The following values are defined (see also win32.showWindow()):

Here is a simple example:

local env={
  windir='ridniw',
  SnazzyStuff='boring',
  IDLE_PATH=os.ENV['IDLE_PATH'] -- else PrintSpawnParameters might not run
}
local r,w=io.pipe()
local p=os.spawnProcess('idle.exe',{'PrintSpawnParameters.idle',
  'one',2,3,4,'five',env=env,stdout=w,flags=os.PF.NEW_CONSOLE})
os.waitProcess(p)
print('exit code:',p.exitcode)
w:close()
for line in r:lines() do print(line) end
r:close()

The function returns a process value that can be used with os.waitProcess(), os.killProcess() and os.setProcessPrio(). In case of an error, it returns false and an error string. You can also query the following fields:

os.splitPath(pathname)
top of page

Splits the path in pathname into up to four parts and returns them: drive, path, name and extension. If you feed the four elements back into os.makepath() you will get a valid path.

os.time([table])
top of page

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, and day, and may have fields hour, min, sec, and isdst (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 the epoch (1.1.1970, 00:00 UTC). 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()
top of page

Returns a string with a name that can be used for a temporary file. The file must be explicitly opened and explicitly removed when no longer needed.

os.waitProcess(process) or process:waitProcess()
top of page

Waits until a spawned process terminates (see os.spawnProcess()) and returns its exitcode. In case of error os.waitProcess() returns false and an error message.

os.walkDir(path,pattern[,flags[,fileCB[,dirCB]]])
top of page

Walks directory (or directory tree) path, looking for entries according to pattern. If path is empty, the current directory is used. If pattern is empty, '*' is assumed. pattern can be either a usual wildcard pattern (with one small extension: a semicolon separates multiple wildcards, so that '*.c;*.cpp;*.h' nicely matches C/C++ files) or a regular expression. flags can be any combination of the following characters:

If fileCB and dirCB are nil the function simply returns a table with the full pathnames of all found entries.

For more control about the process of harvesting entries, you can define two callback functions. fileCB is called whenever os.walkDir() finds a file (if you define fileCB, os.walkDir() will not fill its internal return table). This callback function receives three parameters:

The callback function should return one of three values:

dirCB is a callback function that is called once immediately before a directory is entered and again immediately after it has been left. It receives two parameters:

The callback should return one of the three values described for fileCB.

os.writeDynMem(dynmem,s)
top of page

Initialises the memory block dynmem (which must have been allocated with a call to os.allocDynMem()) with the content of binary string s. This string, in turn, can be initialised by a call to util.pack(). This function can create binary structures used for os.getDynLink() calls.

os.writeDynStruct(dynmem,...)
top of page

Packs all received values into memory structure dynmem (see os.DynStruct()) and returns the packed binary string. This function can be used to initialise binary structures used as parameter in a call to a dynamically linked function, in an external DLL (see os.getDynLink()). The function looks like this:

function writeDynStruct(d,...)
  return writeDynMem(d,util.pack(d.proto,...))
end

Module package
top of page

The package library provides facilities for loading and building modules. Two of its functions, require() and module(), are exported into the global environment. All other functionality is made available through table package.

module(name[,...])
top of page

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

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

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

require(modname)
top of page

Loads module modname. The function starts by looking into table package.loaded to determine whether modname is already loaded. If it is, then require() returns the value stored at package.loaded[modname]. Otherwise, it tries to find a loader for the module. To find a loader, require() first queries package.preload[modname]. If it has a value, this value (which should be a function) is the loader. Otherwise require() searches for an Idle file with a loader using the path stored in package.path. If that fails, it searches for a DLL with a C loader using the path stored in package.cpath. If that also fails, it searches for a loader along the search path defined by archives mounted by module zio (if any). If that fails, it searches along the process environment variable PATH for an Idle file (first for .idle, then .idol). If that fails, it tries an all-in-one loader (see below).

When loading a C library, require() first uses a dynamic link facility to link the application with the library. If it succeeds, it tries to find a C function inside this 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 name of the loader function will be luaopen_b_c.

If require() finds neither an Idle library nor a C library for a module, it calls the all-in-one loader. This loader 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 a single library, with each submodule keeping its original open function.

Once a loader is found, require() calls the loader with a single argument, modname. If the loader returns any value, require() assigns the returned value to package.loaded[modname]. If the loader returns no value and has not assigned any value to package.loaded[modname], then require() assigns true to this entry. In any case, require() returns the final value of package.loaded[modname].

If there is any error loading or running the module, or if it cannot find any loader for the module, then require() signals an error.

package.cpath
top of page

The path used by require() to search for a DLL. Idle initialises package.cpath in a similar way it initialises the Idle search path package.path, using the environment variable IDLE_CPATH or the default path which is defined as '.\?.dll;..\?.dll;<IDLE_DIR>\?.dll;<IDLE_DIR>\loadall.dll' with <IDLE_DIR> being a placeholder for the directory from which the Idle interpreter was loaded. See package.path for details and an example.

package.import(module[,name,...])
top of page

Imports global entities from a module into the current environment. The first parameter is the module table from which to import (os, string, et cetera); the remaining parameters describe what to import from module. If this list is empty, all global functions and tables from module (with the exception of module._M) are imported. Otherwise, name is a string with the name of the global entity to import. Imported names can be changed by appending 'as newname' to the name such that

import(os,'getTimer as mytimerfunc')

imports the function os.getTimer() into the current environment as mytimerfunc.

package.ipath
top of page

The path used by the predefined macro __INCLUDE() (see Predefined Macros) to search for include files; default is the content of environment variable IDLE_IPATH or, if that variable is not defined, of environment variable PATH.

package.loaded
top of page

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

package.loadlib(libname,funcname)
top of page

Dynamically links the host program with the C library libname. Inside this library, looks for a function funcname and returns this function as a C function. funcname must follow the Idle calling protocol.

This is a low-level function. It completely bypasses the package and module system. Unlike require(), it does not perform any searches along IDLE_PATH or IDLE_CPATH and does not automatically add an extension. libname must be the complete filename of the C library, including if necessary a path and extension (however, if libname does not specify an absolute pathname, the underlying Windows functions will search the system-wide PATH; see os.searchPath() for details). funcname must be the exact name exported by the C library (which may depend on the C compiler and linker used).

package.path
top of page

The path used by require() to search for an Idle loader. At start-up, Idle initialises this variable with the value of the environment variable IDLE_PATH or with a default path (see below), if the environment variable is not defined. Any ';;' in the value of the environment variable is replaced by the default path which is defined as '.\?.idle;..\?.idle;<IDLE_DIR>\?.idle;<IDLE_DIR>\init.idle' with <IDLE_DIR> being a placeholder for the directory from which the Idle interpreter was loaded.

A path is a sequence of templates separated by semicolons. For each template, require() will change each question mark in the template by filename, which is modname with each dot replaced by a directory separator; then it will try to load the resulting filename. So, for instance, if the Idle path is

'.\?.idle;.\?.idol;c:\windows\?\init.idle'

the search for an Idle loader for module foo will try to load the files .\foo.idle, .\foo.idol, and c:\windows\foo\init.idle, in that order.

package.preload
top of page

A table to store loaders for specific modules (see require()).

package.seeall (module)
top of page

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

Module strict
top of page

This module provides a certain measure of control of accessing and using global variables in Idle programs. It has two basic modes: a less strict one, in which variables have to be initialised before first use; and a very strict mode, in which all global variables need explicit declarations. The Idle runtime is implemented with the latter mode enabled.

strict.declareGlobal(n,v[,m])
top of page

Declares identifier n as global variable in module m and initialises n with v (if n is already declared, this function does nothing). If m is nil or missing, n will be inserted into the global environment (that is, _G). Only required if strict.draconian (see below) is true.

strict.declareGlobals(t)
top of page

This convenience function allows to declare many variables with a single call. Table t contains the names and values of the variables to declare. All variables will be inserted into the calling module. Example:

strict.declareGlobals{x=math.pi,y=true,
z=function(n) return n*n end,
s='strings are nice'}

strict.getModulename(m)
top of page

Returns the printable name of module m or '<UNKNOWN>' if the name cannot be found. Useful in strict.handler().

strict.handler(m,n,v)
top of page

This is the error handler that is called if strict catches an access to an undeclared variable. The default handler prints a helpful message and terminates the program. However, you can write your own handler function and assign it to strict.handler(). m and n are the offending module and identifier, respectively. v is either nil (if a reading access was caught) or the value that normally would have been assigned to n.

Among other things, this feature allows a custom handler 'to smuggle' variables into modules, if some conditions are met.

strict.isDeclared(n[,m])
top of page

Returns true if n is declared in module m. If m is nil or missing the global environment (that is, _G) is used.

strict.registerModule(m)
top of page

Registers module m into the strict system. A non-registered module is not affected by the strict module which can be a blessing or a curse. All standard Idle modules are either pre-registered or self-registering upon first use. strict.registerModule() modifies the metatable of module m (specifically, it assigns handlers to __index and __newindex), so registering a third-party module may conflict with other uses. This function returns nothing.

strict.strict
top of page

This is a boolean variable that controls whether strict does check variable accesses. Setting it to false effectively disables the strict module. The default is true.

strict.draconian
top of page

This is a boolean variable that controls whether strict works in draconian or in weakling mode. Weakling mode allows global variables to be created with a simple assignment; strict will only complain if non-initialised globals are referenced. This mode is the default (i.e. strict.draconian is by default false). In draconian mode all global variables have to be explicitly declared with strict.declareGlobal() or strict.declareGlobals() before they can be used. However, different parts of a program can use different values for strict.draconian.

Hint: setting strict.draconian to true means that global functions cannot be defined without a previous declaration:

strict.draconian=true
function xbad() end -- won't work
declareGlobal('xgood1',0) -- initialiser can be anything but nil
function xgood1() end -- these two will work
declareGlobal('xgood2',function() end)

Module string
top of page

This library provides functions for string manipulation, such as finding and extracting substrings. It also supplies two pattern-matching engines, a relatively simple internal library and a full-blown implementation of Perl regular expressions.

When indexing strings in Idle, the first character is at position 1 (not at 0, as in C). Strings are not necessarily null-terminated and they can contain any binary values, including binary zeros. The length of a string is stored internally as an explicit value. In general, indices are allowed to be negative; such values 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 most string functions in object-oriented style. For instance:

j=string.byte(s,i)
s4=string.sub(s,1,4)
-- can be written as
j=s:byte(i)
s4=s:sub(1,4)

Besides being easier to type and understand, oo-style calls have the advantage of generating slightly faster code.

string.byte(s[,i[,j]])
top of page

Returns the internal numerical codes of the characters s[i], s[i+1],..., s[j]. The default value for i is 1; the default value for j is i. Note that numerical codes are not necessarily portable across platforms.

string.char(...)
top of page

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

string.chomp(s[,z])
top of page

Deletes string z (default is '\n') from string s if z forms the last part of s (a namesake function is traditionally used to cut off newlines in the Perl world).

string.compare(s1,s2[,from[,len]])
top of page

This function compares two substrings in s1 and s2. The start position in both strings and the length is given in the optional parameters from (default 1) and len (default length of s1). If the substrings are equal, the function returns 0. If s1 is less then s2, it returns -1; if s1 is greater than s2, it returns 1. If from is greater than len, it returns nil. The function takes the current locale into account (see os.setlocale()).

string.dump(function)
top of page

Returns a string containing a binary representation of the given function, so that a later loadstring() on this string returns a copy of the function. function must be an Idle function without upvalues.

string.find(s,pattern[,init[,plain]])
top of page

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

If the pattern has captures, then in a successful match the captured values are also returned, after the two indices.

string.format(formatstring,...)
top of page

Returns a formatted version of its arguments following the description given in its first argument (which must be a string). The format string follows the same rules as the printf family of standard C functions. The only differences are that the options/modifiers *, l, L, n, p, and h are not supported and that there is an extra option, q. The q option formats a string in a 'quoted' form suitable to be safely read back by the Idle interpreter: the string is written between double quotes, and all double quotes, newlines, embedded zeros, and backslashes in the string are correctly escaped when written. For instance, the call

string.format('%q','a string with "quotes" and \n new line')

will produce the string:

"a string with \"quotes\" and \
new line"

The options c, d, E, e, f, g, G, i, o, u, X, and x all expect a number as argument, whereas q and s expect a string. This function does not accept string values containing embedded zeros, except as arguments to the q option.

string.gmatch(s,pattern)
top of page

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

s = "hello world from Idle"
for w in string.gmatch(s,"%a+") do print(w) end

will iterate over all the words from string s, printing one per line. The next example collects all key=value pairs from the given string into a table:

t = {}
s="from=world, to=Idle"
for k,v in string.gmatch(s,"(%w+)=(%w+)") do t[k]=v end

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

string.gsub(s,pattern,repl[,n])
top of page

Returns a copy of s in which all occurrences of the pattern have been replaced by a replacement string specified by repl, which may be a string, a table, or a function. gsub also returns, as its second value, the total number of substitutions made.

If repl is a string, then its value is used for replacement. The character % works as an escape character: any sequence in repl of the form %n, with n between 1 and 9, stands for the value of the n-th captured substring (see below). The sequence %0 stands for the whole match. The sequence %% stands for a single %.

If repl is a table, then the table is queried for every match, using the first capture as the key; if the pattern specifies no captures, then the whole match is used as the key.

If repl is a function, then this function is called every time a match occurs, with all captured substrings passed as arguments, in order; if the pattern specifies no captures, then the whole match is passed as a sole argument.

If the value returned by the table query or by the function call is a string or a number, then it is used as the replacement string; otherwise, if it is false or nil, then there is no replacement (that is, the original match is kept in the string).

The optional last parameter n limits the maximum number of substitutions to occur. For instance, when n is 1 only the first occurrence of pattern is replaced.

Here are some examples:

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

string.insert(s1,s2,i)
top of page

Inserts string s2 into string s1 at position i. i may be negative, in which case it is counted from the end of s1.

string.join()
top of page

This is a shortcut for table.concat().

string.len(s)
top of page

Receives a string and returns its length. The empty string "" has length 0. Embedded zeros are counted, so "a\000bc\000" has length 5. For strings, this functions does the same as the length operator #.

string.lower(s)
top of page

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

string.match(s,pattern[,init])
top of page

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

string.reFind(s,pattern[,init[,opt]])
top of page

Looks for the first match of pattern in the string s, similar to string.find(). pattern can be a Perl style regular expression (see Regular Expressions); if pattern is the empty string, the function reuses the last compiled pattern (this feature should only be used in tight, controlled loops because the Idle runtime also calls string.reFind() at various places). If the function finds a match, then it returns the indices of s where this occurrence starts and ends; otherwise, it returns nil. A third, optional numerical argument init specifies where to start the search; its default value is 1 and it may be negative. A fourth, also optional, string argument specifies the match options. These are defined by a combination of the following character codes (see the PCRE regular expression manpage for further details):

If the pattern has captures, then in a successful match the captured values are also returned, after the two indices.

string.reGMatch(s,pattern[,opt])
top of page

Returns an iterator function that, each time it is called, returns the next captures from pattern over string s. If pattern specifies no captures, then the whole match is produced in each call. Matching is controlled by the options in opt, see string.reFind() for details. This function works like string.gmatch(); the pattern, however, can be a regular expression (see Regular Expressions).

For this function, a '^' at the start of a pattern does work as an anchor, because Perl style regular expressions support strings with more than one anchor (see multi-line mode in the options description of string.reFind()).

string.reGSub(s,pattern,repl[,n])
top of page

Returns a copy of s in which all occurrences of pattern have been replaced by a replacement specified by repl, which may be a string, a table, or a function. This function works like string.gsub(); the pattern, however, can be a full regular expression (see Regular Expressions). If the repl parameter is a string, it can contain backreferences to groups defined in pattern; these can be referenced either by number (i.e. $1 (or ${12} if more than one digit), up to the number of defined groups) or by name, if the pattern included named groups. Here's a simple example:

s='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
s=s:reGSub('(..)(?<two>..)(..)(..)(..)(..)(..)(..)(..)(?<ten>..)(..)(..)',
  '${12}${11}${ten}$9$8$7$6$5$4$3${two}$1')
print(s)

See the PCRE man page for all the gory details.

string.reMatch(s,pattern[,init[,opt]])
top of page

Looks for matches of pattern in the string s, similar to string.reFind(). pattern can be a Perl style regular expression (see Regular Expressions); if pattern is the empty string, the function reuses the last compiled pattern (this feature should only be used in tight, controlled loops because the Idle runtime also calls string.reMatch() at various places). If the function finds one or more matches or captures, it returns the found match(es) or captures; otherwise, it returns nil. A third, optional numerical argument init specifies where to start the search; its default value is 1 and it may be negative. A fourth, also optional, string argument specifies options; see string.reFind() for details.

string.rep(s,n)
top of page

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

string.replace(s,p,repl[,init])
top of page

Returns a copy of s in which all occurrences of string p have been replaced by a replacement string (but no pattern) specified by repl. A fourth, optional numerical argument init specifies where to start replacement; its default value is 1 and it may be negative.

string.reverse(s)
top of page

Returns a string that is the string s reversed.

string.split(s,p)
top of page

Splits string s with pattern p and returns a table with the resulting substrings. p can be a character like '\n', a string or a regular expression. If s starts with p, the first entry in the returned table will be the empty string.

string.sub(s,i[,j])
top of page

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

string.suffix(s,p)
top of page

Makes sure that string s ends with string p by appending p to s, if neccessary.

string.toHex(b[,sep[,fmt]])
top of page

Converts a binary string b into a textual representation of its bytes and returns this as a string. sep is the separator between the bytes (default is empty); fmt is the format string used to format for byte values (default is '%02x', for details see string.format()). Example:

s='A test\0\0\string'
print('$'..s:toHex(' ','<%02x>')..'$')

will print

$<41> <20> <74> <65> <73> <74> <00> <00> <73> <74> <72> <69> <6e> <67>$

string.tr(s,from,to[,re])
top of page

Transliterates all characters in string s. from and to are two strings that describe how to perform the operation: every character in from is replaced by its counterpart in to. If to has fewer characters than from, the missing characters are taken to be the last character of to. A binary zero in to means that the corresponding character in from is deleted. The optional parameter re selects which characters in s get transformed (default is all characters which are in from). Examples:

s="Folks, this is the last one. Promised."
print(s:tr(".aeiou","!AEIOU"))
print(s:tr(".aeiou","!\0"))

will print

FOlks, thIs Is thE lAst OnE! PrOmIsEd!
Flks, ths s th lst n! Prmsd!

string.trim(s[,r[,w]])
top of page

Trims string s. r is a regular expression that describes what should be trimmed (default is '\s+' which means all whitespace); w is a character that can be either 'l' (default), 'r' or 'b', to trim left, right or both.

string.upper(s)
top of page

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

Simple Patterns
top of page

This describes the internal pattern matching engine that Idle 'inherited' from its 'parent' Lua. Lua's pattern matching is not as powerful as full regular expressions but for many simpler tasks it is more than adequate: many of the concepts (character classses, quantifiers) are similar to regular expressions. However, Lua patterns are certainly easier to understand and to deal with than full-blown Perl regular expressions.

Character Class
top of page

A character class is used to represent a set of characters. The following combinations are allowed in describing a character class:

For all classes represented by a single letter (%a, %c, et cetera), the corresponding uppercase letter represents the complement of the class. For instance, %S represents all non-space characters.

The definitions of letter, space, and other character groups depend on the current locale. In particular, the class [a-z] may not be equivalent to %l.

Pattern Item
top of page

A pattern item may be

Pattern
top of page

A pattern is a sequence of pattern items. A '^' at the beginning of a pattern anchors the match at the beginning of the subject string. A '$' at the end of a pattern anchors the match at the end of the subject string. At other positions, '^' and '$' have no special meaning and represent themselves.

Captures
top of page

A pattern may contain sub-patterns enclosed in parentheses; they describe captures. When a match succeeds, the substrings of the subject string that match captures are stored (captured) for future use. Captures are numbered according to their left parentheses. For instance, in the pattern "(a*(.)%w(%s*))", the part of the string matching "a*(.)%w(%s*)" is stored as the first capture (and therefore has number 1); the character matching "." is captured with number 2, and the part matching "%s*" has number 3.

As a special case, the empty capture () captures the current string position (a number). For instance, applying the pattern "()aa()" on the string "flaaap" will produce two captures: 3 and 5.

A pattern cannot contain embedded zeros. Use %z instead.

Regular Expressions
top of page

The internal pattern-matching engine just described is supplemented by a full implementation of Perl style regular expressions. Idle uses the well-known and respected PCRE library, created by Phil Hazel. PCRE is a fast and mature implementation; it supports almost all of Perl's regular expression features (or, as some would say, idiosyncracies). Perl style regular expressions are mighty beasts indeed, although they can be a wee bit unwieldy at times. There are many options, lots of tricks and a few things that seem designed to confuse unwary newcomers.

For this reason, the single best source for further reference documentation is the PCRE man page. Another quite usable reference is the Perl regular expression documentation. Two good general sites for all things regex are the Regular Expression Library and Regular-Expressions.info.

The main reason why Idle provides two pattern-matching engines (and that's not counting the lpeg module) is versatility. There are certain classes of problems that are better (or easier) solved with the internal library (not to talk about the significant number of external libraries already written for Lua... all this code should work 'right out of the box' with Idle). On the other hand, regular expression can do things (albeit sometimes at the expense of readability) that are way beyond the simpler matching engine Idle has inherited from Lua.

Both libraries are reasonably efficient. In informal tests, performance differences for comparable operations were mostly in the five to ten percent range; with the internal engine not always providing the faster implementation. This is especially true for calls into PCRE functions that reuse an already compiled pattern: these tend to be a bit faster than calls to the internal library. It pays, though, to invest some thought into making a complicated pattern as efficient as possible, especially if it will be used to process dozens of megabytes of input data.

One final hint: strings in Idle are either of the 'short' or the 'long' variety. The short strings use '' and "" as delimiters, whereas long strings use [=[ ]=] and ``. Short strings interpret \X style escapes, so if you want to use those for regular expressions (which is pretty unavoidable), get in the habit of escaping your escapes. Or, perhaps better, use the long string delimiters: they do not interpret escapes. These three strings are more or less ugly but mean the same:

"\\(((?:(?>[^()]+)|(?R))*)\\)(\\d\\d)"
[=[\(((?:(?>[^()]+)|(?R))*)\)(\d\d)]=]
`\(((?:(?>[^()]+)|(?R))*)\)(\d\d)`

Module table
top of page

This module provides generic functions for table manipulation and provides all its functions inside the table table. Most functions in this library assume that the table represents an array (or a list). For these functions, the length of a table means the result of the length operator #.

All tables generated by Idle or Idle function calls can be used in a object-oriented style as Idle sets a metatable where the __index field points to table table. For instance:

t2=table.copy(t1)
s=table.concat(t,5,9)
table.save(t,'savedtable')
-- could be written as
t2=t1:copy()
s=t:concat(5,9)
t:save('savedtable')

Besides being easier to type and understand, oo-style calls have the advantage of generating slightly faster code.

table.copy(t[,shallow])
top of page

Returns a deep or, if shallow is true, a shallow copy of table t. For a deep copy values of type boolean,number, string, table and Idle function (so long as they have no upvalues) are copied. Userdata cannot be copied without further knowledge about their internal structure, so a reference is included instead.

For a shallow copy only the first level of t is copied; values of type boolean,number, string and Idle function (so long as they have no upvalues) are copied, while tables and userdata are included by reference.

table.concat(t[,sep[,i[,j]]]) or t:concat([sep[,i[,j]]])
top of page

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

table.copy(t,deep) or t:copy()
top of page

Returns a deep or a shallow copy of table t. If deep is omitted or false, then the copy is shallow and tables elements are "copied" by reference. If deep is true, table elements themselves are copied as well. Cyclic and recursive tables are handled correctly.

table.grep(t,f[,...]) or t:grep(f[,...])
top of page

Applies a filter function f over all entries of table t. f can be either a string (in which case it is first loaded via loadstring()) or an Idle function. f is called in turn for all elements in t, receiving the field key and field value as parameters k and v (and the ... parameter list if given). For each such call that returns true, the corresponding field value is copied into a second table which is returned as the result of table.grep(). If a call to f returns true and a second value, then the second value is copied into the result table instead of the original value. A simple example:

dir,files=os.readDir("*")
OS1files=files:grep('string.reFind(v,"^OS")!=nil')
OS2files=files:grep(function(k,v) return string.reFind(v,"^OS")!=nil end)

table.inject(t1,[pos,]t2) or t1:inject([pos,]t2)
top of page

Inserts all fields of array t2 into array t1 at position pos, shifting up other elements to open space, if necessary. If t2 is not a table, this function simply calls table.insert().

table.insert(t,[pos,]value) or t:insert([pos,]value)
top of page

Inserts element value (which can be any Idle type, including a table) at position pos in table t, shifting up other elements to open space, if necessary. The default value for pos is n+1, where n is the length of t, so that a call table.insert(t,x) inserts x at the end of table t.

table.invert(t)
top of page

This inverts table t such that its keys and values are swapped.

local t=table.new{a='AAA',b='BBB',x='XXX'}
t:print()          --> a: AAA; x: XXX; b: BBB
t:invert():print() --> AAA: a; XXX: x; BBB: b

table.load(name)
top of page

Loads a previously saved table (see table.save()) from file name and returns it (or nil, in case of an error). See also table.unpickle().

table.map(t,f[,...]) or t:map(f[,...])
top of page

Applies a function f over all entries of table t. f can be either a string (in which case it is first loaded via loadstring()) or an Idle function. f is called in turn for each element in t, receiving the field key and field value as parameters k and v (and the ... parameter list if given). The return value of each call is copied back into table t.

A simple example:

local t=table.new({1,2,3,4,5})
t:map('v+v')  -- replaces all t[i] with t[i]+t[i]
t:map(function (k,v) return v*v end)  -- replaces t[i] with t[i]*t[i]

table.maxn(t) or t:maxn()
top of page

Returns the largest positive numerical index of the given table, or 0 if the table has no positive numerical indices. (To do its job this function does a linear traversal of the whole table.) Using the # operator, if possible, is preferable.

table.new([t[,n]])
top of page

If called without a parameter, returns an empty table. This way of creating an empty table is preferable to using the idiom {}, because the returned table may use the object-oriented versions of the table functions.

If parameter t is an already existing table, this function returns t with its metatable modified such that t can be used with the object-oriented versions of the table functions. Therefore, these two lines are equivalent:

t={} t=table.new(t)
t=table.new()

If parameter t and optional parameter n are numerical values this function returns a new empty table with space pre-allocated for t array elements and n non-array elements.

table.pickle(t) or t:pickle()
top of page

Converts table t into a binary representation and returns this as a string. t can contain the simple Idle types boolean, number and string as well as tables (cyclic and recursive tables are handled correctly, but see the hints below). Functions stored in table t are supported so long as they do not use upvalues. The binary string that is returned by table.pickle() can be used with table.unpickle() to recreate the original table(s).

table.pickle() uses a local table to keep track of already pickled tables and will not attempt to pickle tables already seen; instead it returns an internal reference. If two tables t1 and t2 include a third table t3 as a subtable, the call t1:pickle () will return a binary string with t1 and t3, whereas a subsequent call t2:pickle () will return t2 and an internal reference to t3. This means that table.unpickle() is able to recreate all tables and their dependencies, if the tables are unpickled in the same order they were pickled.

If you do not want this feature, you can reset the internal referencing mechanism between calls to table.pickle() by calling table.pickle(nil): this clears all stored references in the internal table.

table.print(t[,h[,f]]) or t:print([h[,f]])
top of page

Prints a dump of table t with optional header h and footer f. Cyclic and recursive tables are handled correctly.

table.remove(t[,pos[,len]]) or t:remove([pos[,len]])
top of page

Removes from table t len elements starting with position pos, shifting down other elements to close the space, if necessary. Returns the value of the removed elements. The default value for pos is n, where n is the length of the table, so that a call table.remove(t) removes the last element of table t. The default for len is 1.

table.save(t,name) or t:save(name)
top of page

This function calls table.pickle() to convert table t into a binary representation which is then saved in name. Saved tables can be loaded with table.load().

table.slice(t,[,pos[,len]]) or t:slice([pos[,len]])
top of page

Returns a slice of table t, starting from index pos and with length len. pos defaults to 1 and len to the length of the table.

table.sort(t[,comp]) or t:sort([comp])
top of page

Sorts table elements in a given order, in-place, from t[1] to t[n], where n is the length of the table t. If comp is given, then it must be a function that receives two table elements, and returns true when the first is less than the second (so that not comp(t[i+1],t[i]) will be true after the sort). If comp is not given, then the standard Idle operator < is used.

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.splice(t1,pos,len,t2) or t1:splice(pos,len,t2)
top of page

Removes elements from table t1, starting from index pos and with length len, then inserts table t2 into t1 at index pos. The function returns the removed elements as a table.

table.unpickle(s)
top of page

Recreates and returns a table from binary string s. s must be the result of a previous call to table.pickle(). See table.pickle() for tables that contain subtables.

Module task
top of page

Module task provides primitives for executing chunks of Idle code in a pre-emptive multitasking environment. Each chunk executes as a separate OS thread and receives its own private state (for the stack, global variables and functions, et cetera). Tasks can communicate via message queues (see task.post() and task.receive()) or any other IPC mechanism, such as sockets or pipes.

The Idle runtime is thread-safe. The one (possibly) non-safe function is os.setlocale(): changing the locale re-initialises the character tables used by the regular expression engine. This may lead to unexpected behaviour if, after a change of locale, an already compiled regular expression is reused. This could happen in two cases, both fairly theoretical in nature: if string.reFind() or string.reMatch() is called with an empty pattern (thereby implicitly reusing the last compiled pattern) and in a loop that calls an iterator generated by string.reGMatch(). Changing the locale in these circumstances should be avoided.

File accesses (as well as other shared resource accesses) are not synchronised between threads: it is the responsibility of threads to lock files or file regions (or other shared resources) if they require exclusive access.

task.cancel([id])
top of page

This function terminates a task. If id is missing or 0, the calling task is terminating itself and the function never returns. Otherwise, the task identified by the number id is forcibly terminated (ie killed). This feature should not normally be used to terminate other tasks, as it does not free or close any resources held by the task and may leave the application in an undefined state. Tasks should either terminate normally by reaching the end of their execution path (or by using a return statement) to return control in an orderly fashion or by calling task.cancel() without an id, thereby terminating themselves. See also task.forcereturn().

task.create(name,chunk[,args])
top of page

The task.create() function creates an Idle state named name inside a new thread and executes chunk in it. If chunk is a string of the format '@filename', then the new thread loads and executes the file filename. Otherwise, it executes the content of chunk as Idle code. args is a table with arguments for the new task (which the task can access through the arg table). If task.create() is successful, it returns an integer value greater than 0; this is the id of the newly created task. In case of an error task.create() returns a negative value.

task.find(name)
top of page

This function returns the numerical id of task name. If the task cannot be found task.find() returns a negative value.

task.forcereturn(id)
top of page

This function forces task id to return control as soon as possible, effectively ending it in a controlled fashion. This can be used to control execution of runaway threads (ie in sandboxes). See also task.cancel().

task.id()
top of page

The function task.id() returns the numerical id of the running task.

task.isrunning(id)
top of page

This returns true if the task identified by the number id is running.

task.list()
top of page

This function returns a table of subtables with information about the active tasks. Each subtable has the following elements:

Here is a simple example:

util.printf('\nID   SOURCE           MSG COUNT NAME\n')
util.printf('---- ---------------- --------- ----------------\n')
if tl then
  for i,t in pairs(tl) do
    util.printf('%4d %-16.16s %9d %-16.16s\n',i,t.source,t.msgcount,t.name)
  end
end

task.post(id,msg,flags)
top of page

The task.post() function appends the contents of string msg to the message queue of the task identified by the number id. flags is a general-purpose number value (up to 32 bit) that is posted with msg. msg may include binary zeros. If the function succeeds, it returns id. Otherwise, it returns a negative value.

task.receive([timeout])
top of page

The task.receive() function gets the next entry from the message queue of the current task. If timeout is missing or equal to -1, the function waits until there is a message in the queue. Otherwise, timeout specifies the maximum interval in milliseconds to wait if there are no messages in the queue. The function returns the data (which may contain binary zeros) and flags posted (see task.post()) and 0 if it succeeds. On timeout it returns nil, nil and -2. In case of error it returns nil, nil and -1.

Module template
top of page

Module template implements basic template and preprocessing functionality. Functions are called via table template.

template.execute(src,name)
top of page

Preprocesses the string in src as chunk name (see template.fill()) and loads and executes the result as Idle code. Returns the results of running the chunk or raises an error.

template.fill(src,name)
top of page

Preprocesses the string in src as chunk name (default 'anonymous') and returns the result. Preprocessing works by executing all lines which begin with a '#' character as Idle code or else letting them pass through unchanged. Two further preprocessing features are support for a textual #include facility and the replacement of macro variables which are denoted by ${var} and refer to the global Idle variable var. All lines starting with '#' have to be valid Idle code (or an #include <file> statement) but the rest of the source string need not be Idle: it could be a HTML or css template or any other text.

A trivial example:

pp=[=[
#PARAS=3
#include <header.tmpl>
#for i=1,PARAS do
  <p>This is paragraph number ${i}</p>
#end
#include <footer.tmpl>
]=]
TITLE='Whatever...'
local s=template.fill(pp)

with header.tmpl:

<html><title>${TITLE}</title><body>

and footer.tmpl:

</body></html>

will produce this result:

<html><title>Whatever...</title><body>
<p>This is paragraph number 1</p>
<p>This is paragraph number 2</p>
<p>This is paragraph number 3</p>
</body></html>

#include <file> statements are expanded via calls to util.includeFile(), so path searches along PATH are supported. template.fill() supports a maximum of 512 include files (this is an arbitrary limit designed to break possible recursion in the included files).

Module util
top of page

This module provides (mainly simple) utility functions. All functions are called through the util prefix.

util.bitAnd(v1,v2[,...])
top of page

Performs a numerical and operation with all given parameters and returns the result. This function works reliably with integer values of up to 52 bits.

util.bitNot(v)
top of page

Performs a numerical not operation with the given parameter and returns the result. This function works reliably with integer values of up to 52 bits.

util.bitOr(v1,v2[,...])
top of page

Performs a numerical or operation with all given parameters and returns the result. This function works reliably with integer values of up to 52 bits.

util.bitXor(v1,v2[,...])
top of page

Performs a numerical xor (exclusive or) operation with all given parameters and returns the result. This function works reliably with integer values of up to 52 bits.

util.dayOfWeek(d,m,y)
top of page

Takes a date with day d, month m and year y and returns a value of 1 to 7 (plus a three-letter string with the shortened name) for the day of the week, with Sunday being day 1.

util.daysInMonth(m,y)
top of page

Returns the number of days in month m of year y.

util.if2(cond,t,f)
top of page

Returns t if cond is true and f otherwise.

util.includeFile((name,path[,read]))
top of page

Searches for file name along path. If found and read is true, returns a string with the file content. If found and read is false or missing, executes the file by calling dofile(). In this case, the function returns the results of the dofile() call.

if path is nil or missing, the value in package.path is used.

util.isLeap(y)
top of page

Returns true if year y is a leap year.

util.md5(message)
top of page

Computes and returns the 128-bit MD5 message-digest of the string message. The output is formatted as a binary string with 16 characters (to convert this into a printable string, see string.toHex()).

util.md5decrypt(message,key)
top of page

Decrypts a string. The input message must be the result of a previous call to util.md5encrypt(). For any message, key and seed, we have that

util.md5decrypt(util.md5encrypt(msg,key,seed),key)==msg

util.md5encrypt(message,key[,seed])
top of page

Encrypts a string, using MD5 in CFB (Cipher-feedback mode). message is an arbitrary binary string to be encrypted. key is an arbitrary binary string to be used as a key. seed is an arbitrary binary string (maximum length 16 bytes) to be used as a seed. The function returns the cyphertext as a binary string. If no seed is provided, util.md5encrypt() uses the result of os.time() as a seed. It is recommended that you use different seeds for each message; the seed itself is not private, and should contain no private data, because it goes plain in the beginning of the encrypted message. The length of the returned cyphertext is the length of the message plus the length of the seed plus one.

util.pack(packstr,...)
top of page

Packs strings and numerical values into a binary string and returns it. packstr is a format string that describes what to pack, followed by the items to pack. The format string is a combination of character codes, followed by optional length values. The following character codes (and their C equivalents) are defined:

A character code can be followed by an optional length. For the two string formats, this denotes how many bytes the string will take up in the packed string (0 means the complete input string, but without terminating zero). A longer string is right trimmed; a shorter string is filled with either binary zeros or spaces, depending on the format character. A length for numerical formats means that this number of items is to be packed. A few examples:

util.pack('iii',i1,i2,i3)  -- 'iii' (or 'i3') packs three integer values
                           -- the result will be a 12-byte binary string
s='teststring'
util.pack('A4s',s,0)
-- the result string will be 'test\0\0'
util.pack('ca0dIc',#s,s,math.pi,420420,127)
-- the result string will be 24 bytes long: 1+10+8+4+1

Calling util.pack() with just a pack string but no actual values to pack will calculate and return the length of the resulting binary string:

print(util.pack('a4(c4)idsx')) -- prints 23

This 'dry-run' feature will not work for pack strings with 'a0' or 'A0' elements because in this case the total packed length will be dependent on the length of the actual strings. In this case util.pack() will raise an error.

If you have to deal with devilishly complicated structures, the following function can be used to convert complex pack strings with parenthesised expressions into simpler ones that are acceptable by util.pack():

function expandPackString(s)
  repeat
    local n
    s,n=string.reGSub(s,`\(((?:(?>[^()]+)|(?R))*)\)(\d*)`,
                      function(inp,n) return string.rep(inp,n) end)
  until n==0
  return s
end

This converts 'a4A2 ( i(II)3c )4 si' into 'a4A2 iIIIIIIc iIIIIIIc iIIIIIIc iIIIIIIc si'.

util.parseArg(args,opts[,sw[,csens]])
top of page

Parses command line arguments in array args. opts is an array which describes the valid options, with one entry per option. sw is a string with the actual switch character(s). This can be a simple value like '-' (the default) or '--' or even '/' or it can be a full-blown regular expression. csens is a boolean, true (the default) means that switch characters or names are case-sensitive.

An entry in opts is simply a string with up to three fields, separated by '|'. The first field is the type of the option, this can be 'b' for a boolean switch (i.e. no further parameters) or 's' for a string switch with a single parameter (numbers on the command line are dealt with as strings) or 'x' for a callback switch (the function that will be called for all callback switches has to be given in field opts.parseArgCB; it receives three parameters: the switch character(s), the current value of the switch and the initialiser, if given).

The second field in an opts entry is the name of the option: this is what the user has to type on the command line as well as the field name in opts that you use to query the option value after calling the function. The third field is an optional initialiser which can be true or false for boolean switches or any valid string value for string switches. If this field is missing, boolean switches will be initialised with false and string switches with the empty string. Initialisers that start with '>' are taken to contain Idle code.

If opts.stop exists, this should contain a string (eg '--') that, if encountered on the command line, will stop further processing of switches.

An opts array with six entries might look like this:

opts={
  -- watch out: the initialisers for -d and -t are code snippets
  -- that are run inside parseArg()
  -- boolean -nodbg: opts.nodbg is true if switch is not specified
  "b|nodbg|true",
  -- boolean -w: opts.w is false if switch is not specified
  "b|w|false",
  -- string -d: opts.d is os.ENV['PATH'] if switch is not specified
  "s|d|>os.ENV['PATH']",
  -- string -u: opts.u is 'St. Jacques' if switch is not specified
  "s|u|St. Jacques",
  -- string -t: opts.t is current time if switch is not specified
  "s|t|>os.time()",
  -- string -!: opts.! is 'strange character' if switch is not specified
  "s|!|strange character"
}

util.parseArg() first initialises all option fields in opts with their default values and then proceeds to evaluate the command line arguments. If a command line argument contains a valid switch, the relevant value is written into the its field in opts: in the case of a boolean switch the field is toggled; in the case of a string switch the string following the switch, either directly or in the next command line argument, is copied into the field (in other words, the function supports '-Xtest' as well as '-X test'). The function returns an updated copy of args with command line arguments for processed switches removed, leaving only non-switch arguments. args itself is left untouched.

If there is an error during processing, the function returns nil, followed by an error string and a number. The error string gives the reason for the error; this can be 'arguments' (error in array args), 'options' (error in array opts) or 'unprocessed' (an unprocessed switch was found in array args). At any rate, the number indicates the index in the args or opts array that is responsible for the error.

util.printf(fmt,...)
top of page

Formats a string according to the format specification in string fmt (for details of the supported formats see string.format()) and writes it to stdout.

util.sha1(message)
top of page

Computes and returns the 160-bit SHA1 hash of string message. The output is formatted as a binary string with 20 characters (to convert this into a printable string, see string.toHex()).

util.shiftAR(v,dist)
top of page

Shifts signed value v to the right by dist bits. This function works reliably with integer values of up to 52 bits.

util.shiftL(v,dist)
top of page

Shifts v to the left by dist bits. This function works reliably with integer values of up to 52 bits.

util.shiftR(v,dist)
top of page

Shifts unsigned value v to the right by dist bits. This function works reliably with integer values of up to 52 bits.

util.strxor(str1,str2)
top of page

Computes the bitwise exclusive or of (possibly binary) strings str1 and str2 and returns the result. Both input strings must have the same length, which will also be the length of the returned string.

util.unpack(str,packstr[,init])
top of page

Unpacks binary string str into separate values and returns them. packstr is a format string that describes the format of str (for details see util.pack() and below). init is the start position in str (default is 1). This function returns the unpacked items according to the format string, followed by the next position in str. This allows consecutive calls to unpack a complex string. Example:

print(util.unpack('test\0\0','a4')) -- returns 'test' and 5

If this function is used to unpack strings (codes 'a' and 'A') there are two special cases to consider. Code 'a', followed by a 0, indicates a zero-terminated string. Code 'A', followed by a 0, means that the length of the string to unpack is found in the number unpacked just before the string itself. Example:

s='packing\0stuff'
s=util.pack('sa0',#s,s)
n,s1=util.unpack(s,'sa0')  -- returns 13 and 'packing'
n,s1=util.unpack(s,'sA0')  -- returns 13 and 'packing\0stuff'

Module win32
top of page

This module implements functions related to the Win32 API, such as access to the clipboard or to the registry. All functions are called through table win32.

win32.allocConsole()
top of page

Creates and attaches the calling process to a console window if the process is not yet connected with a console (an Idle script started as a GUI application or after having called win32.freeConsole() is not connected to a console).

win32.attachConsole(pid)
top of page

Attaches the calling process to the console window of another process whose process id is given in pid. If pid is -1 the caller will be attached to the console window of its parent process. This function does not support Windows 2000; it requires at least Windows XP.

win32.attachStdio(pid)
top of page

Connects the Idle standard file handles (see module io) with a newly allocated or attached console window (see win32.allocConsole() or win32.attachConsole()).

win32.clearConsole()
top of page

Clears the console screen buffer and positions the cursor at the top-left corner if the current script is running in a console window.

win32.convertToOem(s[,toANSI])
top of page

This function translates string s from the current codepage into the OEM codepage (if toANSI is missing or false) or vice versa (if toANSI is true) and returns the converted string. This function is useful if you want to print filenames received from the operating system in a console window whose codepage is 850 or 437. If the console codepage is the same as the system codepage (for example 1252) then such a conversion is not needed.

win32.createFileChange(path,flags[,recurse])
top of page

Creates and returns a file change notification object which can later be used to monitor certain changes in the directory or subtree given by path (see win32.waitFileChange()). If the boolean recurse is missing or false, then only path itself is monitored; true monitors path and its subtree. flags specifies the changes to be monitored; this is one or a combination of the following characters:

If more than one class of change is to be monitored, then even a single change can produce multiple notifications.

win32.enumWindows()
top of page

Returns a table with information about all top-level windows. The numerical window handles are the keys and a subtable (with fields 'text' for the window text and 'class' for the class name) are the values. Example:

local t=win32.enumWindows()
for hwnd,winfo in pairs(t) do
  if winfo.text=='Calculator' then
    win32.setForegroundWindow(hwnd)
  end
end

win32.findWindow(cls,name[,parent[,child]])
top of page

Returns the numerical window handle of the window with class name cls and window text name (name can be the empty string, then all windows are searched). parent is the handle to the parent window whose child windows are to be searched. If parent is 0 or missing, the function uses the desktop window as the parent window. child is the handle to a child window. The search begins with the next child window in the Z order. The child window must be a direct child window of parent, not just a descendant window. If child is 0 or mmissing, the search begins with the first child window of parent. If both parent and child are 0 or missing, the function searches all top-level and message-only windows.

In case of an error or if no window can be found this functions returns nil and an error code.

win32.freeConsole()
top of page

Detaches the calling process from its console. The process continues to run but any output will not be directed towards a console. To connect a process with a console, see win32.allocConsole() or win32.attachConsole().

win32.getClipboard([fmt])
top of page

Returns a boolean with the clipboard state or the contents of the clipboard as a string (if the clipboard is empty, an empty string is returned). If fmt is '?', the function returns true if the clipboard is not empty, false otherwise. If fmt is 'a' or missing, the returned string is in the current locale. If fmt is 'o', the string returned is in the OEM character set.

win32.getConsoleCP()
top of page

Returns the current console output and input pages.

win32.getConsoleInfo()
top of page

This functions returns five values if the current script is running in a console window: the horizontal and vertical sizes of the console screen buffer, the horizontal and vertical value of the cursor position and the current colour attribute for text and background:

sizeX,sizeY,cursorX,cursorY,attr=win32.getConsoleInfo()

win32.getForegroundWindow()
top of page

This function returns the numerical window handle of the window that is currently in the foreground.

win32.gotoXY(x,y)
top of page

This function attempts to set the console cursor position to x and y if the current script is running in a console window. All coordinates are zero-based with 0, 0 being the top-left corner.

win32.peekChar()
top of page

Returns information about the first character or keypress waiting in the input queue (ASCII code of the key, its virtual key code and the state of the control keys; see win32.readChar() for details) or nil if the input queue is empty.

win32.printf(fmt,...)
top of page

Formats a string according to the format specification in string fmt (for details of the supported formats see string.format()) and writes it to the console window.

win32.readChar([raw])
top of page

Waits for a keypress and returns three numerical values: the ASCII code of the key pressed, its virtual key code and the state of the control keys. If raw is false or missing, only non-shift and non-ctrl keypresses are returned. If raw is true, pressing any of the Alt, Ctrl or Shift keys returns values as well. If a key has no ASCII code (such as the function or shift keys), the ASCII code returned is 0. The most important virtual key code values are accessible through table win32.VK (more details and additional codes can be found in the Microsoft SDK documentation) :

The state of the control keys is coded in a combination of up to nine bit flags which are accessible through table win32.KEYF:

To query these flags util.bitAnd() can be used:

ascii,vk,ctrl=win32.readChar()
if vk==win32.VK.F12 and util.bitAnd(ctrl,win32.KEYF.LALT)==win32.KEYF.LALT then
  -- F12 was pressed and the left Alt key was down
end

win32.readConsoleOutput()
top of page

This function returns two userdata values, the first containing the attributes of the console window, the second the characters.

win32.regDeleteKey(hkey,subkey)
top of page

Deletes a registry subkey. hkey has to be one of the top-level registry keys (see the string shortcuts below), subkey is a string with the name of the subkey in hkey to be deleted. The valid values for hkey are:

win32.regDeleteValue(hkey,subkey,vname)
top of page

Deletes a registry value. hkey has to be one of the top-level registry keys (see win32.regDeleteKey()), subkey is a string with the name of the subkey in hkey and vname is the name of the value to be deleted (if you want to delete the default value of subkey then use an empty string as vname).

win32.regEnumKeys(hkey,subkey)
top of page

Returns a table with all key names within subkey. hkey has to be one of the top-level registry keys (see win32.regDeleteKey()).

win32.regEnumValues(hkey,subkey)
top of page

Returns a table with all value names within subkey. hkey has to be one of the top-level registry keys (see win32.regDeleteKey()).

win32.regGetValue(hkey,subkey,vname)
top of page

Queries a registry value. hkey has to be one of the top-level registry keys (see win32.regDeleteKey()), subkey is a string with the name of the subkey in hkey and vname is the name of the value to be queried (if you want to query the default value of subkey then use an empty string as vname). The function returns the queried value as a string if the value pointed to by vname is of type REG_EXPAND_SZ, REG_BINARY, REG_MULTI_SZ or REG_SZ. It returns a number if the value pointed to by vname is of type REG_DWORD_BIG_ENDIAN or REG_DWORD. If hkey, subkey or vname are invalid or not existent, the function returns nil. Note that this function cannot be used to query performance-related pseudo keys under HKEY_PERFORMANCE_DATA.

win32.regSetValue(hkey,subkey,vname,value[,type])
top of page

Sets a registry value. hkey has to be one of the top-level registry keys (see win32.regDeleteKey()), subkey is a string with the name of the subkey in hkey and vname is the name of the value to be set (if you want to set the default value of subkey then use an empty string as vname). value is the new value for vname. If value is a number, the type of the new value is taken to be an unsigned integer (REG_DWORD); if value is a string, type is one of the following strings:

win32.scrollConsole([n])
top of page

This function scrolls the content of the console screen buffer by n lines (default is 1). If n is a positive value, the buffer is scrolled up; if n is negative the buffer is scrolled down.

win32.scrollConsoleBuffer(toX,toY,l,t[,r,b])
top of page

Copies all or part of the console screen buffer to a new position. toX and toY are the target coordinates of the rectangle to be copied. This rectangle is given by the four values l and t (for left/top corner) and r and b (for right/bottom corner). The latter two values are optional; if they are missing the height and width of the console screen buffer is assumed. Any values outside the current size of the console screen buffer are silently truncated. All coordinates are zero-based with 0, 0 being the top-left corner. Example:

win32.scrollConsoleBuffer(0,0,0,1)  -- scroll buffer up one line
win32.scrollConsoleBuffer(0,1,0,0) -- scroll buffer down one line

win32.sendKbdEvent(key[,flags[,count[,delay]]])
top of page

This function sends a keypress to the window currently in the foreground (see win32.setForegroundWindow()). key is the numerical value of the ASCII code or virtual key code to send (see win32.readChar() for a description of table win32.VK and the most important virtual key codes). flags is a string which determines which modifier keys (Alt, Ctrl, Shift, Win) are pressed and released with the key code:

The optional parameters count and delay determine how often the keypress is sent (default is 1) and whether there is a delay between individual keypresses (default is 0 which means no delay; value is in milliseconds).

Here are a few examples:

win32.sendKbdEvent(67,'')   -- sends a 'C'
win32.sendKbdEvent(99,'')   -- sends an 'c'
win32.sendKbdEvent(99,'^')  -- sends ^c
win32.sendKbdEvent(win32.VK.F1,'v')    -- sends F1
win32.sendKbdEvent(win32.VK.F1,'!^v')  -- sends Alt-Ctrl+F1

Note 1: Sending large amounts of text may cause the internal buffers used by the system to overflow. In this case it may be advisable to copy the text to the clipboard and to send a Ctrl-V keypress instead:

win32.setClipboard(someVeryLongString)    -- copy text to clipboard
win32.sendKbdEvent(string.byte('v'),'^')  -- send ^v

Note 2: This function is extremely powerful and extremely dangerous. Make sure that you know exactly which window is in the foregound before sending any keystrokes and use judicious delays (for example, to make sure that a dialog box just activated is indeed initialised and actually has the focus).

Note 3: Triple-check everything you send.

win32.sendString(str[,delay])
top of page

Sends a string of keystrokes to the window currently in the foreground (see win32.setForegroundWindow()). str is a string with the characters to send; delay is the delay between individual keypresses (default is 0 which means no delay; value is in milliseconds).

The string to send is composed of individual characters; every character may be preceded by one or more of the following modifier keys:

A value like '!+c'means Alt-Shift C. The four characters for the modifier keys ('!^+#') and all virtual keys (the cursor keys, the function keys et cetera) have to be enclosed in curly braces (normal characters can also be used in curly braces). A key given in curly braces can be followed by an optional numerical count: a value like '{a 5} means send five a's; '{+}{!}' sends a plus and an exclamation sign. Virtual keys are given by the following keywords (case is irrelevant):

An additional code ({PAUSE n}) can be used to pause for n milliseconds while sending characters.

Here are a few examples:

win32.sendString('test')         -- just sends 'test'
win32.sendString('test{enter}')  -- sends 'test' and the Return key
win32.sendString('^c+{esc}')     -- Ctrl-C, followed by Shift-Escape
win32.sendString('test{left 4}') -- 'test' and four times Left
win32.sendString('{F1}{pause 100}{! 2}{a 3}') -- F1 key, a pause of
                                              -- 100 msec and '!!aaa'

See win32.sendKbdEvent() for some important remarks.

win32.setClipboard(s[,fmt])
top of page

Sets the contents of the clipboard to string s. IF s is the empty string, the clipboard is cleared. If fmt is 'a' or missing, s is supposed to be coded in the current locale. If fmt is 'o', s is coded in the OEM character set.

win32.setConsoleAttribute(attr)
top of page

Sets the colour attribute for console foreground (text) and background. attr is a numerical value which can be constructed from two tables with bit values for foreground (win32.TEXT) and background (win32.BACK) colours:

As an example, the following sets the foreground colour to red and the background to green and blue:

attr=util.bitOr(win32.TEXT.RED,win32.BACK.GREEN,win32.BACK.BLUE)
win32.setConsoleAttribute(attr)

win32.setConsoleCP(outCP,inCP)
top of page

Sets the current console output page and input page. If this function succeeds, it returns true, else it returns nil, plus a string describing the error.

win32.setForegroundWindow(hwnd)
top of page

Sets the foreground window to the top-level window whose window handle is given in hwnd.

win32.shell(file[,op[,params[,dir]]])
top of page

Starts file (which can be an executable file or any file for which an application has been registered). op is the operation to perform. This can be any verb that has been registered for the type of the file specified (common verbs are 'open', 'print', 'play' and 'explore'); the default is 'open'. The string params gives the parameters, if any. dir is the working directory. The function returns true or, in the case of an error, nil and an error message.

win32.shellCopy(fromdorf,todorf[,rec])
top of page

Copies file or directory fromdorf to todorf, using Win32 shell function SHFileOperation. The underlying function supports wildcards in parameter fromdorf, but not in todorf. If you use wildcards and the boolean rec is true, then the function may recurse into subdirectories, depending on the actual wildcard pattern used, and copy files and directories recursively.

win32.shellDelete(dorf,[,rec])
top of page

Deletes file or directory dorf, using Win32 shell function SHFileOperation. The underlying function supports wildcards in parameter dorf. If you use wildcards and the boolean rec is true, then the function may recurse into subdirectories (depending on the actual wildcard pattern used) and delete files and directories recursively. This means that win32.shellDelete(...,true) can delete a complete directory tree faster than you can say 'Shit!', so make absolutely sure you know what you are doing (or have a backup handy).

win32.shellMove(fromdorf,todorf,[,rec])
top of page

Move file or directory fromdorf to todorf, using Win32 shell function SHFileOperation. The underlying function supports wildcards in parameter fromdorf, but not in todorf. If you use wildcards and the boolean rec is true, then the function may recurse into subdirectories, depending on the actual wildcard pattern used, and move files and directories recursively.

win32.shellRename(fromdorf,todorf)
top of page

Renames file or directory fromdorf to todorf, using Win32 shell function SHFileOperation. The underlying function supports neither wildcards nor recursion.

win32.showWindow(hwnd,flag)
top of page

Shows or hides window with handle hwnd. The following flag values are defined:

win32.waitFileChange(fc[,timeout]) or fc:wait([timeout])
top of page

After creating a file change notification object (see win32.createFileChange()), this function is used to wait for actual changes in the monitored directory (or subtree). fc is the file change notification object to wait for. If timeout is not given, the function waits indefinitely; else this is the timeout value in milliseconds. The function returns true if a change took place and false if the timeout is reached.

win32.waitForObject(handle[,timeout])
top of page

Waits for the object whose numerical handle is given in handle. If timeout is not given, the function waits indefinitely; else this is the timeout value in milliseconds. The function returns true if the object is available (or has changed state) and false if the timeout is reached. In case of an error, the function returns nil and an error code.

win32.writeConsole(s)
top of page

Writes string s to the console window.

win32.writeConsoleOutput(attr,chars)
top of page

This function writes back to the console window the attribute and character userdata values previously read by a call to win32.readConsoleOutput().

win32.writeConsoleRaw(s,x,y)
top of page

Writes string s to the console window at position x and y, without interpreting escape sequences like \n etc.

Module zio
top of page

The zio module replicates many of the functions for file I/O found in module io. However, all read operations are performed through a virtual file system that can include zip and 7z archives as well as normal directories. Read accesses to 'files' and 'directories' in a mounted archive happen in a fully transparent manner. Write accesses are limited to files which reside in a specified write directory (or a subdirectory of this directory). This allows Idle script code to be restricted to working within a sandbox.

The zio virtual file system initially consists only of a root and is otherwise empty. To add archives or normal directories you have to call zio.mount(), to remove a mounted archive or a directory you call zio.unmount(). All mounted archives and directories form a search path which is searched if a file is opened for reading. No such search is performed if a file is opened for writing as all write accesses have to be performed through the designated write directory anyway.

Like io.open(), the function zio.open() returns a file descriptor; all further file operations can be performed by methods of this file descriptor. Unless otherwise stated, all 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.

zio.close(file) or file:close()
top of page

Closes file. This call can fail if the library was buffering writes to the physical media, and, now forced to write those changes to physical media, cannot store the data for some reason. In such a case, the filehandle stays open.

zio.eof(file) or file:eof()
top of page

Returns true if the end of file on file has been reached.

zio.exists(name)
top of page

Returns true if file name exists in the search path and false otherwise.

zio.flush(file) or file:flush()
top of page

Saves any written data to file.

zio.getMountInfo(name)
top of page

Returns a string with the mount point for archive or directory name. This is either the root of the virtual file system or the directory given during mounting the archive or directory.

zio.getSearchPath()
top of page

Returns a table with the current search path. The search path includes the mounted archives and directories.

zio.isDir(name)
top of page

Returns true if name is a (sub-)directory inside the virtual file system and false otherwise.

zio.length(file) or file:length()
top of page

Returns the length of file in bytes.

zio.mount(zipordir[,mountpoint])
top of page

Mounts compressed file or directory zipordir under the location mountpoint in the virtual file system. If mountpoint is nil or missing, the root of the virtual file system is used. This function supports zip and 7z archives and maps all paths and files in an archive into the virtual file system.

The mounted directories will be searched by require() if that function cannot find the required Idle module in the path defined by IDLE_PATH (see require()).

zio.open(name[,mode])
top of page

Open file name for reading (if mode is 'r' or missing) or writing (if mode is 'w') and returns a file descriptor. A file to be opened for reading will be searched for along the search path (see zio.getSearchPath()); a file to be written has to be located in the write directory (see zio.setWriteDir()).

All files are opened in binary mode. This means that reading a block of data with a certain length returns the block exactly as it is on disk.

zio.read(file[format[,format...]]) or file:read([format[,format...]])
top of page

Reads the file file, according to the given formats, which specify what to read. For each format, the function returns a string with the characters read, or nil if it cannot read data with the specified format. When called without formats, it uses a default format that reads the entire next line (see below).

The available formats are

zio.readDir(name)
top of page

Copies all entries in directory name in the virtual file system into a table and returns this table.

zio.searchPath(name)
top of page

Returns the location in the virtual file system where file name resides.

zio.seek(file[,whence][,offset]) or file:seek([whence][,offset])
top of page

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:

In case of success, the function returns the final file position, measured in bytes from the beginning of the file. If this function fails, it returns nil, plus a string describing the error.

The default value for whence is 'cur', and for offset it is 0. Therefore, the call file:seek() returns the current file position, without changing it; the call file:seek('set') sets the position to the beginning of the file (and returns 0); and the call file:seek('end') sets the position to the end of the file, and returns its size.

zio.setWriteDir(name)
top of page

Sets the write directory to directory name (which must be a physical directory). All files opened for writing are opened in (or below) this directory. A directory set by this call is not automatically included in the search path (see zio.mount()).

zio.unmount(zipordir)
top of page

Unmounts compressed file or directory zipordir.

zio.write(file,...) or file:write(...)
top of page

Writes the value of each of its arguments to the file. The arguments must be strings or numbers. To write other values, use tostring() or string.format() before calling this function.



$$ built from IdleRuntime.txt d106963c4f77 Mon Sep 27 13:27:10 2010 +0000 thomasl $$