-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlua_interpreter.hxx
98 lines (73 loc) · 2.45 KB
/
lua_interpreter.hxx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#pragma once
#include <memory>
#include <stdexcept>
#include <string>
#include <tuple>
namespace luai {
class luastate_error : public std::runtime_error {
using std::runtime_error::runtime_error;
};
enum class types {
INT, NUM, STR, BOOL, TABLE,
NIL, OTHER, LTYPE
};
class table_handle;
// all possible types one can get from state.get_global(), get_field() and get_index()
template<types Type>
using get_var_t =
std::conditional_t<Type == types::INT, long long,
std::conditional_t<Type == types::NUM, double,
std::conditional_t<Type == types::STR, std::string,
std::conditional_t<Type == types::BOOL, bool,
std::conditional_t<Type == types::TABLE, table_handle,
std::conditional_t<Type == types::LTYPE, types,
/*unsupported types*/ luastate_error
>>>>>>;
class lua_interpreter {
public:
static const int lua_version;
// opens a new lua state
lua_interpreter();
// MOVE
lua_interpreter(lua_interpreter &&) noexcept;
lua_interpreter &operator=(lua_interpreter &&) noexcept;
// COPYING DELETED
// returns whether executing waas successful PLUS error message
std::tuple<bool, std::string> run_chunk(const char *code) noexcept;
// opens all standard libraries
void openlibs() noexcept;
// get a global variable
template<types Type>
get_var_t<Type> get_global(const char *varname);
private:
struct impl;
std::shared_ptr<impl> pimpl;
friend class table_handle;
};
// RAII managed lua table getter
// when this object is alive, the top of the lua stack is always the table.
// when this object is destroyed, the top of the stack is popped
class table_handle {
public:
// get a field from the current table
template<types Type>
get_var_t<Type> get_field(const char *varname);
// get a field using int index from the current array
template<types Type>
get_var_t<Type> get_index(long long idx);
// get the length of current array. DOES NOT make sense if array contains holes
// or if __len() metamethod does not return int
long long len();
// MOVE
table_handle(table_handle &&) noexcept;
table_handle &operator=(table_handle &&) noexcept;
// COPYING DELETED
// must be called immediately after using table_handle
//~table_handle();
private:
struct impl;
std::shared_ptr<impl> pimpl;
table_handle(std::shared_ptr<lua_interpreter::impl>, std::shared_ptr<impl>);
friend class lua_interpreter;
};
} // namespace luai