Go Down

Topic: String as a function name ?? (Read 1 time) previous topic - next topic

jraskell

Or, with function pointers and lookup table:

Code: [Select]

struct funcLookup{
  char name[10];
  void (*function)(int);
};

int x = 10;
funcLookup funcTable[3];

void setup(){
  strcpy(funcTable[0].name, "func1");
  strcpy(funcTable[1].name, "func2");
  strcpy(funcTable[2].name, "func3");
 
  funcTable[0].function = &func1;
  funcTable[1].function = &func2;
  funcTable[2].function = &func3;
 
  Serial.begin(115200);
 
  char funcName[] = "func2";
 
  callFunc(funcName, 10);
 
}

void loop(){
 
 
}

void callFunc(char* funcName, int val){
  for(int i = 0; i < 3; i++){
    if(strcmp(funcName, funcTable[i].name) == 0){
      funcTable[i].function(val);
      return;
    }
  }
}

void func1(int val){
  Serial.println("Function 1");
  Serial.println(val);
}

void func2(int val){
  Serial.println("Function 2");
  Serial.println(val);
}

void func3(int val){
  Serial.println("Function 3");
  Serial.println(val);
}

Professor Chaos


Go Up