Nasal library/io: Difference between revisions

From FlightGear wiki
Jump to navigation Jump to search
(→‎open(): Add examples)
Line 150: Line 150:
|param2 = mode
|param2 = mode
|param2text = Optional mode parameter. See the table below. Defaults to "rb".
|param2text = Optional mode parameter. See the table below. Defaults to "rb".
|example1 =  
|example1text = Note that the below example must be run first for the others to work.
|example1 = var path = getprop("/sim/fg-home") ~ '/Export/demo.txt';
var file = io.open(path, "w"); # open in write mode
var text = 'Hello, World!' ~ "\r";
io.write(file, text);
io.close(file);
|example2 = var path = getprop("/sim/fg-home") ~ '/Export/demo.txt';
var file = io.open(path, "r"); # open in read mode
print(io.readln(file)); # prints "Hello, World!"
io.close(file);
|example3 = var path = getprop("/sim/fg-home") ~ '/Export/demo.txt';
var file = io.open(path, "a"); # open in append mode
var text = "\n" ~ 'This is line 2';
io.write(file, text);
io.close(file);
}}
}}



Revision as of 18:24, 23 October 2016

WIP.png Work in progress
This article or section will be worked on in the upcoming hours or days.
See history for the latest developments.

This page contains documentation for the io namespace in Nasal. This namespace provides APIs for input/output (IO) operations on files. The io namespace is sourced from fgdata/Nasal/io.nas and simgear/simgear/nasal/iolib.c.

Functions

basename()

io.basename(path);

Version added: FG 3.0 (commit)

Returns last element of a path as a string.

path
Path as a string.

Examples

var path = '/demo/demo.xml';
print(io.basename(path)); # prints "demo.xml"
var path = 'C:\FlightGear\FlightGear 3.2.0\data';
print(io.basename(path)); # prints "data"

close()

io.close(file);

Flushes and closes the specified file. Returns nil.

file
File object as returned by open() .

Example

var path = getprop("/sim/fg-root") ~ '/keyboard.xml';
var file = io.open(path);
print(io.readln(file)); # prints the XML header
io.close(file);

dirname()

io.dirname(path);

Version added: FG 3.0 (commit)

Returns the directory of a path as a string.

path
Path as a string.

Examples

var path = '/demo/demo.xml';
print(io.dirname(path)); # prints "/demo/"
var path = 'C:\FlightGear\FlightGear 3.2.0\data';
print(io.dirname(path)); # prints "C:/FlightGear/FlightGear 3.2.0/"

flush()

io.flush(file);

Flushes the file's buffer. This means that the contents of the buffer (a kind of temporary storage) are written to the actual file on the hard disk. Note that the buffer is also flushed when close() is called.

file
File object as returned by open() .

Example

var path = getprop("/sim/fg-home") ~ '/Export/demo.txt';
var file = io.open(path, "w"); # create and open file
io.write(file, "Hello, World!"); # write (to the buffer)

var file2 = io.open(path); # open the file separatly
var b = bits.buf(13); # create a buffer
io.read(file2, b, 13); # read file
print(b); # prints nothing

io.flush(file); # flush buffer to file
io.read(file2, b, 13); # read file again
print(b); # prints "Hello, World!"

io.close(file); # close
io.close(file2);

include()

io.include(file);

Version added: FG 3.0 (commit)

Loads a given Nasal file into where the function is called from.

file
Path to file as a string. If it is just a filename, it will be assumed that the file is in the same folder as calling script. Otherwise, it will be searched for in the standard FlightGear directories (see Resolving Paths).

Example

io.include("Nasal/geo.nas"); # include the geo namespace
var coord = Coord.new(); # create a new Coord object
coord.set_latlon(0, 0, 2000); # set coordinates
print(coord.alt()); # prints "2000"

load_nasal()

io.load_nasal(file[, module]);

Loads and executes a given Nasal script into a namespace.

file
Full path to the Nasal file as a string.
module
Optional name of module to load the script into as a string. If not given, the namespace will be the name of the file.

Examples
For the examples, first put the below code in to a new file, $FG_HOME/Export/demo.nas:

var sayHello = func(){
    print("Hello, World!");
}
var file = getprop("/sim/fg-home") ~ '/Export/demo.nas';
io.load_nasal(file); # load into "demo" namespace
demo.sayHello(); # "Hello, World!" will be printed
var file = getprop("/sim/fg-home") ~ '/Export/demo.nas';
io.load_nasal(file, "myDemo"); # load into "myDemo" namespace
myDemo.sayHello(); # "Hello, World!" will be printed

open()

io.open(path[, mode]);

Opens the file with the specified mode and returns an iofile ghost object representing the file.

