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@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 0.3'; _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.

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(filename,[,mode])
top of page

Returns the contents of file filename as a (possibly binary) string. The file is opened in mode mode (see io.open() for details).

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

Reads the contents of file filename and return them as a table of separate lines (separating newline characters are removed; see also string.split()). 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, which is needed on Windows to open the file in binary mode. The mode string is exactly what is used in the standard C function fopen().

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(filename,sort[,mode])
top of page

Saves sort (a string or a table ) in file filename which is opened with mode mode.

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

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 (these are textual macros, after all). If Idle code has to be executed during compile time, the predefined macro __INLINE() can be used (see 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 (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; the 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'

__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 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.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 funtions 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(varname,value)
top of page

Sets process environment variable varname to value. Equivalent to writing 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 funtion 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 funtion 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.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 out[ut channel altogether.) 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})
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() and os.killProcess(). 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) pattern, 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 varibale 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.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="0.2"}
x=string.gsub("$name-$version.tar.gz", "%$(%w+)",t)
  --> x="idle-0.2.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.setlocal()).

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. 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:</