Nemo
Nemo

Reputation: 112

Reading C++ #defines into Lua state

For a project I'm working on, we have about 2k defines we use to identify different items in the game, it looks like this:

#define ITEMID_WEAPON_SWORD_PEARL                41  
#define ITEMID_WEAPON_SWORD_CYCLONE              42  
#define ITEMID_WEAPON_SWORD_INVADERS             43  
#define ITEMID_WEAPON_SWORD_SWITCH               44  
#define ITEMID_WEAPON_SWORD_MULTIBLADE           45  
#define ITEMID_WEAPON_SWORD_KATANA               46  

Etc etc. Mind you this wasn't by choice, it's a system set in place by the previous developers and would take too much effort at this point to be practical.

I was asked to basically make a crafting system, and in the hopes that I could make it clean and organized, I wanted to use Lua. My plan was essentially to do something like the following:

Cooking =  
{  
    ["Sandvich"] =   
    {  
        {   --In  
            {ITEMID_COOKING_BREAD,  2, -1},  
            {ITEMID_COOKING_MEAT,   1, -1},  
            {ITEMID_COOKING_TOMATO, 1, -1},  
        },  
        {   --Out  
            {ITEMID_COOKING_SANDVICH, 1}  
        }  
    }  
}  

The only issue I can see with it, though, is that Lua can't natively read C/C++ #defines, as far as I know. (Maybe it can? That'd be nice.)

I was wondering if there are any libraries or modules or something I can use to read in these defines with, or maybe if I should use another method instead of Lua? I'm admittedly relatively unskilled with it, but given a starting point I should be able to get something up and running with very little effort.

Upvotes: 3

Views: 768

Answers (2)

lhf
lhf

Reputation: 72392

I'm not sure what your precise needs are.

If you just need to replace those identifiers by the corresponding numbers, with some luck you may be able to run your Lua file through the C preprocessor (cpp or gcc -E).

If you want to define Lua variables with those names and values, you can parse the C file in Lua with code like this:

C=[[
#define ITEMID_WEAPON_SWORD_PEARL                41  
#define ITEMID_WEAPON_SWORD_CYCLONE              42  
#define ITEMID_WEAPON_SWORD_INVADERS             43  
#define ITEMID_WEAPON_SWORD_SWITCH               44  
#define ITEMID_WEAPON_SWORD_MULTIBLADE           45  
#define ITEMID_WEAPON_SWORD_KATANA               46  
]]

for k,v in C:gmatch("#define%s+(%S+)%s+(%d+)") do
    _G[k]=tonumber(v)
end

If you don't want to make the variables global, use a different table instead of _G.

The code above is just a test. You may want to read your C file line by line or everything at once and then do the matching.

Upvotes: 3

tumdum
tumdum

Reputation: 2031

You can try using boost::wave for parsing those headers.

Upvotes: 1

Related Questions