So, as part of my current project, I'm trying to handle my input for layered menus and such from the ground up for the sake of experimentation. As such, I have this code currently:
if(AreKeysLeft()) {
({ KEY_UP: startWindow.handleUp,
KEY_DOWN: startWindow.handleDown,
KEY_LEFT: startWindow.handleLeft,
KEY_RIGHT: startWindow.handleRight,
KEY_Z: startWindow.handleAccept,
KEY_X: startWindow.handleCancel
})[GetKey()].call(startWindow);
}
Now, this code does not currently work because the [GetKey()] step returns undefined, which is because KEY_UP, DOWN, etc. are actually numerical constants, and I can't seem to break them down within the object creation to do something like convert KEY_UP to 84, nor can I seem to get the value from GetKey() as its word form. I'm a bit stumped as to what to do here that would still result in legible code while also having equivalent functionality.
You'll be able to do this in Sphere 2.0, because the built-in enumerations are two-way, which is to say:
Key[Key.Enter] = "Enter"Therefore:
if(kb.haveKeys) {
({ Up: startWindow.handleUp,
Down: startWindow.handleDown,
Left: startWindow.handleLeft,
Right: startWindow.handleRight,
Z: startWindow.handleAccept,
X: startWindow.handleCancel
})[Key[kb.getKey()]].call(startWindow);
}
I'm unaware of a way to do this in Sphere 1.x though.
It's worth noting that this would have been possible if Sphere supported ES6 using computed property names, in which case you could just wrap KEY_UP etc. constants in brackets. Alas, ES6+ support still looks like it's a ways off for Duktape.
Alright, I guess I'll just make my own reverse-enumeration function for now and call it good. Glad to know this kind of thing won't be as much of a problem in Sphere 2.0 ;)