source: trunk/src/shared/impl/lua_func_wrapper.cpp

Last change on this file was 405, checked in by stephen, 12 months ago

update release date & copyright years.

File size: 2.3 KB
Line 
1/*
2 * lua_func_wrapper.cpp
3 *
4 * This file is part of Knights.
5 *
6 * Copyright (C) Stephen Thompson, 2006 - 2013.
7 * Copyright (C) Kalle Marjola, 1994.
8 *
9 * Knights is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation, either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * Knights is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with Knights.  If not, see <http://www.gnu.org/licenses/>.
21 *
22 */
23
24#include "misc.hpp"
25
26#include "lua_func_wrapper.hpp"
27
28#include "boost/thread/mutex.hpp"
29#include "boost/thread/locks.hpp"
30
31// definition copied from ldo.c
32struct lua_longjmp {
33  struct lua_longjmp *previous;
34  int b;
35  volatile int status;  /* error code */
36};
37
38namespace {
39
40    boost::mutex g_wrapper_mutex;
41    std::map<int, lua_CFunction> g_func_map;
42    int g_next_index;
43   
44    int LuaWrapperFunc(lua_State *lua)
45    {
46        int i = lua_tointeger(lua, lua_upvalueindex(1));
47       
48        lua_CFunction func;
49        {
50            boost::unique_lock<boost::mutex> lock(g_wrapper_mutex);
51            func = g_func_map[i];
52        }
53
54        try {
55            return func(lua);
56
57        } catch (lua_longjmp *) {
58            // This is a Lua error. Lua knows how to deal with this so
59            // we can re-throw it w/o problems.
60            throw; 
61           
62        } catch (const std::exception &e) {
63            // Convert this to a Lua error.
64            return luaL_error(lua, e.what());
65
66        } catch (...) {
67            // Convert this to a Lua error.
68            return luaL_error(lua, "Unknown C++ exception");
69        }
70    }
71}
72
73void PushCClosure(lua_State *lua, lua_CFunction func, int nupvalues)
74{
75    int i;  // initialized below
76    {
77        boost::unique_lock<boost::mutex> lock(g_wrapper_mutex);
78        i = g_next_index++;
79        g_func_map[i] = func;
80    }
81   
82    lua_pushinteger(lua, i);
83    lua_insert(lua, -nupvalues - 1);
84
85    lua_pushcclosure(lua, &LuaWrapperFunc, nupvalues + 1);
86}
Note: See TracBrowser for help on using the repository browser.