miniswig supports int, float and string constants now
[supertux.git] / src / scripting / wrapper_util.hpp
1 #ifndef __WRAPPERUTIL_HPP__
2 #define __WRAPPERUTIL_HPP__
3
4 #include <squirrel.h>
5 #include <exception>
6 #include <sstream>
7 #include <string>
8
9 struct WrappedFunction {
10     const char* name;
11     SQFUNCTION f;
12 };
13
14 template<typename T>
15 struct WrappedConstant {
16     const char* name;
17     T value;
18 };
19
20 struct WrappedClass {
21     const char* name;
22     WrappedFunction* functions;
23     WrappedConstant<int>* int_consts;
24     WrappedConstant<float>* float_consts;
25     WrappedConstant<const char*>* string_consts;
26 };
27
28 class SquirrelError : public std::exception
29 {
30 public:
31   SquirrelError(HSQUIRRELVM v, const std::string& message) throw();
32   virtual ~SquirrelError() throw();
33
34   const char* what() const throw();
35 private:
36   std::string message;
37 };
38
39 void register_functions(HSQUIRRELVM v, WrappedFunction* functions);
40 void register_classes(HSQUIRRELVM v, WrappedClass* classes);
41
42 static inline void push_value(HSQUIRRELVM v, int val)
43 {
44     sq_pushinteger(v, val);
45 }
46
47 static inline void push_value(HSQUIRRELVM v, float val)
48 {
49     sq_pushfloat(v, val);
50 }
51
52 static inline void push_value(HSQUIRRELVM v, const char* str)
53 {
54     sq_pushstring(v, str, -1);
55 }
56
57 template<typename T>
58 void register_constants(HSQUIRRELVM v, WrappedConstant<T>* constants)
59 {
60     sq_pushroottable(v);
61     for(WrappedConstant<T>* c = constants; *constants->name != 0; ++c) {
62         sq_pushstring(v, c->name, -1);
63         push_value(v, c->value);
64         if(sq_createslot(v, -3) < 0) {
65             std::stringstream msg;
66             msg << "Couldn't register int constant '" << c->name << "'";
67             throw SquirrelError(v, msg.str());
68         }
69     }
70     sq_pop(v, 1);
71 }
72
73 void print_squirrel_stack(HSQUIRRELVM v);
74
75 #endif