5.2. Testing With Mappings

If you want to test whether a variable of type mapping is defined or undefined you can do the following:

Example 5-5. Testing a variable of type mapping to see if it is defined


  mapping m;

  if (!undefinedp(m)) {
    write("is defined\n");
  } else {
    write("is not defined\n");
  }

  if (m) {
    write("is defined\n");
  } else {
    write("is not defined\n");
  }

This prints "is not defined" twice.

If you want to test whether a variable of type mapping is empty or not empty, you should use the sizeof function like this:

Example 5-6. Testing a variable of type mapping to see if it is defined


  mapping m = ([ ]);

  if (sizeof(m) == 0) {
    write("empty\n");
  } else {
    write("non-empty\n");
  }

This will print "empty".

The following will NOT work for testing variables of type mapping:


  mapping m = ([ ]);

  if (m == ([ ]) {
    ...
  }

This will always be false. LPC cannot test whether one mapping is equal to another mapping regardless of the contents of each mapping. In order to do this correctly, you'd need a function.

The following will NOT work for testing variables of type mapping:


  mapping m = ([ ]);

  if (m) {
    ...
  }

This will always be true because m is defined and has a mapping as a value. Regardless of whether the mapping is empty or non-empty, this test will always be true.