luavmstate.cpp 1.65 KB
Newer Older
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
#include "luavmstate.h"

#include <iostream>
#include "globalluatable.h"

extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}


namespace campvis {

    LuaVmState::LuaVmState(bool loadStdLibs /*= true*/) : _luaState(0)
    {
        _luaState = luaL_newstate();

        // load standard Lua libraries
        if (loadStdLibs)
            luaL_openlibs(_luaState);
    }

    LuaVmState::~LuaVmState() {
        lua_close(_luaState);
    }

    void LuaVmState::logLuaError() {
        const char* errorMsg = lua_tostring(_luaState, -1);

        if (errorMsg == nullptr)
            std::cerr << "(error object is not a string)" << std::endl;
        else
            std::cerr << errorMsg << std::endl;

        lua_pop(_luaState, 1);
    }

    bool LuaVmState::execFile(const std::string& scriptPath) {
        // run a Lua script here; true is returned if there were errors
        if (luaL_dofile(_luaState, scriptPath.c_str())) {
            this->logLuaError();
            return false;
        }

        return true;
    }

    bool LuaVmState::execString(const std::string& scriptString) {
        if (luaL_dostring(_luaState, scriptString.c_str())) {
            this->logLuaError();
            return false;
        }

        return true;
    }

    std::shared_ptr<GlobalLuaTable> LuaVmState::getGlobalTable() {
        return std::shared_ptr<GlobalLuaTable>(new GlobalLuaTable(*this));
    }

    lua_State *LuaVmState::rawState() const {
        return _luaState;
    }

    void LuaVmState::callLuaFunc(int nargs, int nresults) {
        if (lua_pcall(_luaState, nargs, nresults, 0) != LUA_OK) {
            this->logLuaError();
        }
    }
}