luavmstate.cpp 2.51 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include "luavmstate.h"

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

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


namespace campvis {

15
16
17
    LuaVmState::LuaVmState(bool loadStdLibs /*= true*/)
        : _luaState(0)
        , _luaStateMutex()
18
19
20
21
22
23
    {
        _luaState = luaL_newstate();

        // load standard Lua libraries
        if (loadStdLibs)
            luaL_openlibs(_luaState);
24
25
26
27
28
29
30
31
32

        /*
         * Store a pointer to the mutex guarding access to _luaState in the state's registry; this
         * way code that accesses Lua state directly (e.g. connections between sigslot's signals and
         * slots defined in Lua) has access to it and can lock it when necessary.
         */
        lua_pushlightuserdata(_luaState, static_cast<void*>(_luaState));
        lua_pushlightuserdata(_luaState, static_cast<void*>(&_luaStateMutex));
        lua_settable(_luaState, LUA_REGISTRYINDEX);
33
34
35
    }

    LuaVmState::~LuaVmState() {
36
        LuaStateMutexType::scoped_lock lock(_luaStateMutex);
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
        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) {
52
53
        LuaStateMutexType::scoped_lock lock(_luaStateMutex);

54
55
56
57
58
59
60
61
62
63
        // 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) {
64
65
        LuaStateMutexType::scoped_lock lock(_luaStateMutex);

66
67
68
69
70
71
72
73
74
75
76
77
        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));
    }

78
    lua_State* LuaVmState::rawState() const {
79
80
81
        return _luaState;
    }

82
83
84
85
    LuaStateMutexType& LuaVmState::getMutex() {
        return _luaStateMutex;
    }

86
    void LuaVmState::callLuaFunc(int nargs, int nresults) {
87
88
        LuaStateMutexType::scoped_lock lock(_luaStateMutex);

89
90
91
92
93
        if (lua_pcall(_luaState, nargs, nresults, 0) != LUA_OK) {
            this->logLuaError();
        }
    }
}