Create an Array of Variable Pairs (or touples?)

edited February 2017 in Questions about Code

I am looking for a way to make my code easier to read and edit.

I am creating an interface for a sketch that has a bunch of buttons. Each button has a name and a hotkey. I have a setup section at the beginning of my code where I can edit names and hotkeys. It looks something like this:

// Setup Section 
String[] buttonNames= {
  "firstButton", 
  "secondButton", 
  "thirdButton", 
  "someOtherButton"
};

char[] buttonHotkeys= {
  'q',
  'w',
  'e',
  'r',
};
//End Setup

Later on there is a for loop in which I use this two arrays to create the buttons.

I would prefer to be able to do it like this:

//Setup Section
magicalDataTyp[] buttonNamesandHotkeys {
  ("firstButton", 'q'),
  ("secondButton", 'w'),
  ("thirdButton", 'e'), 
  ("someOtherButton", 'r')
}
// End Setup

How would you go about doing this? (again, the goal here is not to make my code more efficient or anything, the goal is that someone editing the code can with a single glance identify which buttons are associated with which hotkey. Imagine that there might be 30 buttons instead of 4)

Thanks for any suggestions

Tagged:

Answers

  • Answer ✓
    String[][] buttonNamesandHotkeys = new String[][]{
      {"firstButton", "q"},
      {"secondButton", "w"},
      {"thirdButton", "e"}, 
      {"someOtherButton", "r"}
    };
    
    void setup() {
      println(buttonNamesandHotkeys[1][0], buttonNamesandHotkeys[1][1]);
    }
    

    this is as close as you can get to what you have. note the chars are now strings.

    it's not great though - there's no obvious relation between array[n][0] and buttonName, for instance.

    you'd be better off with a class, then you can:

    Button[] buttons = new Button[] {
      new Button("firstButton", 'q'), 
      new Button("secondButton", 'w'), 
      new Button("thirdButton", 'e')
    };
    
    void setup() {
      println(buttons[2].name);
      noLoop();
    }
    
    class Button {
      String name;
      char k;
      Button(String name, char k) {
        this.name = name;
        this.k = k;
      }
    }
    
  • Sorry I never got back to you. I ended up doing this. Thank you.

  • edited August 2017

    excuse me for jumping in

    your wrote

    I am creating an interface for a sketch that has a bunch of buttons. Each button has a name and a hotkey.

    Ok, but there is more to it then than just the hotkeys, isn't?

    When these are mouse keys, each of them has a position, a size, an image and a command associated with it.

    Is that correct?

Sign In or Register to comment.