lua-users home
lua-l archive

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


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.


/* This is a template for matching one of multiple strings using the
 * ragel state machine compiler. Edit/extend the state machine and the
 * defines below. If using more than one state machine in a C file,
 * the exported function name must be redefined.
 * Compile (to str2id.h):
 * $ ragel -C -G2 str2id.rh
 * For graphviz output:
 * $ ragel -V -p str2id.rh | dot -T png -o out.png

#define STR2ID_FUNC_NAME str2id

#define  ID_FOO     0
#define  ID_BAR     1
#define  ID_BAZ     2
#define  ID_FOOBAR  3
#define  ID_HELLO   4
#define  ID_BYE     5

  machine s2i;
  main :=
    "foo"    %/{ return ID_FOO; } |
    "bar"    %/{ return ID_BAR; } |
    "baz"    %/{ return ID_BAZ; } |
    "foobar" %/{ return ID_FOOBAR; } |
    "hello"  %/{ return ID_HELLO; } |
    "bye"    %/{ return ID_BYE; };

/*            DO NOT CHANGE ANYTHING BELOW THIS COMMENT!            */

#include <stddef.h>

static unsigned STR2ID_FUNC_NAME( char const* p, size_t n ) {
  char const* pe = p + n;
  char const* eof = pe;
  int cs = 0;
  write data;
  write init;
  write exec;
  return -1;