summaryrefslogtreecommitdiffstats
path: root/src/luabind-test.cpp
blob: bbb4f2a07b0c3a2f0eaefb24c59dc19abd07f833 (plain)
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
#include <cassert>
#include <iostream>
#include <string>

#include <luabind/luabind.hpp>
#include <lua.hpp>

void greet()
{
    std::cout << "hello world!\n";
}

class Test {
public:
    Test(std::string name):
        name_(name) {
    }

    std::string name() const {
        return name_;
    }

private:
    std::string name_;
};

extern "C" int init(lua_State* L)
{
    using namespace luabind;

    open(L);

    module(L)
    [
        def("greet", &greet),
        class_<Test>("Test")
            .def(constructor<std::string>())
            .def("name", &Test::name)
    ];

    return 0;
}

int main()
{
    lua_State* L = luaL_newstate();
    init(L);
    // hello world
    luaL_dostring(L, "greet()");
    // class
    luaL_dostring(L, "t = Test('123'); assert(t:name() == '123'");
    // iterate Lua table in C++
    luaL_dostring(L, "list123 = {1, 2, 3}");
    int sum = 0;
    lua_getglobal(L, "list123");
    luabind::object list123(luabind::from_stack(L, -1));
    lua_pop(L, 1);
    for (luabind::iterator it(list123), end; it != end; ++it) {
        luabind::object item = *it;
        sum += luabind::object_cast<int>(item);
    }
    assert(sum == 6);
}