Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'pikachuyann/simgrid-stoprofiles'
[simgrid.git] / src / bindings / lua / lua_utils.cpp
1 /* Copyright (c) 2010-2020. The SimGrid Team.
2  * All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or modify it
5  * under the terms of the license (GNU LGPL) which comes with this package. */
6
7 /*
8  * This file contains functions that aid users to debug their lua scripts; for instance,
9  * tables can be easily output and values are represented in a human-readable way. (For instance,
10  * a nullptr value becomes the string "nil").
11  *
12  */
13 /* SimGrid Lua helper functions                                             */
14 #include "lua_utils.hpp"
15 #include <lauxlib.h>
16 #include <string>
17 #include <xbt/string.hpp>
18
19 /**
20  * @brief Returns a string representation of a value in the Lua stack.
21  *
22  * This function is for debugging purposes.
23  *
24  * @param L the Lua state
25  * @param index index in the stack
26  * @return a string representation of the value at this index
27  */
28 std::string sglua_tostring(lua_State* L, int index)
29 {
30   std::string buff;
31
32   switch (lua_type(L, index)) {
33     case LUA_TNIL:
34       buff = "nil";
35       break;
36
37     case LUA_TNUMBER:
38       buff = simgrid::xbt::string_printf("%.3f", lua_tonumber(L, index));
39       break;
40
41     case LUA_TBOOLEAN:
42       buff = lua_toboolean(L, index) ? "true" : "false";
43       break;
44
45     case LUA_TSTRING:
46       buff = simgrid::xbt::string_printf("'%s'", lua_tostring(L, index));
47       break;
48
49     case LUA_TFUNCTION:
50       buff = lua_iscfunction(L, index) ? "C-function" : "function";
51       break;
52
53     case LUA_TTABLE:
54       buff = simgrid::xbt::string_printf("table(%p)", lua_topointer(L, index));
55       break;
56
57     case LUA_TLIGHTUSERDATA:
58     case LUA_TUSERDATA:
59       buff = simgrid::xbt::string_printf("userdata(%p)", lua_touserdata(L, index));
60       break;
61
62     case LUA_TTHREAD:
63       buff = "thread";
64       break;
65
66     default:
67       buff = simgrid::xbt::string_printf("unknown(%d)", lua_type(L, index));
68       break;
69   }
70   return buff;
71 }
72
73 /**
74  * @brief Returns a string representation of a key-value pair.
75  *
76  * @param L the Lua state
77  * @param key_index index of the key (in the lua stack)
78  * @param value_index index of the value (in the lua stack)
79  * @return a string representation of the key-value pair
80  */
81 std::string sglua_keyvalue_tostring(lua_State* L, int key_index, int value_index)
82 {
83   return std::string("[") + sglua_tostring(L, key_index) + "] -> " + sglua_tostring(L, value_index);
84 }