slang-users mailing list

[2020 Date Index] [2020 Thread Index] [Other years]
[Thread Prev] [Thread Next]      [Date Prev] [Date Next]

Re: [slang-users] is_defined


Morten Bo Johansen <mbj@xxxxxxxxxxx> wrote:
> Hi
>
> If I do
>
>   if (is_defined ("foo"))
>     foo ();
>
> and "foo" is not defined, then this notwithstanding, an error
> is thrown: "foo is undefined".
>
> This shouldn't happen, IMO, since the condition was not met,
> and then the statement should be silently ignored and no error
> thrown.
>
> But maybe there is a reason for this?

The statement first gets compiled to byte-code, and is then executed.
The error comes during the compilation stage.

You can achieve what you are trying to do a few different ways.  If
"foo" has a global scope such that is is visible to the preprocessor,
then you can use:

 #ifexists foo
 foo();
 #endif

However, I recommend using the __get_reference function:

 funct = __get_reference ("foo");
 if (funct != NULL) (@funct)();

The __get_reference function returns a reference to an object that is
globally accessible.  A globally accessible object is one that is
public to any scope, or is globally accessible via a namespace.  To
better understand this, consider the following slsh script:

 implements ("foo");
 public define global_bar (str)
 {
    vmessage ("%s is defined", str);
 }

 static define static_bar (str)
 {
    vmessage ("%s is defined", str);
 }

 private define private_bar (str)
 {
    vmessage ("%s is defined", str);
 }

 public define slsh_main ()
 {
    variable fstr, f;
    variable funcs = ["global_bar", "static_bar", "private_bar"];
    foreach fstr ([funcs, "foo->"+funcs])
      {
        f = __get_reference (fstr);
        if (f != NULL) (@f)(fstr);
      }
 }

Executing this produces the output:

 global_bar is defined
 foo->static_bar is defined

It does not find references to "static_bar" and "private_bar" because,
as written, they are not globally accessible even though they are in
scope.  However, "foo->static_bar" is globally accessible.

I hope this helps.
Thanks,
--John
_______________________________________________
For list information, visit <http://jedsoft.org/slang/mailinglists.html>.


[2020 date index] [2020 thread index]
[Thread Prev] [Thread Next]      [Date Prev] [Date Next]