Solved Looping though config files...

Discussion in 'Spigot Plugin Development' started by Lightcaster5, May 29, 2020.

  1. So I know I need to use a foreach loop to solve this problem but I don't know the best approach to start. I have a configuration file and it is set up as follows:

    Code (Text):
    PlayerUUID1:
        Owner: PlayerName1
        X: 0
        Y: 60
        Z: 0
        World: world
    PlayerUUID2:
        Owner: PlayerName2
        X: 1
        Y: 60
        Z: 0
        World: world
    PlayerUUID3:
        Owner: PlayerName3
        X: 2
        Y: 60
        Z: 0
        World: world
    My question is how can I tell if a block is in any one of those positions like so:

    Code (Text):
    public boolean blockIsOwned(Location location) {
        for(Something something : Something) {
            Location savedLocation = new Location(something + ".X", something + ".Y", something + ".X", Bukkit.getWorld(something + ".World"));
            if (savedLocation == location) {
                return true;
            }
        }
        return false;
    }
    All help is appreciated, thanks!
     
  2. Loop through the configuration keys.

    Code (Java):
    for(String key : getConfig().getKeys(false)) {
       int x = getConfig().getInt(key + ".X"));
       int y = getConfig().getInt(key + ".Y"));
       int z = getConfig().getInt(key + ".Z"));
       String world = getConfig().getString(key + ".World");
       if(Bukkit.getWorld(world) != null)) {
          World w = Bukkit.getWorld(world);
          Location loc = new Location(world, x, y, z);
       } else {
         // invalid world
      }
    }

    If the file is going to contain more than just playeruuid entries, put them all under a single parent node such as "playerUUIDS" so instead of looping through all the config keys, you can use

    getConfig().getConfigurationSection("playerUUIDS").getKeys(false));

    vs

    getConfig().getKeys(false));

    This is to prevent looping through invalid / unintended keys.

    Also, just as a fyi:
    getKeys(false) will return only parent keys of the configuration section, while getKeys(true) will return all parent and child nodes of the configuration section.
     
    #2 kixmc, May 30, 2020
    Last edited: May 30, 2020
    • Like Like x 2
    • Informative Informative x 1
  3. Thanks so much for your help, it worked perfectly! I completely forgot about getKeys(false) lmao!
     
  4. Glad to hear! Make sure you mark this thread as solved and if you're feeling generous feel free to leave a rating on my post c: