Aaron F.
Aaron F.

Reputation: 63

How to make an extension in NetLogo 5.x return a value of "nobody"?

I've created some methods that allow me to use extensions to take a turtle/breed variable as a string and return the value (number, boolean, string, object (e.g. list/table). However, I want it to fail safe and return "nobody" if the turtle/breed does not possess the variable name.

I can't get anything to turn Java's null into NetLogo's nobody however such that in the NetLogo environment nobody(1) from the netlogo world and nobody(2) as returned form the extension) are the same.. i.e.:

nobody(1) = nobody(2) is true

Some of the code:

import org.nlogo.api.*;
import org.nlogo.agent.Agent;
import org.nlogo.agent.AgentSet;
import org.nlogo.agent.Patch;
import org.nlogo.api.Nobody$;

public void load(PrimitiveManager primitiveManager) throws ExtensionException {
    primitiveManager.addPrimitive("get-variable-by-name", new GetVariableByName());
}

public static class GetVariableByName extends DefaultReporter{
    public String getAgentClassString() {
        return "OTPL";
    }

    public Syntax getSyntax() {
        return Syntax.reporterSyntax(
                new int[] { Syntax.AgentType(), Syntax.StringType() },
                Syntax.WildcardType());
    }

    public Object report(Argument[] args, Context arg1)
            throws ExtensionException, LogoException {

        Agent a = (Agent) args[0].get();
        String name = (String) args[1].get();

        Object value = null;

        for (int i = 0; i < a.getVariableCount(); i++ ){
            if (a.variableName(i).compareToIgnoreCase(name) == 0){
                value = a.getVariable(i);
                break;
            }
        }

        if (value instanceof Double){
            return (Double) value;
        }
        else if (value instanceof Boolean){
            return (Boolean) value;
        }
        else if (value instanceof String){
            return (String) value;
        }
        else if (value == null){
            return Nobody$.MODULE$;  // I've tried several things here, but none work.  This the last attempt.
        }
        else {
            return value;
        }
    }
}

Upvotes: 2

Views: 151

Answers (1)

Seth Tisue
Seth Tisue

Reputation: 30453

I believe that

return Nobody$.MODULE$;

is actually correct.

Why it wasn't working for you at first is hard to guess. After you rebuild your extension, it's necessary to either restart NetLogo or use the __reload-extensions command for your changes to take effect — maybe you weren't doing that?

Upvotes: 1

Related Questions