lua-users home
lua-l archive

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


Archibald wrote:

>>I want to share my identificators by both program and script. It's easy
>>when I use #define (I simply delete #define part and copy the rest to 
the
>>script). But how can I do it when I use C++ enum? Is it possible in lua 
to
>>do it other way than manually giving each identificator it's number?
>>
>>enum enumItem {  ITEM_SWORD, ITEM_AXE, ITEM_SHIELD };

>Lua traditionally uses strings instead of numbers for enums (after all, 
enums
>and defines were introduced to improve readabiliy too). To map strings to
>numbers, use luaL_findstring. See the POSIX library lposix for examples 
of
>this technique. See also f_seek in src/lib/liolib.c.
>--lhf

Here's an outrageous hack:

// C side

#define Enum(n) enum n


Enum(enumItem) {ITEM_SWORD, ITEM_AXE, ITEM_SHIELD}


-- Lua side
U:\>lua
Lua 5.0  Copyright (C) 1994-2003 Tecgraf, PUC-Rio
> setmetatable(_G, {__index = function(t, k) return k end})
> function Enum(name)
>>   return function(table)
>>     local invert = {}
>>     for k, v in table do invert[v] = k - 1 end
>>     _G[name] = invert
>>   end
>> end
>
>
> Enum(enumItem) {ITEM_SWORD, ITEM_AXE, ITEM_SHIELD}
>
> =enumItem.ITEM_AXE
1
>
-- Don't forget to turn the metatable off when you're finished with it :)