Variable

Discussion in 'Plugin Development' started by Dekuhhh, Oct 22, 2020.

  1. Offline

    Dekuhhh

    How can I make sure that, through a specific command, an argument is saved in a variable, to be used also for other commands. Numbers are added to this variable, and when executing a new command it must return the previous variable as a message.If anyone can explain it to me and give me some examples, please!
     
  2. Offline

    spuddy

    Hoping this is the kind of thing you meant.

    Code:
        int total = 0;
        String lastValue = "no last value";
     
        private Integer stringToInt(String s) {
            try {
                return Integer.parseInt(s);
            }
            catch(NumberFormatException e) {
                return null;
            }
        }
         
        public boolean onCommand(CommandSender sender, Command cmd, String alias, String[] args) {
            if(cmd.getName().equalsIgnoreCase("addvalue")) {
                if(args.length == 1) {
                    Integer a = stringToInt(args[0]);
                    if(a != null) {
                        total += a;
                        sender.sendMessage("Total is now: " + total);
                        sender.sendMessage("Last value was: " + lastValue);
                        lastValue = a.toString();
                        return true;
                    }
                }
                return false;
            }
            // ...
            // ...
            // ...
            return false;
        }
    
    This is pretty fundamental stuff so I'm assuming you're new to coding? If you're trying to learn via immersion then that's fine (it's how I learned), we all have to learn the basics somehow. Only reason I say this is because on forums like this, you'll encounter people who may get triggered, just be prepared.
     
    Last edited: Oct 22, 2020
  3. Offline

    Strahan

    Well, it'd have helped if you were a little more explicit in what you are trying to accomplish. But basically, you just need to use a variable with a scope that will persist past the command execution. I'm going to assume this value is specific to the player, so you could create a Map and store it in there, indexed on the player's UUID and put it somewhere all classes can access it. Like the main class, then use dependency injection to pass an instance of the main class around as needed.

    Give more details and we can give a more detailed recommendation.
     
  4. Offline

    Dekuhhh

    I mean to assign a variable to a player or topic. it can also be read by other methods and classes

    Uhm, I don't mean that, I mean a hasmap variable

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Oct 23, 2020
  5. Offline

    CraftCreeper6

    @Dekuhhh
    Make a hashmap with UUID as the key and int as the value, then just add the player to the hashmap the first time they use the command. Then from there, just get the stored value from the hashmap using the players UUID.
     
  6. Offline

    spuddy

    Okay, it wasn't clear exactly what you meant from your original post. Using a HashMap<UUID, String> would be better than using Integer. It future proofs it a little, allows you to add custom values such as "Disabled", "Infinity" and stuff like that, and only adds a small amount of extra code to parse the string. If you want it readable by other classes, I would suggest not storing the Map Object in the main class, back referencing classes is not a good idea. Instead maybe store it as a static in a separate class, you may also use the same class for other stuff and it gives all your code a common FORWARD reference and location for globals. Although using statics for information sharing is also frowned upon, as is accessing fields directly instead of using get() set() methods. If you want the values to be persistent, maybe look into creating player specific config files.

    Note: this is untested, just knocked it up as an excercise, a class that can deal with any type of data you want to store with respect to players.

    Code:
    import java.util.HashMap;
    import java.util.Map;
    
    import org.bukkit.entity.Player;
    
    public class PlayerValue {
        private static Map<String, PlayerValue> allValues;
        private Map<String, Object> values;
       
        static {
            allValues = new HashMap<String, PlayerValue>();
        }
       
        private PlayerValue() {
            values = new HashMap<String, Object>();
        }
       
        private static PlayerValue getPlayerValue(Player player) {
            PlayerValue pv = allValues.get(player.getUniqueId().toString());
            if(pv == null) {
                pv = new PlayerValue();
                allValues.put(player.getUniqueId().toString(), pv);
            }
            return pv;
        }
       
        @SuppressWarnings("unchecked")
        public static <T> T get(Player player, String key, Object def) {
            try {
                return (T)getPlayerValue(player).get(key, def);
            }
            catch(ClassCastException e) {
                e.printStackTrace();
                return null;
            }
        }
       
        private Object get(String key, Object def) {
            Object val = values.get(key);
            if(val == null) {
                val = def;
            }
            return val;
        }
       
        public static void put(Player player, String key, Object val) {
            getPlayerValue(player).put(key, val);
        }
       
        private void put(String key, Object val) {
            values.put(key, val);
        }
       
        public static int[] addTo(Player player, String key, int inc) {
            int last = get(player, key, 0);
            int current = last + inc;
            put(player, key, current);
            return new int[] { current, last };
        }
    }
     
    Last edited: Oct 23, 2020
  7. Offline

    Dekuhhh

    How do I get the variable back?
     
  8. Offline

    spuddy

    PlayerValue.put(player, "counter", 4); will store the value 4 under the name "counter"
    int i = PlayerValue.get(player, "counter", 0); will retrieve the value or 0 if the value doesn't exist yet.
    int[] a = PlayerValue.addTo(player, "counter", 1); will add 1 to the stored value and the returned array a[0] will be the current value, a[1] will be the old value
     
  9. Offline

    Strahan

    That's an... interesting approach heh.
     

Share This Page