使用唯一的动态变量名(不是变量值!)

2021-12-30 00:00:00 lua c++

好吧,这比其他任何事情都重要.

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

假设我们有一个名为 lua_State 的结构,现在我需要创建不确定数量的唯一 lua_State.为了确保我不会两次使用相同的变量名,我需要在每次创建新状态时使用某种方法来获取唯一变量.

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();

现在我需要某种方法来动态地将S"更改为..无论如何.

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

例如:如果我有 4 个 lua 文件,并且我想将每个文件加载到它们自己的 lua_State 中,我会调用: lua_State *A = lewL_newstate();首先,lua_State *B = lewL_newstate();第二个,依此类推.请记住,lua 文件的数量各不相同,因此创建固定数量的状态可能不会顺利.

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.

我该怎么做?

澄清:

.h

struct lua_State

.cpp

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

我想过创建一个

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

但是我仍然会遇到为每个 int-index 实际生成变量名(因为缺少更好的词)的问题.

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?

提前致谢.

推荐答案

使用 std::vector 来存储创建的状态并生成顺序标识符(即数组索引).除非我遗漏了什么,否则您的要求过于复杂.

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];
}

相关文章