3

所以有一个 main_window 类来处理所有事情,这里重要的是敌人的向量,敌人,当敌人死亡时,它会将一个效果对象推回效果的向量中。方便的地方来了

lua_State *G = luaL_newstate(); // I need this thing to be global

// class constructor
Effect::Effect(int ix, int iy)
{
  // not important codes deleted
  luaL_openlibs(G);
  luaL_dofile(G, "script/effect/blue_explosion.lua");
  lua_getglobal(G, "draw_x");
  draw_x = lua_tointeger(G, -1);
  lua_getglobal(G, "draw_y");
  draw_y = lua_tointeger(G, -1);
  /* the function name */
  lua_getfield(G, LUA_GLOBALSINDEX, "setup");
  /* the first argument */
  lua_pushnumber(G, ix);
  /* the second argument */
  lua_pushnumber(G, iy);
  /* call the function with 2 arguments, return 1 result */
  lua_call(G, 2, 0);
}

这些事情本身就很好,但问题来了

void Effect::close_lua()
{
    lua_close(G);
}

在没有这个闭包的情况下在效果的生命周期结束时调用它,它会开始吃掉我的 Ram,但是如果我使用它,并且创建了很多的效果对象,这个东西会因为
访问冲突而崩溃(分段错误)

有人知道如何解决这个问题吗?

还是我应该只更改脚本语言?

好像我有两次关闭一个状态,但是 lua_close(G) 在同一个向量中的不同对象中,我只是想一个办法,也许我也可以把 lua_states 放在一个向量中?

4

1 回答 1

2

problem solved! what i did was make the lua_state object to private and it's not crashing anymore, it's probably is because that lua_state pointer got copied to other places, so now after i made it private it's not copyable anymore!

so first in header, private section declare lua_State *G;
and use G = luaL_newstate(); in the constructer

and some how it won't work in destructor, so i had this in the loop

for(int i = effects->size()-1; i > -1 ; i--)
{
    effects->at(i).act();
    if(effects->at(i).should_remove())
    {
        effects->at(i).close_lua();
        effects->erase(effects->begin()+i);
    }
}

that manually run the close_lua() witch is

void Effect::close_lua()
{
    lua_close(G);
    //std::cout << "closed"; a chick line
}

these lines worked perfectly as i watching the memory of the program in task manager

于 2013-10-20T03:31:37.293 回答