summaryrefslogtreecommitdiff
path: root/lib/BLua.cc
blob: 286857e3db7e1208573de8a857de3be5b4546ac3 (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
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
#include "BLua.h"

#ifndef LUAL_BUFFERSIZE
#define LUAL_BUFFERSIZE	  BUFSIZ
#endif

class LuaStatics : public Base {
  public:
    static const char * getF(lua_State *, void *, size_t *);
};

std::map<lua_State *, Lua *> Lua::lualist;

Lua::Lua() : L(lua_open()) {
    // error setting ? **TODO**
    lualist[L] = this;
}

Lua::Lua(lua_State * _L) : L(_L) {
    // error setting ? **TODO**
    lualist[L] = this;
}

Lua::~Lua() {
    lua_close(L);
}

Lua::Lua(const Lua & l) throw (GeneralException) {
    throw GeneralException("Error: can't duplicate a Lua object.");
}

void Lua::push() {
    lua_pushnil(L);
}

void Lua::push(double n) {
    lua_pushnumber(L, n);
}

void Lua::push(const String & s) {
    lua_pushlstring(L, s.to_charp(), s.strlen());
}

void Lua::push(bool b) {
    lua_pushboolean(L, b);
}

void Lua::push(void * p) {
    lua_pushlightuserdata(L, p);
}

void Lua::push(lua_CFunction f, int n) {
    lua_pushcclosure(L, f, n);
}

struct LoadF {
    Handle * f;
    char buff[LUAL_BUFFERSIZE];
};

const char * LuaStatics::getF(lua_State * L, void * ud, size_t * size) {
    LoadF *lf = (LoadF *)ud;
    (void)L;

    *size = lf->f->read(lf->buff, LUAL_BUFFERSIZE);
    return (*size > 0) ? lf->buff : NULL;
}

void Lua::load(Handle * h) throw (GeneralException) {
    LoadF lf;
    int status;

    lf.f = h;

    status = lua_load(L, LuaStatics::getF, &lf, h->GetName().to_charp());

    if (status) {
	// displaying error **TODO**
	throw GeneralException("Error loading lua chunk `" + h->GetName() + "'");
    }
}

Lua * Lua::thread() {
    return new Lua(lua_newthread(L));
}

Lua * Lua::find(lua_State * _L) {
    return lualist.find(_L)->second;
}