So, I’m using the GinSing library for Arduino, and I’ve run into a problem. There is a chunk of their code in which they extract a value from a variable name (or object? or something?). I’ve read up about having values in variable names on here (Stack Overflow) and I know that you’re not supposed to do it, but I’m stuck!
I’m not a good enough programmer to modify their code, but I still want to use it (the GinSing shield is pretty cool). Here’s an example of the usage of their s->setEnvelope:
s->setEnvelope (OSC_1, AT_100MS, 1.0f, DR_100MS, 1.0f, DR_100MS, 0.0f);
I want to randomly change those values so I made this:
String adsrMake(String type, int attack){
return type + attack + "MS";
}
and then I do this:
s->setEnvelope (OSC_1, adsrMake("AT_",time/2), etc..
but it doesn’t like that. It doesn’t want a string, it wants a name (?) or something. The error I get says it wants:
void GinSingSynth::setEnvelope(GSSynthOsc, GSAttackDur, float, GSDecRelDur, float, GSDecRelDur, float)
I opened up the .cpp file, and it says it’s doing this on the other end:
void GinSingSynth::setEnvelope (GSSynthOsc oscIdx ,
GSAttackDur attackDur , float attackAmp,
GSDecRelDur decayDur , float decayAmp ,
GSDecRelDur releaseDur, float releaseAmp )
{
ubyte voiceIdx = OscIdxToVoiceIdx(oscIdx);
// Construct ADR bytes ( high four bits amplitude, low four bits duration )
ubyte atkByte = ( (ubyte) ( 0x0f * attackAmp ) << 4 ) + attackDur;
ubyte dcyByte = ( (ubyte) ( 0x0f * decayAmp ) << 4 ) + decayDur;
ubyte rlsByte = ( (ubyte) ( 0x0f * releaseAmp ) << 4 ) + releaseDur;
While you know that the
GSAttackDurenum members are sequential numeric values, to rely upon inside information of a third-party library (or even your own library) to infer that a cast of an integer to an enum is valid or safe is not best practice.It may not always be true in the general case or under code maintenance that the values are sequential or even an arithmetic progression. A better general solution is to use a look-up table to translate your random integer to a valid enum type value, thus requiring no knowledge of the actual enum literal values in either magnitude or order: