eliasdaler

Safe_handle.cpp

Jan 15th, 2017
303
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.14 KB | None | 0 0
  1. #include <sol.hpp>
  2. #include <string>
  3. #include <iostream>
  4.  
  5. class Entity {
  6. public:
  7.     Entity() : name("John") {}
  8.     const std::string& getName() const { return name; }
  9. private:
  10.     std::string name;
  11. };
  12.  
  13. int main()
  14. {
  15.     sol::state lua;
  16.     lua.open_libraries();
  17.  
  18.     lua.new_usertype<Entity>("Entity",
  19.         "getName", &Entity::getName,
  20.         "extraFunc", [](Entity& e) { std::cout << "EXTRA!" << e.getName() << " is working\n"; });
  21.  
  22.     lua.do_file("script.lua");
  23.  
  24.     sol::function createHandle = lua["createHandle"];
  25.     sol::function test = lua["test"];
  26.     sol::function test2 = lua["test2"];
  27.     sol::function onEntityDeleted = lua["onEntityDeleted"];
  28.    
  29.     sol::object handle(lua);
  30.  
  31.     {
  32.         Entity e;
  33.         handle = createHandle(e);
  34.  
  35.         test(handle); // everything ok here
  36.         test2(e);
  37.  
  38.         // entity will be destroyed after leaving the scope, so we need to notify handle about that
  39.         onEntityDeleted(handle);
  40.     }
  41.  
  42.     try {
  43.         test(handle); // this will throw error
  44.     }
  45.     catch (sol::error& e) {
  46.         std::cout << e.what() << std::endl;
  47.     }
  48.     return 0;
  49. }
Add Comment
Please, Sign In to add comment