Howto:Test if a file exists in Nasal

From FlightGear wiki
Jump to: navigation, search

Objective

Demonstrate how we can check if a file exists to show a corresponding Canvas GUI dialog, e.g. by parsing the file.

Specifically, this will cover Nasal's call API, which will be used to invoke a function in a safe way using exception handling.

The following code snippets are self-contained, i.e. can be easily tested using the Nasal Console but also added to your Aircraft-set.xml file.

Example

Let's assume, we would like to check if a certain file exists:

var fileFound = func(filename) {
return call(io.readfile, [filename], nil, nil, var err=[]);
} # fileFound

var path=getprop("/sim/fg-root") ~ "/Nasal/props.nas";
var found = fileFound(path)!=nil?"yes":"no";
print("File check:", found );

Next, let's assume, we would like to check if a file named .git/config exists:

var fileFound = func(filename) {
return call(io.readfile, [filename], nil, nil, var err=[]);
} # fileFound

var haveGitConfig = func(path) {
return fileFound(path~"/.git/config");
} #haveGitConfig

var path=getprop("/sim/aircraft-dir");
var found = haveGitConfig(path)!=nil?"yes":"no";

print(".git/config in $FG_AIRCRAFT:", found);

Now, let's assume, we would like to run this check for all three folders, in any of the $FG_AIRCRAFT, $FG_ROOT and $FG_SCENERY folders:

var fileFound = func(filename) {
return call(io.readfile, [filename], nil, nil, var err=[]);
} # fileFound

var haveGitConfig = func(path) {
return fileFound(path~"/.git/config");
} #haveGitConfig

foreach(var p; ['/sim/aircraft-dir','/sim/fg-root', '/sim/fg-scenery' ]) {
var path=getprop(p);
var found = haveGitConfig(path)!=nil?"yes":"no";
print(".git/config in", path, " :", found);
}