aboutsummaryrefslogtreecommitdiff
path: root/src/LuaRuntime.cpp
blob: d89f7dc7f62c2cc1b47ed29499d09411ca85bfdd (plain) (blame)
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
#include <QtCore>
#include <lua.hpp>
extern "C" {
#include <luv.h>
}

#include "LuaRuntime.hpp"

LuaRuntime::LuaRuntime() {
  state = luaL_newstate();
  luaL_openlibs(state);

  // Load `uv` (luv)
  luaopen_luv(state);
  lua_setglobal(state, "uv");

  // Load `web`
  luaL_Reg weblib[] = {
      {"open", &LuaRuntime::lua_onUrlOpen},
      {"tabopen", &LuaRuntime::lua_onUrlTabOpen},
      {NULL, NULL},
  };
  luaL_newlib(state, weblib);
  lua_setglobal(state, "web");

  // auto pp = R"(
  // print('Hello -- ');
  // local h = uv.fs_open('foobar', 'w', tonumber('644', 8), function(err, h)
  //  assert(not err, err);
  //  print('inside');
  //  print(h);
  //  print(err);
  //  uv.fs_write(h, 'Hello world');
  // end);
  // print(h);
  // uv.run();
  // print('-- end');
  // )";
  // auto pp = R"(
  // print('Hello -- ');
  // local t = uv.new_timer();
  // uv.timer_start(t, 4000, 0, function()
  //   print('after time')
  // end);
  // uv.run();
  // print('-- end');
  // )";
  // if (luaL_dostring(state, pp)) {
  //   qDebug() << "Lua Error: " << lua_tostring(state, -1);
  // } else {
  //   qDebug() << "succ";
  // }
}

void LuaRuntime::evaluate(QString code) {
  luaL_dostring(state, code.toStdString().c_str());
}

int LuaRuntime::lua_onUrlOpen(lua_State *state) {
  const char *url = luaL_optstring(state, 1, "");
  auto runtime = LuaRuntime::instance();
  emit runtime->urlOpened(url, OpenType::OpenUrl);
  return 1;
}

int LuaRuntime::lua_onUrlTabOpen(lua_State *state) {
  const char *url = luaL_optstring(state, 1, "");
  auto runtime = LuaRuntime::instance();
  emit runtime->urlOpened(url, OpenType::OpenUrlInTab);
  return 1;
}

LuaRuntime::~LuaRuntime() { lua_close(state); }