home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #31 / NN_1992_31.iso / spool / rec / games / programm / 5223 < prev    next >
Encoding:
Text File  |  1992-12-30  |  1.5 KB  |  56 lines

  1. Path: sparky!uunet!gatech!concert!borg!beethoven!bell
  2. From: bell@beethoven.cs.unc.edu (Andrew Bell)
  3. Newsgroups: rec.games.programmer
  4. Subject: Re: Goto [variable] in C++ ?
  5. Message-ID: <18566@borg.cs.unc.edu>
  6. Date: 30 Dec 92 08:01:08 GMT
  7. References: <725647749.AA00000@therose.pdx.com>
  8. Sender: news@cs.unc.edu
  9. Organization: The University of North Carolina at Chapel Hill
  10. Lines: 44
  11.  
  12. kinsman@jupiter.sun.csd.unb.ca (Aphoriel/Kinsman) writes:
  13.  
  14. >This is a question from someone new to C...
  15.  
  16. >How could I set up C code so that a program goes to a function where the
  17. >name of the function is placed in a string variable?
  18.  
  19. You can't, but why bother?
  20.  
  21. >The specific use I'm thinking of is for an adventure game, where the
  22. >function the parser calls depends on the verb the player used in typing
  23. >in his command..
  24.  
  25. So set up a table and a function:
  26.  
  27. struct CommandEntry {
  28.   char *command;
  29.   int (* function)();
  30. } commandTable[] = {
  31.   {"eat",eatFunction},
  32.   {"give",giveFunction}
  33.   [...]
  34. };
  35.  
  36. #define NUMCOMMANDS (sizeof(commandTable))/(sizeof(struct commandEntry))
  37.  
  38. void
  39. callCommand(char *command)
  40. {
  41.    /* Go through the table until we find a match */
  42.    for ( int commandnum = 0 ; commandnum < NUMCOMMANDS ; commandnum++ )
  43.        /* If we find one... */
  44.        if ( !strcmp(command,commandTable[commandnum].command) )
  45.        {
  46.            /* run the command and return. */
  47.            commandTable[commandnum].function();
  48.            return;
  49.        }
  50.     /* If we didn't find this command, say so. */
  51.     fprintf(stderr,"Unrecognized command.\n");
  52. }
  53.  
  54. Or something like that.
  55.  
  56.