I have a C program which uses Lua for scripting. In order to keep readability and avoid importing several constants within the individual Lua states, I condense a large amount of functions within a simple call (such as “ObjectSet(id, “ANGLE”, 45)”), by using an “action” string.
To do this I have a large if tree comparing the action string to a list (such as “if(stringcompare(action, “ANGLE”) … else if (stringcompare(action, “X”)… etc”)
This approach works well, and within the program it’s not really slow, and is fairly quick to add a new action. But I kind of feel perfectionist. Is there a better way to do this in C?
And having Lua in heavy use, maybe there is a way to use it for this purpose? (embedded “chunks” making a dictionary?) Although this part is mostly curiosity.
Edit: I should note I am not using C++
It’s hard to say exactly what might be better, since you’re not very clear about what your constraints are. Other answers show what you could do if you were willing to export more symbols into Lua or delegate more work to Lua. My answer addresses a narrow question: how could you refactor your C code without changing the way you interact with Lua? I propose you make your code table-driven.
Here’s a design sketch:
If the linear search through actions gets too expensive, you can sort by name when you open the library, then call
bsearch.