Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

c++ - Using unique dynamic variable names (not variable values!)

Ok so, this is more a sanity check than anything else.

Lets asume we have a struct called lua_State, now I need to create a uncertain amount of unique lua_State's. To make sure I don't use the same variable name twice I would need to have some sort of way to get an unique variable every time i make a new state.

However there is only one way (I think?) to create a new state, and that is as follows:

lua_State *S = lewL_newstate();

Now I would need some way to dynamically change that "S" to.. whatever.

For example: If I had 4 lua files, and I wanted to load each into their own lua_State, I would call: lua_State *A = lewL_newstate(); for the first, lua_State *B = lewL_newstate(); for the second, and so on. Keep in mind the number of lua files varies so creating a fixed number of states probably won't go over well.

How would I go about doing this?

clarification:

.h

struct lua_State

.cpp

createNewState(Lua_State* something){
 lua_State* something = luaL_newstate();
}

I thought about creating a

std::map<int, lua_State*> luaMap;

but then I would still have the problem of actually generating (for lack of better words) a variable name for every int-index.

So, have I been drinking too much coffee and is there a glaringly obvious simply solution to what I am trying to do, or should I just stop coding untill the crazy blows over?

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use a std::vector to both store the created states and generate sequential identifiers (i.e. array indices). Unless I'm missing something, then you are grossly over-complicating your requirements.

std::vector<lua_State *> stateList;

// create a new Lua state and return it's ID number
int newLuaState()
{
    stateList.push_back(luaL_newstate());
    return stateList.size() - 1;
}

// retrieve a Lua state by its ID number
lua_State * getLuaState(int id)
{
    assert(0 <= id && stateList.size() > id);
    return stateList[id];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...