lua-users home
lua-l archive

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


From: Curt Carpenter curtc@microsoft.com XXXXXXXXXXXXX
> I want Lua syntax like:
>     local a = table.KnownKeyName1
>     local b = table.KnownKeyName37
>     local c = table.KnownKeyName1234
>     -- do something with a, b, c, etc.
>
> etc., where those keynames don't exist and the values are supplied by an
> index tag method, established like so:

If this is truly a bottleneck in your program, then there's no particular
reason to use a naive multi-strcmp() approach.  For your particular example,
you could use (roughly):

  if ( strncmp(keyname, "KnownKeyName", 12) == 0 ) {
      switch ( atoi(keyname + 12) ) {
          case 1:
          case 2:
          ...
      }
  }
  ...

Which is sort of a smart-assed answer, I know, but my point is there are
lots of good string searching algorithms out there.  In particular, you
should should check out gperf:

    http://www.gnu.org/software/gperf/gperf.html

Which will generate a perfect hash table for any set of strings you give it.
It's very handy for identifying keywords like this.

If you need to dynamically create some of the table fields, you can just
spin your own hash table.  With a good hash function, a good sized table,
and collisions handled by linked lists, you'll probably never see more than
one or two string compares.

Although I'm sure some one will post a very clever Lua-based solution which
will mostly invalidate this post.  But I still look forward to reading it.
:)

Good luck.

--
Ryan Bright