I’ve written a simple CLI in C that understands four basic instructions: add, deduct and multiply two numbers and exit.
I can type something like add(4,5) after the prompt and it works perfectly. But I want the user to be capable of defining variables and use them afterwards. I mean, a user types myvar = myobj(param_1,param_2) and then mymethod(myvar) and everything works well.
How can I get this?
EDIT:
Finally I used the uthash library written in C by Troy Hanson and you can find at http://uthash.sourceforge.net/
Thanks for all your answers.
First part is parsing (“how are you going to recognize names in the input?”), the second part: “how to store and manage variables?”.
About parsing. If your parser is really simple, just place some additional checks in places where integers are supposed to be recognized, and if not, look up the value by name in the variable store (read more below). The use of some regular expressions is recommended to split the input to meaningful pieces (“lexemes”, in compiler/interpreters parlance).
About storing. You need a structure that gives easy and fast access to an item by its name and supports adding and deleting entries. This is well handled by a map or a hashtable (there’s no stardard map implementation in the C standard library,
<map>/<unordered_map>in C++ will suffice). For a small amount of variables, just an array or a list ofstruct variable { const char *name; vardata_t var; }may be used (though lookups may be increasingly slow, you can consider binary search to enhance this).