|
1 #ifndef SQUIRREL_CLASS_HPP |
|
2 #define SQUIRREL_CLASS_HPP |
|
3 |
|
4 /** |
|
5 * The template to define classes in Squirrel. It takes care of the creation |
|
6 * and calling of such classes, to make the AI Layer cleaner while having a |
|
7 * powerful script as possible AI language. |
|
8 */ |
|
9 template <class CL> |
|
10 class DefSQClass { |
|
11 private: |
|
12 const char *classname; |
|
13 |
|
14 public: |
|
15 DefSQClass(const char *_classname) : |
|
16 classname(_classname) |
|
17 {} |
|
18 |
|
19 /** |
|
20 * The destructor, to delete the real instance. |
|
21 */ |
|
22 static SQInteger Destructor(SQUserPointer p, SQInteger size) |
|
23 { |
|
24 /* Remove the real instance too */ |
|
25 if (p != NULL) delete (CL *)p; |
|
26 return 0; |
|
27 } |
|
28 |
|
29 /** |
|
30 * The constructor, to create the real instance. |
|
31 */ |
|
32 static SQInteger Constructor(HSQUIRRELVM vm) |
|
33 { |
|
34 /* Create the real instance */ |
|
35 CL *instance = new CL(); |
|
36 sq_setinstanceup(vm, -1, instance); |
|
37 sq_setreleasehook(vm, -1, &DefSQClass::Destructor); |
|
38 return 0; |
|
39 } |
|
40 |
|
41 /** |
|
42 * This defines a method inside a class for Squirrel. |
|
43 */ |
|
44 template <typename Func> |
|
45 void DefSQFunction(HSQUIRRELVM vm, Func function_proc, const char *function_name) |
|
46 { |
|
47 // int nparam = 1; |
|
48 // const char *params = "x"; |
|
49 void *ptr; |
|
50 |
|
51 sq_pushstring(vm, function_name, -1); |
|
52 /* Store the real function-pointer in the user-data */ |
|
53 ptr = sq_newuserdata(vm, sizeof(function_proc)); |
|
54 memcpy(ptr, &function_proc, sizeof(function_proc)); |
|
55 sq_newclosure(vm, SQConvert::DefSQCallback<CL, Func>, 1); |
|
56 // sq_setparamscheck(vm, nparam, params); |
|
57 sq_createslot(vm, -3); |
|
58 } |
|
59 |
|
60 void PreRegister(HSQUIRRELVM vm) |
|
61 { |
|
62 /* Prepare the new class */ |
|
63 sq_pushroottable(vm); |
|
64 sq_pushstring(vm, this->classname, -1); |
|
65 sq_newclass(vm, SQFalse); |
|
66 |
|
67 /* Register a constructor */ |
|
68 sq_pushstring(vm, "constructor", -1); |
|
69 sq_newclosure(vm, &DefSQClass::Constructor, 0); |
|
70 // sq_setparamscheck(vm, nparam, params); |
|
71 sq_createslot(vm, -3); |
|
72 } |
|
73 |
|
74 void PostRegister(HSQUIRRELVM vm) |
|
75 { |
|
76 /* Create the class and all his methods */ |
|
77 sq_createslot(vm, -3); |
|
78 } |
|
79 }; |
|
80 |
|
81 #endif /* SQUIRREL_CLASS_HPP */ |