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
17#ifndef HEADER_SUPERTUX_SQUIRREL_SQUIRREL_UTIL_HPP
18#define HEADER_SUPERTUX_SQUIRREL_SQUIRREL_UTIL_HPP
19
20#include <assert.h>
21#include <limits>
22#include <memory>
23#include <sstream>
24#include <vector>
25
26#include "squirrel/squirrel_virtual_machine.hpp"
27#include "squirrel/squirrel_error.hpp"
28#include "scripting/wrapper.hpp"
29
30typedef std::vector<HSQOBJECT> ScriptList;
31
32std::string squirrel2string(HSQUIRRELVM vm, SQInteger i);
33void print_squirrel_stack(HSQUIRRELVM vm);
34
35SQInteger squirrel_read_char(SQUserPointer file);
36
37HSQUIRRELVM object_to_vm(HSQOBJECT object);
38
39void compile_script(HSQUIRRELVM vm, std::istream& in,
40 const std::string& sourcename);
41void compile_and_run(HSQUIRRELVM vm, std::istream& in,
42 const std::string& sourcename);
43
44template<typename T>
45void expose_object(HSQUIRRELVM vm, SQInteger table_idx,
46 std::unique_ptr<T> object, const std::string& name)
47{
48 sq_pushstring(vm, name.c_str(), -1);
49 scripting::create_squirrel_instance(vm, object.release(), true);
50
51 if (table_idx < 0)
52 table_idx -= 2;
53
54 // register instance in root table
55 if (SQ_FAILED(sq_createslot(vm, table_idx))) {
56 std::ostringstream msg;
57 msg << "Couldn't register object '" << name << "' in squirrel table";
58 throw SquirrelError(vm, msg.str());
59 }
60}
61
62static inline void unexpose_object(HSQUIRRELVM vm, SQInteger table_idx,
63 const std::string& name)
64{
65 assert(name.length() < static_cast<size_t>(std::numeric_limits<SQInteger>::max()));
66 sq_pushstring(vm, name.c_str(), static_cast<SQInteger>(name.length()));
67
68 if (table_idx < 0)
69 table_idx -= 1;
70
71 if (SQ_FAILED(sq_deleteslot(vm, table_idx, SQFalse))) {
72 std::ostringstream msg;
73 msg << "Couldn't unregister object '" << name << "' in squirrel root table";
74 throw SquirrelError(vm, msg.str());
75 }
76}
77
78#endif
79
80/* EOF */
81