Changes

Jump to navigation Jump to search
1,596 bytes added ,  18:38, 22 September 2016
→‎Programs, Libraries, and Packages: add recipe to check if package is missing
Line 25: Line 25:  
     ## Image IO with support for png files
 
     ## Image IO with support for png files
 
     any (cellfun (@(x) ismember ("png", x), {imformats.ext}))
 
     any (cellfun (@(x) ismember ("png", x), {imformats.ext}))
 +
 +
=== Find if a package is installed ===
 +
 +
==== Problem ====
 +
 +
You have a program that uses different functions or behaves different
 +
depending on the availability of specific packages.
 +
 +
==== Solution ====
 +
 +
Use {{codeline|pkg ("describe", pkg-name)}} like so:
 +
 +
if (! isempty (pkg ("describe", "foo")))
 +
  ## use functions from package foo, the prefered way
 +
elseif (! isempty (pkg ("describe", "bar")))
 +
  ## use functions from package bar, not so optimal
 +
else
 +
  ## default case
 +
endif
 +
 +
==== Discussion ====
 +
 +
It's not recommended to use this if the only purpose is to then fail
 +
in the absence of the package.  In such case, simply try to load the package
 +
and Octave will already give a error message that is informative enough.
 +
 +
There is only purpose to check this, if there is something different to
 +
do if a package is missing.  The same is true for catching an error from
 +
{{codeline|pkg load}}.  If you only catch an error to then throw it again
 +
then you might as well not catch it in the first place.
 +
 +
## This contraption doesn't add anything.  If 'pkg load' fails, it
 +
## will already give an error message to the user.
 +
try
 +
  pkg load foo;
 +
catch
 +
  error ("failed to load foo: %s", lasterr ());
 +
end_try_catch
 +
 +
## Again, doesn't add anything.  The failure of 'pkg load' is enough
 +
if (isempty (pkg ("describe", "foo")))
 +
  error ("program: package foo is not installed");
 +
endif
 +
 +
Beware that an installed package is not always a guarantee that a function
 +
will be available.  Some packages may disable functions at build time, or
 +
specific functions may have specific runtime requirements.
    
== Structures ==
 
== Structures ==

Navigation menu