Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/resource2/src/core/LuaState.cc @ 5655

Last change on this file since 5655 was 5655, checked in by rgrieder, 15 years ago

Added static DeclareToluaInterface macro to ease up tolua intefaces for modules.

  • Property svn:eol-style set to native
File size: 9.0 KB
RevLine 
[1959]1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
23 *      Benjamin Knecht
[5654]24 *      Reto Grieder
[1959]25 *   Co-authors:
26 *      ...
27 *
28 */
29
[5654]30#include "LuaState.h"
[1959]31
[5654]32#include <tolua/tolua++.h>
[2710]33extern "C" {
[5654]34#include <lua.h>
[2710]35#include <lualib.h>
36}
37
[3196]38#include "util/Debug.h"
[2710]39#include "Core.h"
[5654]40#include "Resource.h"
[5655]41#include "ToluaBindCore.h"
[1959]42
43namespace orxonox
44{
[5654]45    LuaState::ToluaInterfaceMap LuaState::toluaInterfaces_s;
46    std::vector<LuaState*> LuaState::instances_s;
[1959]47
[5655]48    // Do this after declaring toluaInterfaces_s and instances_s to avoid larger problems
49    DeclareToluaInterface(Core);
50
[5654]51    LuaState::LuaState()
52        : bIsRunning_(false)
53        , includeParseFunction_(NULL)
54    {
55        // Create new lua state and configure it
56        luaState_ = lua_open();
[1959]57#if LUA_VERSION_NUM == 501
[5654]58        luaL_openlibs(luaState_);
[1959]59#else
[5654]60        luaopen_base(luaState_);
61        luaopen_string(luaState_);
62        luaopen_table(luaState_);
63        luaopen_math(luaState_);
64        luaopen_io(luaState_);
65        luaopen_debug(luaState_);
[1959]66#endif
[3370]67
[5654]68        // Open all available tolua interfaces
69        this->openToluaInterfaces(luaState_);
[3370]70
[5654]71        // Create dummy file info
72        sourceFileInfo_.reset(new ResourceInfo());
73        sourceFileInfo_->group = "General";
74        sourceFileInfo_->size = 0;
[1959]75
[5654]76        // Push this pointer
77        tolua_pushusertype(luaState_, static_cast<void*>(this), "orxonox::LuaState");
78        lua_setglobal(luaState_, "luaState");
[3370]79
[5654]80        // Parse init script
81        // Note: We have to use a hard coded path because the script is required for the resource loading
82        this->doString("dofile(\"" + Core::getDataPathString() + "lua/LuaStateInit.lua\")");
83    }
[1959]84
[5654]85    LuaState::~LuaState()
86    {
87        lua_close(luaState_);
88    }
[2710]89
[5654]90    shared_ptr<ResourceInfo> LuaState::getFileInfo(const std::string& filename, const std::string& resourceGroup, bool bSearchOtherPaths)
91    {
92        shared_ptr<ResourceInfo> sourceInfo;
93        if (resourceGroup != "NoResourceGroupProvided")
94            sourceInfo = Resource::getInfo(filename, resourceGroup);
[1959]95
[5654]96        // Continue search if not explicitely forbidden
97        if (bSearchOtherPaths && sourceInfo == NULL)
98        {
99            // Call might be relative to the file currently being processed
100            sourceInfo = Resource::getInfo(sourceFileInfo_->path + filename, sourceFileInfo_->group);
101            if (sourceInfo == NULL)
102            {
103                // Maybe find something in the same group but in the root path
104                sourceInfo = Resource::getInfo(filename, sourceFileInfo_->group);
105            }
106        }
107        return sourceInfo;
108    }
109
110    void LuaState::includeFile(const std::string& filename, const std::string& resourceGroup, bool bSearchOtherPaths)
[1959]111    {
[5654]112        shared_ptr<ResourceInfo> sourceInfo = this->getFileInfo(filename, resourceGroup, bSearchOtherPaths);
113        if (sourceInfo != NULL)
114            this->includeString(Resource::open(sourceInfo->filename, sourceInfo->group)->getAsString(), sourceInfo);
115        else
116            COUT(2) << "LuaState: Cannot include file '" << filename << "' in resource group '"
117                    << (resourceGroup == "NoResourceGroupProvided" ? sourceFileInfo_->group : resourceGroup) << "': group not found." << std::endl;
[1959]118    }
119
[5654]120    void LuaState::includeString(const std::string& code, shared_ptr<ResourceInfo> sourceFileInfo)
121    {
122        // Parse string with provided include parser (otherwise don't preparse at all)
123        std::string luaInput;
124        if (includeParseFunction_ != NULL)
125            luaInput = (*includeParseFunction_)(code);
126        else
127            luaInput = code;
[1959]128
[5654]129        this->doString(luaInput, sourceFileInfo);
130    }
131
132    void LuaState::doFile(const std::string& filename, const std::string& resourceGroup, bool bSearchOtherPaths)
[1959]133    {
[5654]134        shared_ptr<ResourceInfo> sourceInfo = this->getFileInfo(filename, resourceGroup, bSearchOtherPaths);
135        if (sourceInfo != NULL)
136            this->doString(Resource::open(sourceInfo->filename, sourceInfo->group)->getAsString(), sourceInfo);
137        else
138            COUT(2) << "LuaState: Cannot do file '" << filename << "' in resource group '"
139                << (resourceGroup == "NoResourceGroupProvided" ? sourceFileInfo_->group : resourceGroup) << "': group not found." << std::endl;
[1959]140    }
141
[5654]142    void LuaState::doString(const std::string& code, shared_ptr<ResourceInfo> sourceFileInfo)
143    {
144        // Save the oold source file info
145        shared_ptr<ResourceInfo> oldSourceFileInfo = sourceFileInfo_;
146        // Only override if sourceFileInfo provides useful information
147        if (sourceFileInfo != NULL)
148            sourceFileInfo_ = sourceFileInfo;
[1959]149
[5654]150        //if (!bIsRunning_)
151        //{
152        //    bIsRunning_ = true;
[1959]153
[5654]154        int error = 0;
[1959]155#if LUA_VERSION_NUM != 501
[5654]156        LoadS ls;
157        ls.s = code.c_str();
158        ls.size = code.size();
159        error = lua_load(luaState_, &orxonox::LuaState::lua_Chunkreader, &ls, code.c_str());
160#else
161        error = luaL_loadstring(luaState_, code.c_str());
[1959]162#endif
[5654]163
164        // execute the chunk
165        if (error == 0)
166            error = lua_pcall(luaState_, 0, 0, 0);
167        if (error != 0)
168        {
169            std::string origin;
170            if (sourceFileInfo != NULL)
171                origin = " originating from " + sourceFileInfo_->filename;
172            COUT(2) << "Error in Lua-script" << origin << ": " << lua_tostring(luaState_, -1) << std::endl;
173        }
174
175        //    bIsRunning_ = false;
176        //}
177        //else
178        //{
179        //    COUT(2) << "Warning: LuaState do function called while running!" << std::endl;
180        //}
181
182        // Load the old info again
183        sourceFileInfo_ = oldSourceFileInfo;
[1959]184    }
[5654]185
186    void LuaState::luaPrint(const std::string& str)
[1959]187    {
[5654]188        output_ << str;
[1959]189    }
190
[5654]191    void LuaState::luaLog(unsigned int level, const std::string& message)
[1959]192    {
[5654]193        OutputHandler::getOutStream().setOutputLevel(level) << message << std::endl;
[1959]194    }
[5654]195
196#if LUA_VERSION_NUM != 501
197    const char * LuaState::lua_Chunkreader(lua_State *L, void *data, size_t *size)
[1959]198    {
[5654]199        LoadS* ls = static_cast<LoadS*>(data);
200        if (ls->size == 0)
201            return NULL;
202        *size = ls->size;
203        ls->size = 0;
204        return ls->s;
[1959]205    }
[5654]206#endif
[1959]207
[5654]208    /*static*/ bool LuaState::addToluaInterface(int (*function)(lua_State*), const std::string& name)
[1959]209    {
[5654]210        for (ToluaInterfaceMap::const_iterator it = toluaInterfaces_s.begin(); it != toluaInterfaces_s.end(); ++it)
[1959]211        {
[5654]212            if (it->first == name || it->second == function)
213            {
214                COUT(2) << "Warning: Trying to add a Tolua interface with the same name or function." << std::endl;
215                return true;
216            }
[1959]217        }
[5654]218        toluaInterfaces_s[name] = function;
219
220        // Open interface in all LuaStates
221        for (std::vector<LuaState*>::const_iterator it = instances_s.begin(); it != instances_s.end(); ++it)
222            (*function)((*it)->luaState_);
223
224        // Return dummy bool
225        return true;
[1959]226    }
227
[5654]228    /*static*/ bool LuaState::removeToluaInterface(const std::string& name)
[1959]229    {
[5654]230        ToluaInterfaceMap::iterator it = toluaInterfaces_s.find(name);
231        if (it == toluaInterfaces_s.end())
[1959]232        {
[5654]233            COUT(2) << "Warning: Cannot remove Tolua interface '" << name << "': Not found" << std::endl;
234            return true;
[1959]235        }
236
[5654]237        // Close interface in all LuaStates
238        for (std::vector<LuaState*>::const_iterator itState = instances_s.begin(); itState != instances_s.end(); ++itState)
[1959]239        {
[5654]240            lua_pushnil((*itState)->luaState_);
241            lua_setglobal((*itState)->luaState_, it->first.c_str());
[1959]242        }
243
[5654]244        // Remove entry
245        toluaInterfaces_s.erase(it);
246
247        // Return dummy bool
248        return true;
[1959]249    }
250
[5654]251    /*static*/ void LuaState::openToluaInterfaces(lua_State* state)
252    {
253        for (ToluaInterfaceMap::const_iterator it = toluaInterfaces_s.begin(); it != toluaInterfaces_s.end(); ++it)
254            (*it->second)(state);
255    }
[1959]256
[5654]257    /*static*/ void LuaState::closeToluaInterfaces(lua_State* state)
[3370]258    {
[5654]259        for (ToluaInterfaceMap::const_iterator it = toluaInterfaces_s.begin(); it != toluaInterfaces_s.end(); ++it)
260        {
261            lua_pushnil(state);
262            lua_setglobal(state, it->first.c_str());
263        }
[3370]264    }
[1959]265}
Note: See TracBrowser for help on using the repository browser.