forked from SteveKChiu/lua-intf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.cpp
96 lines (79 loc) · 1.54 KB
/
test.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <lua.hpp>
#include "LuaIntf/LuaIntf.h"
/*
* Class declaration
*/
class Base
{
public:
virtual ~Base() { }
};
class Derived : public Base
{
public:
int a;
};
/*
* Global variables
*/
Base *b;
std::shared_ptr<Base> sp;
/*
* Global accessor functions
*/
Base *getBase()
{
return b;
}
std::shared_ptr<Base> getSP()
{
return sp;
}
/*
* Downcast function
*/
namespace LuaIntf
{
LUA_USING_SHARED_PTR_TYPE(std::shared_ptr);
template <>
struct LuaAutomaticDowncast<Base>
{
static void *getClassID(Base *b, bool is_const)
{
if (dynamic_cast<Derived*>(b) != nullptr)
{
return is_const?CppConstSignature<Derived>::value():CppClassSignature<Derived>::value();
}
else
{
return is_const?CppConstSignature<Base>::value():CppClassSignature<Base>::value();
}
}
};
}
int main(int argc, char *argv[])
{
using namespace LuaIntf;
LuaContext L;
LuaBinding(L)
.beginClass<Base>("Base")
.endClass()
.beginExtendClass<Derived, Base>("Derived")
.addVariable("a", &Derived::a)
.endClass()
.beginModule("globals")
.addVariableRef("b", &b)
.addVariableRef("sp", &sp)
.addFunction("getBase", &getBase)
.addFunction("getSP", &getSP)
.endModule();
b = new Derived;
static_cast<Derived*>(b)->a = 5;
sp.reset(new Derived);
static_cast<Derived&>(*sp).a = 10;
// Can access the field a in all cases
Lua::exec(L, "print (globals.b.a)");
Lua::exec(L, "print (globals.sp.a)");
Lua::exec(L, "print (globals.getBase().a)");
Lua::exec(L, "print (globals.getSP().a)");
}