forked from chronolaw/cpp_study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConfig.hpp
More file actions
74 lines (55 loc) · 1.49 KB
/
Config.hpp
File metadata and controls
74 lines (55 loc) · 1.49 KB
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
// Copyright (c) 2020 by Chrono
#ifndef _CONFIG_HPP
#define _CONFIG_HPP
#include "cpplang.hpp"
extern "C" {
#include <luajit.h>
#include <lualib.h>
#include <lauxlib.h>
}
#include <LuaBridge/LuaBridge.h>
BEGIN_NAMESPACE(cpp_study)
class Config final
{
public:
using vm_type = std::shared_ptr<lua_State>;
using value_type = luabridge::LuaRef;
using string_type = std::string;
using string_view_type = const std::string&;
using regex_type = std::regex;
using match_type = std::smatch;
public:
Config() noexcept
{
assert(m_vm);
luaL_openlibs(m_vm.get());
}
~Config() = default;
public:
void load(string_view_type filename) const
{
auto status = luaL_dofile(m_vm.get(), filename.c_str());
if (status != 0) {
throw std::runtime_error("failed to parse config");
}
}
template<typename T>
T get(string_view_type key) const
{
if (!std::regex_match(key, m_what, m_reg)) {
throw std::runtime_error("config key error");
}
auto w1 = m_what[1].str();
auto w2 = m_what[2].str();
using namespace luabridge;
auto v = getGlobal(
m_vm.get(), w1.c_str());
return LuaRef_cast<T>(v[w2]);
}
private:
vm_type m_vm {luaL_newstate(), lua_close};
const regex_type m_reg {R"(^(\w+)\.(\w+)$)"};
mutable match_type m_what;
};
END_NAMESPACE(cpp_study)
#endif //_CONFIG_HPP