lua-users home
lua-l archive

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


Ah, luaL_checkoption, I knew I had seen that somewhere.

I see it used here:
http://www.lua.org/source/5.1/lbaselib.c.html#luaB_collectgarbage

I can see it's fairly convenient. However in this case, collectgarbage probably isn't (or at least shouldn't) be called a lot. For functions that are called a lot, would it be more efficient to pre-create the table of strings/values for lookup?



On Wed, Dec 4, 2013 at 5:47 PM, Philipp Janda <siffiejoe@gmx.net> wrote:
Am 04.12.2013 23:23 schröbte Marc Lepage:

Say I am writing C code that wants to get and set properties with string
values, the equivalent of:

     obj1.foo = 'optionA'
     obj2.foo = 'optionB'
     print(obj3.foo)

where in the C code, the strings like 'optionA' must be converted to values
like ENUM_A. Typically, for a property I might have up to half a dozen
values.

So for setting a property, I could manually get the argument as a string,
and use strcmp to choose which enum value is being specified.

Or, I could just build a table where keys are strings and values are the
enum values, and use that to lookup which enum value is being specified.

Which is generally preferred? Is there a better way?


The usual way is probably `luaL_checkoption`[1]. See e.g. here[2].

  [1]: http://www.lua.org/manual/5.2/manual.html#luaL_checkoption
  [2]: https://github.com/xolox/lua-apr/blob/master/src/proc.c#L282

Philipp