*** empty log message ***
[luabind.git] / test / test_lua_classes.cpp
blob7b0dbcac499da7a6926aa93f639109b80abd5d68
1 #include <boost/tokenizer.hpp>
3 #include "test.h"
4 #include <iostream>
6 namespace
8 LUABIND_ANONYMOUS_FIX int feedback = 0;
10 struct base
12 virtual ~base()
14 // std::cout << "~base\n";
15 feedback = -1;
18 virtual const char* f()
20 return "base";
24 struct baseWrap : base
27 luabind::object self_;
28 baseWrap(const luabind::object& self): self_(self) {}
30 static const char* fS(base* obj)
32 return obj->base::f();
35 virtual const char* f()
37 return luabind::call_member<const char*>(self_, "f");
41 struct simple_class
43 void f()
45 feedback = 3;
49 struct no_copy
51 no_copy() {}
52 virtual void f() = 0;
53 private:
54 no_copy(const no_copy&) {}
57 void set_feedback(int n)
58 { feedback = n; }
60 } // anonymous namespace
63 bool test_lua_classes()
65 using namespace luabind;
68 lua_State* L = lua_open();
69 lua_baselibopen(L);
70 lua_closer c(L);
71 int top = lua_gettop(L);
73 open(L);
75 module(L)
77 class_<no_copy>("no copy"),
79 class_<base, baseWrap>("base")
80 .def(constructor<>())
81 .def("f", &baseWrap::fS),
83 class_<simple_class>("simple_class")
84 .def(constructor<>())
85 .def("f", &simple_class::f),
87 def("set_feedback", &set_feedback)
90 dostring(L, "class 'derived' (base)\n"
91 "function derived:__init() super() end\n"
92 "function derived:f() return 'derived -> ' .. base.f(self) end\n");
94 dostring(L, "function create_derived() return derived() end");
96 base* ptr = call_function<base*>(L, "create_derived");
98 if (std::string("derived -> base") != ptr->f()) return false;
100 dostring(L, "class 'simple_derative' (simple_class)");
101 dostring(L, "function simple_derative:__init() super() end\n");
102 dostring(L, "a = simple_derative()");
103 dostring(L, "a:f()");
104 if (feedback != 3) return false;
106 dostring(L, "class 'simple_lua_class'\n");
107 dostring(L, "function simple_lua_class:__init()\n"
108 "super()\n"
109 "self.test_var = 1\n"
110 "end\n"
111 "function simple_lua_class:f()\n"
112 "g = 5\n"
113 "end\n");
114 dostring(L, "a = simple_lua_class()");
115 dostring(L, "a:f()");
116 if (feedback != 3) return false;
117 object g = get_globals(L)["g"];
118 if (object_cast<int>(g) != 5) return false;
120 if (top != lua_gettop(L)) return false;
122 dostring(L, "a = derived()");
127 if (feedback != -1) return false;
131 lua_State* L = lua_open();
132 lua_baselibopen(L);
133 lua_closer c(L);
135 open(L);
137 function(L, "set_feedback", &set_feedback);
139 dostring(L, "class 'simple'");
140 dostring(L, "function simple:__init() set_feedback(321) end");
141 dostring(L, "function simple:__finalize() set_feedback(123) end");
143 dostring(L, "a = simple()");
145 if (feedback != 321) return false;
148 if (feedback != 123) return false;
150 return true;