Mode Meaning
r Opens a file for input (reading) operations. The file must exist.
w Creates a new file for output (writing) operations. If the file already exists, its contents will be cleared first.
a Opens a file for appending data. The file is created if it does not exist.
r+ Open for input and output operations. The file must exist.
w+ Creates a new file for input and output operations. If the file already exists, its contents will be cleared first.
a+ Opens a file for input and output operations. Output operations will append data to the end of the file. Input operations are affected by seek() , but output operations will move the position back to the end of the file. The file is created if it does not exist.
rb Opens a file for input operations, treating it as a binary file. The file must exist. Default mode.
wb Creates a new file for output operations, treating it as a binary file. If the file already exists, its contents will be cleared first.
ab Opens a file for appending data, treating it as a binary file. The file is created if it does not exist.
r+b or rb+ Open for input and output operations, treating it as a binary file. The file must exist.
w+b or wb+ Creates a new file for input and output operations, treating it as a binary file. If the file already exists, its contents will be cleared first.
a+b or ab+ Opens a file for input and output operations, treating it as a binary file. Output operations will append data to the end of the file. Input operations are affected by seek() , but output operations will move the position back to the end of the file. The file is created if it does not exist.
path
Full path to the file as a string.
mode
Optional mode parameter. See the table below. Defaults to "rb".

Examples

Note that the below example must be run first for the others to work.

var path = getprop("/sim/fg-home") ~ '/Export/demo.txt';
var file = io.open(path, "w"); # open in write mode
var text = 'Hello, World!' ~ "\r";
io.write(file, text);
io.close(file);
var path = getprop("/sim/fg-home") ~ '/Export/demo.txt';
var file = io.open(path, "r"); # open in read mode
print(io.readln(file)); # prints "Hello, World!"
io.close(file);
var path = getprop("/sim/fg-home") ~ '/Export/demo.txt';
var file = io.open(path, "a"); # open in append mode
var text = "\n" ~ 'This is line 2';
io.write(file, text);
io.close(file);

read(filehandle, buf, len)

Attempts to read length bytes from the filehandle into the beginning of the mutable string buf. Failures (including overruns when length > size(buf)) are thrown as runtime errors as per die(). Returns the number of bytes successfully read.

read_airport_properties()

Load XML file in FlightGear's native <PropertyList> format. File will be located in the airport-scenery directories according to ICAO and filename, i,e in Airports/I/C/A/ICAO.filename.xml

If the second, optional target parameter is set, then the properties are loaded to this node in the global property tree. Otherwise they are returned as a separate props.Node tree. Returns the data as a props.Node on success or nil on error.

Usage:   io.read_properties(<filename> [, <props.Node or property-path>]);

Example:

var data = io.read_airport_properties("KSFO", "rwyuse");

read_properties()

Load XML file in FlightGear's native <PropertyList> format. If the second, optional target parameter is set, then the properties are loaded to this node in the global property tree. Otherwise they are returned as a separate props.Node tree. Returns the data as a props.Node on success or nil on error.

Usage:   io.read_properties(<filename> [, <props.Node or property-path>]);

Examples:

var target = props.globals.getNode("/sim/model");           
io.read_properties("/tmp/foo.xml", target);                 
                                                            
var data = io.read_properties("/tmp/foo.xml", "/sim/model");
var data = io.read_properties("/tmp/foo.xml");

readfile()

Reads and returns a complete file as a string. Failures are thrown as runtime errors as per die().

io.readfile(file);

readln(filehandle)

Reads and returns a single text line from the filehandle. Interprets both "\n" and "\r\n" as end of line markers, and does not include the "\r" or "\n" bytes in the returned string. End of file or error is signaled by returning nil.

readxml()

Reads an XML file from an absolute path and returns it as property tree. All nodes will be of type STRING. Data are only written to leafs. Attributes are written as regular nodes with the optional prefix prepended to the name. If the prefix is nil, then attributes are ignored. Returns nil on error.

Usage:  io.readxml(path[, prefix = "___"]);
io.readxml(path,prefix);

seek(filehandle, position, whence)

As ANSI fseek(). Attempts to seek to the specified position based on the whence value (which must be one of io.SEEK_SET, io.SEEK_END, or io.SEEK_CUR).

stat(filename)

Calls unix or win32 stat() on the specified file name and returns a seven element array whose contents are, in order: dev, ino, mode, nlink, uid, gid, rdef, size, atime, mtime, ctime. Errors are signaled as exceptions as per die().

tell(filehandle)

Returns the current seek position of the filehandle.

write(filehandle, str)

Attempts to write the entirety of the specified string to the filehandle. Failures are thrown as runtime errors as per die(). Returns the number of bytes successfully written.

write_properties()

Write XML file in FlightGear's native <PropertyList> format. Returns the filename on success or nil on error. If the source is a props.Node that refers to a node in the main tree, then the data are directly written from the tree, yielding a more accurate result. Otherwise the data need to be copied first, which may slightly change node types (FLOAT becomes DOUBLE etc.)

Usage:   io.write_properties(<filename>, <props.Node or property-path>);

Examples:

var data = props.Node.new({ a:1, b:2, c:{ d:3, e:4 } }); 
io.write_properties("/tmp/foo.xml", data);               
io.write_properties("/tmp/foo.xml", "/sim/model");

writexml()

Writes a property tree as returned by readxml() to a file. Children with name starting with <prefix> are again turned into attributes of their parent. <node> must contain exactly one child, which will become the XML file's outermost element.

Usage:  io.writexml(path, node[,indent = "\t"][, prefix = "___"]);
io.writexml(path, node, indent,prefix);

Variables

SEEK_CUR

SEEK_END

SEEK_SET