Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: sandbox/src/libraries/core/LuaState.cc @ 6178

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

Synchronised sandbox with current code trunk. There should be a few bug fixes.

  • Property svn:eol-style set to native
File size: 9.2 KB
Line 
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
24 *      Reto Grieder
25 *   Co-authors:
26 *      ...
27 *
28 */
29
30#include "LuaState.h"
31
32#include <boost/filesystem.hpp>
33#include <tolua/tolua++.h>
34extern "C" {
35#include <lua.h>
36#include <lualib.h>
37}
38
39#include "util/Debug.h"
40#include "PathConfig.h"
41#include "ToluaBindCore.h"
42
43namespace orxonox
44{
45    LuaState::ToluaInterfaceMap LuaState::toluaInterfaces_s;
46    std::vector<LuaState*> LuaState::instances_s;
47
48    // Do this after declaring toluaInterfaces_s and instances_s to avoid larger problems
49    DeclareToluaInterface(Core);
50
51    LuaState::LuaState()
52        : bIsRunning_(false)
53        , includeParseFunction_(NULL)
54    {
55        // Create new lua state and configure it
56        luaState_ = lua_open();
57#if LUA_VERSION_NUM == 501
58        luaL_openlibs(luaState_);
59#else
60        luaopen_base(luaState_);
61        luaopen_string(luaState_);
62        luaopen_table(luaState_);
63        luaopen_math(luaState_);
64        luaopen_io(luaState_);
65        luaopen_debug(luaState_);
66#endif
67
68        // Open all available tolua interfaces
69        this->openToluaInterfaces(luaState_);
70
71        // Create dummy file info
72        sourceFileInfo_.reset(new ResourceInfo());
73
74        // Push 'this' pointer
75        tolua_pushusertype(luaState_, static_cast<void*>(this), "orxonox::LuaState");
76        lua_setglobal(luaState_, "luaState");
77
78        // Parse init script
79        this->doFile("LuaStateInit.lua");
80    }
81
82    LuaState::~LuaState()
83    {
84        lua_close(luaState_);
85    }
86
87    shared_ptr<ResourceInfo> LuaState::getFileInfo(const std::string& filename, bool bSearchOtherPaths)
88    {
89        shared_ptr<ResourceInfo> sourceInfo;
90        sourceInfo = this->getFileInfo(filename);
91
92        // Continue search if not explicitely forbidden
93        if (bSearchOtherPaths && sourceInfo == NULL)
94        {
95            // Call might be relative to the file currently being processed
96            sourceInfo = this->getFileInfo(sourceFileInfo_->path + filename);
97            if (sourceInfo == NULL)
98            {
99                // Maybe find something in the same group but in the root path
100                sourceInfo = this->getFileInfo(filename);
101            }
102        }
103        return sourceInfo;
104    }
105
106    shared_ptr<ResourceInfo> LuaState::getFileInfo(const std::string& filename)
107    {
108        boost::filesystem::path filepath = PathConfig::getDataPath() / "lua" / filename;
109        if (boost::filesystem::exists(filepath))
110        {
111            shared_ptr<ResourceInfo> info(new ResourceInfo());
112            info->filename = filepath.string();
113            info->path = filepath.branch_path().string();
114            info->basename = filepath.leaf();
115            return info;
116        }
117        else
118            return shared_ptr<ResourceInfo>();
119    }
120
121    std::string LuaState::loadFile(const std::string& filename)
122    {
123        std::ifstream file(filename.c_str());
124        std::ostringstream oss;
125        oss << file.rdbuf();
126        return oss.str();
127    }
128
129    void LuaState::includeFile(const std::string& filename, bool bSearchOtherPaths)
130    {
131        shared_ptr<ResourceInfo> sourceInfo = this->getFileInfo(filename, bSearchOtherPaths);
132        if (sourceInfo != NULL)
133            this->includeString(this->loadFile(sourceInfo->filename), sourceInfo);
134        else
135            COUT(2) << "LuaState: Cannot include file '" << filename << std::endl;
136    }
137
138    void LuaState::includeString(const std::string& code, shared_ptr<ResourceInfo> sourceFileInfo)
139    {
140        // Parse string with provided include parser (otherwise don't preparse at all)
141        std::string luaInput;
142        if (includeParseFunction_ != NULL)
143            luaInput = (*includeParseFunction_)(code);
144        else
145            luaInput = code;
146
147        this->doString(luaInput, sourceFileInfo);
148    }
149
150    void LuaState::doFile(const std::string& filename, bool bSearchOtherPaths)
151    {
152        shared_ptr<ResourceInfo> sourceInfo = this->getFileInfo(filename, bSearchOtherPaths);
153        if (sourceInfo != NULL)
154            this->doString(this->loadFile(sourceInfo->filename), sourceInfo);
155        else
156            COUT(2) << "LuaState: Cannot do file '" << filename << std::endl;
157    }
158
159    void LuaState::doString(const std::string& code, shared_ptr<ResourceInfo> sourceFileInfo)
160    {
161        // Save the oold source file info
162        shared_ptr<ResourceInfo> oldSourceFileInfo = sourceFileInfo_;
163        // Only override if sourceFileInfo provides useful information
164        if (sourceFileInfo != NULL)
165            sourceFileInfo_ = sourceFileInfo;
166
167        int error = 0;
168#if LUA_VERSION_NUM != 501
169        LoadS ls;
170        ls.s = code.c_str();
171        ls.size = code.size();
172        error = lua_load(luaState_, &orxonox::LuaState::lua_Chunkreader, &ls, code.c_str());
173#else
174        error = luaL_loadstring(luaState_, code.c_str());
175#endif
176
177        // execute the chunk
178        if (error == 0)
179            error = lua_pcall(luaState_, 0, 1, 0);
180        if (error != 0)
181        {
182            std::string origin;
183            if (sourceFileInfo != NULL)
184                origin = " originating from " + sourceFileInfo_->filename;
185            COUT(2) << "Error in Lua-script" << origin << ": " << lua_tostring(luaState_, -1) << std::endl;
186            // return value is nil
187            lua_pushnil(luaState_);
188        }
189        // push return value because it will get lost since the return value of this function is void
190        lua_setglobal(luaState_, "LuaStateReturnValue");
191
192        // Load the old info again
193        sourceFileInfo_ = oldSourceFileInfo;
194    }
195
196    void LuaState::luaPrint(const std::string& str)
197    {
198        output_ << str;
199    }
200
201    void LuaState::luaLog(unsigned int level, const std::string& message)
202    {
203        OutputHandler::getOutStream().setOutputLevel(level) << message << std::endl;
204    }
205
206    bool LuaState::fileExists(const std::string& filename, bool bSearchOtherPaths)
207    {
208        shared_ptr<ResourceInfo> info =  this->getFileInfo(filename, bSearchOtherPaths);
209        if (info == NULL)
210            return false;
211        else
212            return true;
213    }
214
215#if LUA_VERSION_NUM != 501
216    const char * LuaState::lua_Chunkreader(lua_State *L, void *data, size_t *size)
217    {
218        LoadS* ls = static_cast<LoadS*>(data);
219        if (ls->size == 0)
220            return NULL;
221        *size = ls->size;
222        ls->size = 0;
223        return ls->s;
224    }
225#endif
226
227    /*static*/ bool LuaState::addToluaInterface(int (*function)(lua_State*), const std::string& name)
228    {
229        for (ToluaInterfaceMap::const_iterator it = toluaInterfaces_s.begin(); it != toluaInterfaces_s.end(); ++it)
230        {
231            if (it->first == name || it->second == function)
232            {
233                COUT(2) << "Warning: Trying to add a Tolua interface with the same name or function." << std::endl;
234                return true;
235            }
236        }
237        toluaInterfaces_s[name] = function;
238
239        // Open interface in all LuaStates
240        for (std::vector<LuaState*>::const_iterator it = instances_s.begin(); it != instances_s.end(); ++it)
241            (*function)((*it)->luaState_);
242
243        // Return dummy bool
244        return true;
245    }
246
247    /*static*/ bool LuaState::removeToluaInterface(const std::string& name)
248    {
249        ToluaInterfaceMap::iterator it = toluaInterfaces_s.find(name);
250        if (it == toluaInterfaces_s.end())
251        {
252            COUT(2) << "Warning: Cannot remove Tolua interface '" << name << "': Not found" << std::endl;
253            return true;
254        }
255
256        // Close interface in all LuaStates
257        for (std::vector<LuaState*>::const_iterator itState = instances_s.begin(); itState != instances_s.end(); ++itState)
258        {
259            lua_pushnil((*itState)->luaState_);
260            lua_setglobal((*itState)->luaState_, it->first.c_str());
261        }
262
263        // Remove entry
264        toluaInterfaces_s.erase(it);
265
266        // Return dummy bool
267        return true;
268    }
269
270    /*static*/ void LuaState::openToluaInterfaces(lua_State* state)
271    {
272        for (ToluaInterfaceMap::const_iterator it = toluaInterfaces_s.begin(); it != toluaInterfaces_s.end(); ++it)
273            (*it->second)(state);
274    }
275
276    /*static*/ void LuaState::closeToluaInterfaces(lua_State* state)
277    {
278        for (ToluaInterfaceMap::const_iterator it = toluaInterfaces_s.begin(); it != toluaInterfaces_s.end(); ++it)
279        {
280            lua_pushnil(state);
281            lua_setglobal(state, it->first.c_str());
282        }
283    }
284}
Note: See TracBrowser for help on using the repository browser.