the boat works now
[supertux.git] / src / scripting / wrapper_util.hpp
1 //  $Id$
2 //
3 //  SuperTux
4 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
5 //
6 //  This program is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU General Public License
8 //  as published by the Free Software Foundation; either version 2
9 //  of the License, or (at your option) any later version.
10 //
11 //  This program is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 //  GNU General Public License for more details.
15 //
16 //  You should have received a copy of the GNU General Public License
17 //  along with this program; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19
20 #ifndef __WRAPPERUTIL_HPP__
21 #define __WRAPPERUTIL_HPP__
22
23 #include <squirrel.h>
24 #include <sstream>
25 #include <stdexcept>
26 #include <string>
27 #include "wrapper.hpp"
28 #include "squirrel_error.hpp"
29
30 namespace Scripting
31 {
32
33 std::string squirrel2string(HSQUIRRELVM vm, int i);
34 void print_squirrel_stack(HSQUIRRELVM vm);
35 void compile_script(HSQUIRRELVM vm, std::istream& in, const std::string& sourcename);
36 void compile_and_run(HSQUIRRELVM vm, std::istream& in, const std::string& sourcename);
37
38 template<typename T>
39 void expose_object(HSQUIRRELVM v, int table_idx, T* object,
40                    const std::string& name, bool free = false)
41 {
42   sq_pushstring(v, name.c_str(), -1);
43   Scripting::create_squirrel_instance(v, object, free);
44
45   if(table_idx < 0)
46     table_idx -= 2;
47
48   // register instance in root table
49   if(SQ_FAILED(sq_createslot(v, table_idx))) {
50     std::ostringstream msg;
51     msg << "Couldn't register object '" << name << "' in squirrel table";
52     throw Scripting::SquirrelError(v, msg.str());
53   }
54 }
55
56 static inline void unexpose_object(HSQUIRRELVM v, int table_idx, const std::string& name)
57 {
58   sq_pushstring(v, name.c_str(), name.length());
59   
60   if(table_idx < 0)
61     table_idx -= 1;
62   
63   if(SQ_FAILED(sq_deleteslot(v, table_idx, SQFalse))) {
64     std::ostringstream msg;
65     msg << "Couldn't unregister object '" << name << "' in squirrel root table";
66     throw Scripting::SquirrelError(v, msg.str());
67   }
68 }
69
70 }
71
72 #endif