Most of the standard modules look outward.
io talks to files, os to the operating system, time to the clock.
The sys module looks at the interpreter itself. It tells a program how it was started, which version of Teascript is running it, and on what kind of machine, and it holds the few controls that change how the language itself behaves while a program runs. It can be considered, in a sense, the most important built-in module, even though it is also one of the smallest.
Like any standard module, it is brought in with an import:
import sysAn embedding application can decide what scripts see here, as everything else, since the values of the module are set up by the host and the interpreter. The tea program fills them in as described in this chapter.
Arguments
The attribute sys.argv is a list of strings with the arguments that were given to the program on the command line. Its first item is the name of the script, exactly as it was typed, and the following ones are the argument that came after it:
// args.tea
import sys
print(sys.argv.len)
for var arg in sys.argv
{
print(arg)
}$ tea args.tea one two
3
args.tea
one
two
Fundamentally, the options of the interpreter itself, like -e or -v, are not part of the list; they are consumed by tea before the scripts start, and the script only sees what is meant for it. When there is no script, as in the REPL, the list is empty.
All the items are strings, whatever they look like.
An argument that should be a number has to be converted with tonumber, and, as that function returns nil for text that is not a number, the result must be checked.
Exiting
The function sys.exit ends the program immediately, with a status that the caller can inspect, such as a shell script or another program.
Without an argument the status is success (0). A number gives the status explicitly, and a boolean is a convenient shorthand; true means success, false means failure.
sys.exit() // success
sys.exit(2) // status 2
sys.exit(false) // failure
By convention, a status of zero means that everything went well, and any other number reports a problem, with the meaning of each one left to the program. The range of valid numbers depends on the platform, so it is best to keep them small.
Calling sys.exit does not raise an error, so it cannot be intercepted by pcall, and nothing that follows it runs, wherever the call is made, even deep inside several functions. The interpreter is also closed in an orderly way before the program ends, which means that the objects that still exist are finalized, as normally expected.
The Interpreter
Three attributes describe the interpreter and the machine it is running on.
The attribute sys.version is a map with the version of Teascript, in the fields major, minor and patch, all of them numbers. It allows, for instance, a script to check what it depends on:
var v = sys.version
print("Teascript ${v["major"]}.${v["minor"]}.${v["patch"]}")
if v["major"] < 1
{
print("this script needs Teascript 1 or later")
sys.exit(false)
}The attribute sys.bits is the size of a pointer on the machine, as a number: 64 or 32. And sys.byteorder is a string, little or big, that tells the order in which the machine stores the bytes of a number, which matters to programs that read or write binary data with the io module.
Loaders
This attribute is a bit different from the others, since it is not meant to be read but used to change a behavior of the language. It is also the only one that most programs will never need, so this section only describes what is necessary to understand it.
As we saw in the Module System chapter, an import that is followed by a string looks for a file, relative to the file that contains the statement.
The attribute sys.loaders is a list of functions, the loaders, that are given the chance to handle such an import before the interpreter does. It starts empty, and so the normal search takes place. Adding a function to the list allows a program to load modules from places other than the file system; a table in memory, an archive, a database, a network even, or the contents of a game’s data file. Loaders are consulted for every relative path import; imports of standard modules by name (logical) are never affected.
A loader is just an ordinary function with two parameters.
The first is the path, as it is written in the import, and the second is the directory of the file that contains the import. Its job is to answer one question: is this module mine?
- If it is not, the loader returns
nil. The next loader is tried, and when all of them decline, the interpreter proceeds with its usual search. Items of the list that are not functions are ignored. - If it is, the loader returns a list of two items: a key, which is a string, and a load function.
The key identifies the module.
Once a module has been loaded, it is remembered under its key, so the same key always gives the same module, as with any other import. If the key is already known, the interpreter uses the existing module, and the load function is not even called.
Otherwise, it calls the load function with the key, and it must return the compiled module as a function, which is exactly what loadstring and loadfile do. The interpreter then runs it like the body of a file.
The following loader serves modules from a map of strings kept in memory, without touching the disk:
import sys
var sources = {
greeting = "export function hello(name) { return 'Hello, ' + name }"
}
sys.loaders.add((path, dir) => {
if not (path in sources) { return nil }
return [path, (key) => loadstring(sources[key], key)]
})
import "greeting" as g
print(g.hello("Tea")) // Hello, Tea
There is no file called greetings.tea anywhere (hopefully), and the import still works.
A path that the map does not contain is declined with nil, and handled by the normal rules, as before. If the loader itself raises an error, or returns anything that is not nil or a list of the described shape, the import fails with an error. Likewise, if the code of the module fails while it runs, the module is not kept, and the error continues to the importer.
A loader does not need to load anything to be useful.
Since it is called for every import, one that always returns nil is a way of observing them, which can be handy when finding out where the modules of a program come from:
sys.loaders.add((path, dir) => {
print("importing ${path} from ${dir}")
return nil
})Loaders affect the whole program, and not only the file that registered them, so they are best installed once, at the start of the program, before the imports that depend on them.
An Example
We finish with a small command line tool that uses the arguments and the exit status, as a script that is meant to be called from a terminal or from another program should. It repeats a word a number of times, and reports mistakes in the way that tools customarily do; a message on the standard error stream, and a status that is not zero.
// repeat.tea
import io, sys
function fail(message)
{
io.stderr.write("repeat: ", message, "\n")
io.stderr.write("usage: tea ", sys.argv[0], " word [count]\n")
sys.exit(2)
}
if sys.argv.len < 2
{
fail("a word is needed")
}
var word = sys.argv[1]
var count = 3
if sys.argv.len > 2
{
count = tonumber(sys.argv[2])
if count == nil or count < 1
{
fail("the count must be a positive number")
}
}
for var i in 0..count
{
print(word)
}$ tea repeat.tea tea 2
tea
tea
$ tea repeat.tea tea many
repeat: the count must be a positive number
usage: tea repeat.tea word [count]
$ echo $?
2
Everything the tool needs from the outside world comes from this module; the arguments, which are the whole of its input, and the exit status, which is the whole of its answer to the program that ran it.
The function fail also shows why sys.exit is the right tool; it stops the program on the spot, without the caller of fail having to arrange for anything to happen afterwards.