/
lua.cpp
75 lines (62 loc) · 1.83 KB
/
lua.cpp
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
#include "lua.hpp"
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#include <iostream>
namespace mojavy {
Lua::Lua() {
mL = lua_open();
}
Lua::~Lua() {
lua_close(mL);
}
int Lua::init() {
luaL_openlibs(mL);
return luaL_dostring(mL,
"function echo(x)\n"
" return x\n"
"end\n"
"function invert(x)\n"
" local r = {}\n"
" for k, v in pairs(x) do\n"
// " print(k, v)\n"
" r[v] = k\n"
" end\n"
" return x\n"
"end\n"
);
}
std::string Lua::name() const {
return "lua";
}
std::string Lua::echo(const std::string &s) const {
lua_getglobal(mL, "echo");
lua_pushlstring(mL, s.c_str(), s.size());
if (lua_pcall(mL, 1, 1, 0) != 0) {
luaL_error(mL, "failed to call echo: %s", lua_tostring(mL, -1));
}
std::string res(lua_tostring(mL, -1));
lua_pop(mL, 1);
return res;
}
std::map<std::string, std::string> Lua::invert(const std::map<std::string, std::string> &lis) const {
std::map<std::string, std::string> res;
lua_getglobal(mL, "invert");
lua_newtable(mL);
for (auto it = lis.begin(); it != lis.end(); ++it) {
lua_pushlstring(mL, it->first.c_str(), it->first.size());
lua_pushlstring(mL, it->second.c_str(), it->second.size());
lua_settable(mL, -3);
}
if (lua_pcall(mL, 1, 1, 0) != 0) {
luaL_error(mL, "failed to call invert: %s", lua_tostring(mL, -1));
}
lua_pushnil(mL);
while (lua_next(mL, 1) != 0) {
res[lua_tostring(mL, -1)] = lua_tostring(mL, -2);
lua_pop(mL, 1);
}
lua_pop(mL, 1);
return res;
}
}