Types.cc
1 /*
2  * MoMEMta: a modular implementation of the Matrix Element Method
3  * Copyright (C) 2016 Universite catholique de Louvain (UCL), Belgium
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 #include <lua/bindings/Types.h>
20 
21 #include <ExecutionPath.h>
22 
23 #include <lua/bindings/Path.h>
24 #include <lua.hpp>
25 
26 void push_type_metatable(lua_State* L, const char* name) {
27  // Register metatable
28  luaL_newmetatable(L, name);
29 
30  // Add '__type_' field
31  lua_pushstring(L, name);
32  lua_setfield(L, -2, "__type");
33 }
34 
35 std::string get_custom_type_name(lua_State* L, int index) {
36  if (lua_getmetatable(L, index)) {
37  lua_getfield(L, -1, "__type");
38  const char* type = lua_tostring(L, -1);
39  lua_pop(L, 2);
40 
41  return type;
42  }
43 
44  luaL_error(L, "No metatable associated with index %d", index);
45  return "";
46 }
47 
48 momemta::any get_custom_type_ptr(lua_State* L, int index) {
49  std::string type = get_custom_type_name(L, index);
50 
51  momemta::any result;
52  if (type == LUA_PATH_TYPE_NAME) {
53  auto path = *lua::path_get(L, index);
54  result = path;
55  }
56 
57  if (result.empty()) {
58  luaL_error(L, "Invalid userdata type: %s", type.c_str());
59  }
60 
61  return result;
62 }
Lua binding of C++ Path class.
ExecutionPath * path_get(lua_State *L, int index)
Retrieve an instance of Path from the lua stack.
Definition: Path.cc:83
void push_type_metatable(lua_State *L, const char *name)
Push a new metatable on the stack.
Definition: Types.cc:26
Generic functions to deal with custom lua types.
momemta::any get_custom_type_ptr(lua_State *L, int index)
Convert a lua custom table to a momemta::any value.
Definition: Types.cc:48
std::string get_custom_type_name(lua_State *L, int index)
Get the type of a custom table.
Definition: Types.cc:35