Advertisement
Guest User

Untitled

a guest
Oct 26th, 2014
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. struct State
  2. {
  3. // deleted and defaulted ctors removed for brevity
  4. State(std::string name, uint32_t id) :
  5. id(id), state(luaL_newstate()), name(std::move(name))
  6. {
  7. assert(this->state != nullptr && "state is nullptr");
  8. assert(this->name != "" && "Name is empty");
  9.  
  10. luaL_openlibs(state);
  11. lua_settop(state, 0);
  12. }
  13.  
  14. ~State()
  15. {
  16. lua_close(state);
  17. }
  18.  
  19. uint32_t id;
  20. lua_State* state;
  21. std::string name;
  22. };
  23.  
  24. struct Script
  25. {
  26. // deleted and defaulted ctors removed for brevity
  27. Script(std::string name, uint32_t id, uint32_t stateId) :
  28. id(id), stateId(stateId), name(name) { }
  29.  
  30. uint32_t id;
  31. uint32_t stateId;
  32. std::string name;
  33. };
  34.  
  35. bool ScriptEngine::LoadScript(State& state, std::string filename)
  36. {
  37. auto success(luaL_loadfile(state.state, filename.c_str()) == 0);
  38. lua_setglobal(state.state, filename.c_str());
  39.  
  40. scripts.emplace_back(filename, nextScriptId, state.id);
  41. ++nextScriptId;
  42.  
  43. return success;
  44. }
  45.  
  46. int ScriptEngine::RunScript(Script& script)
  47. {
  48. auto state(GetState(script.stateId));
  49. assert(state != nullptr && "Script state is invalid");
  50.  
  51. lua_getglobal(state->state, script.name.c_str());
  52. // Segfaults in the above line in index2adr called by lua_getfield
  53. // if the state is not the same as the current state
  54.  
  55. auto top(lua_gettop(state->state));
  56. if(lua_pcall(state->state, 0, LUA_MULTRET, 0))
  57. {
  58. std::cout << "unable to run script " << script.name << " " <<
  59. lua_tostring(state->state, -1) << std::endl;
  60. assert(0);
  61. }
  62.  
  63. return top - lua_gettop(state->state);
  64. }
  65.  
  66. int RunScript(lua_State* state)
  67. {
  68. auto script((Script*)lua_touserdata(state, -1));
  69.  
  70. lua_pushliteral(state, "ScriptEngine");
  71. lua_gettable(state, LUA_REGISTRYINDEX);
  72.  
  73. auto engine((ScriptEngine*)lua_touserdata(state, -1));
  74.  
  75. return engine->RunScript(*script);
  76. }
  77.  
  78. local script = ScriptEngine.GetScript("config.txt")
  79. print(script)
  80.  
  81. local rets = ScriptEngine.RunScript(script)
  82. -- crash happens in the above line if the target script has a
  83. -- separate state than this script itself
  84.  
  85. print(rets)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement