lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

On 01/18/2012 01:07 AM, Philipp Janda wrote:

On 17.01.2012 08:12, HyperHacker wrote:
When I write modules to wrap C++ objects, they usually have a __index
method that does a lot of string comparing, like:
if(!strcmp(key, "foo")) lua_pushcfunction(L, obj_method_foo);
else if(!strcmp(key, "bar")) lua_pushcfunction(L, obj_method_bar);
etc... I'm not sure if compilers can optimize this, but doing all
those strcmp()s every time a method/field is looked up seems terribly

Try Ragel[1].


I've attached the template I use for such occasions.

What about gperf?

struct str2id_s { const char *name; int id; };
"foo",    0
"bar",    1
"baz",    2
"foobar", 3
"hello",  4
"bye",    5

#include <stdio.h>

int str2id(const char *s)
	struct str2id_s *p = in_word_set(s, strlen(s));
	return p ? p->id : -1;

int main(int argc, char *argv[])
	printf( "%d \n", str2id("foo") );
	printf( "%d \n", str2id("bar") );
	printf( "%d \n", str2id("baz") );