squirrel_util.hpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // SuperTux
  2. // Copyright (C) 2006 Matthias Braun <matze@braunis.de>
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. #ifndef HEADER_SUPERTUX_SQUIRREL_SQUIRREL_UTIL_HPP
  17. #define HEADER_SUPERTUX_SQUIRREL_SQUIRREL_UTIL_HPP
  18. #include <assert.h>
  19. #include <limits>
  20. #include <memory>
  21. #include <sstream>
  22. #include <vector>
  23. #include "squirrel/squirrel_virtual_machine.hpp"
  24. #include "squirrel/squirrel_error.hpp"
  25. #include "scripting/wrapper.hpp"
  26. typedef std::vector<HSQOBJECT> SquirrelObjectList;
  27. std::string squirrel2string(HSQUIRRELVM vm, SQInteger i);
  28. void print_squirrel_stack(HSQUIRRELVM vm);
  29. SQInteger squirrel_read_char(SQUserPointer file);
  30. HSQUIRRELVM object_to_vm(const HSQOBJECT& object);
  31. void compile_script(HSQUIRRELVM vm, std::istream& in,
  32. const std::string& sourcename);
  33. void compile_and_run(HSQUIRRELVM vm, std::istream& in,
  34. const std::string& sourcename);
  35. template<typename T>
  36. void expose_object(HSQUIRRELVM vm, SQInteger table_idx,
  37. std::unique_ptr<T> object, const std::string& name)
  38. {
  39. sq_pushstring(vm, name.c_str(), -1);
  40. scripting::create_squirrel_instance(vm, object.release(), true);
  41. if (table_idx < 0)
  42. table_idx -= 2;
  43. // register instance in root table
  44. if (SQ_FAILED(sq_createslot(vm, table_idx))) {
  45. std::ostringstream msg;
  46. msg << "Couldn't register object '" << name << "' in squirrel table";
  47. throw SquirrelError(vm, msg.str());
  48. }
  49. }
  50. static inline void unexpose_object(HSQUIRRELVM vm, SQInteger table_idx,
  51. const std::string& name)
  52. {
  53. assert(name.length() < static_cast<size_t>(std::numeric_limits<SQInteger>::max()));
  54. sq_pushstring(vm, name.c_str(), static_cast<SQInteger>(name.length()));
  55. if (table_idx < 0)
  56. table_idx -= 1;
  57. if (SQ_FAILED(sq_deleteslot(vm, table_idx, SQFalse))) {
  58. std::ostringstream msg;
  59. msg << "Couldn't unregister object '" << name << "' in squirrel root table";
  60. throw SquirrelError(vm, msg.str());
  61. }
  62. }
  63. #endif
  64. /* EOF */