Refactor Lua support
[lsnes.git] / src / lua / core.cpp
blobc8f3ac22176608894155209501c6d5d42d4eb5fb
1 #include "core/command.hpp"
2 #include "core/emucore.hpp"
3 #include "lua/internal.hpp"
4 #include "core/framerate.hpp"
5 #include "core/window.hpp"
7 namespace
9 function_ptr_luafun lua_print(LS, "print", [](lua_state& L, const std::string& fname) -> int {
10 int stacksize = 0;
11 while(!L.isnone(stacksize + 1))
12 stacksize++;
13 std::string toprint;
14 bool first = true;
15 for(int i = 0; i < stacksize; i++) {
16 size_t len;
17 const char* tmp = NULL;
18 if(L.isnil(i + 1)) {
19 tmp = "nil";
20 len = 3;
21 } else if(L.isboolean(i + 1) && L.toboolean(i + 1)) {
22 tmp = "true";
23 len = 4;
24 } else if(L.isboolean(i + 1) && !L.toboolean(i + 1)) {
25 tmp = "false";
26 len = 5;
27 } else {
28 tmp = L.tolstring(i + 1, &len);
29 if(!tmp) {
30 tmp = "(unprintable)";
31 len = 13;
34 std::string localmsg(tmp, tmp + len);
35 if(first)
36 toprint = localmsg;
37 else
38 toprint = toprint + "\t" + localmsg;
39 first = false;
41 platform::message(toprint);
42 return 0;
43 });
45 function_ptr_luafun lua_exec(LS, "exec", [](lua_state& L, const std::string& fname) -> int {
46 std::string text = L.get_string(1, fname.c_str());
47 lsnes_cmd.invoke(text);
48 return 0;
49 });
51 function_ptr_luafun lua_booted(LS, "emulator_ready", [](lua_state& L, const std::string& fname) -> int {
52 L.pushboolean(lua_booted_flag ? 1 : 0);
53 return 1;
54 });
56 function_ptr_luafun lua_utime(LS, "utime", [](lua_state& L, const std::string& fname) -> int {
57 uint64_t t = get_utime();
58 L.pushnumber(t / 1000000);
59 L.pushnumber(t % 1000000);
60 return 2;
61 });
63 function_ptr_luafun lua_idle_time(LS, "set_idle_timeout", [](lua_state& L, const std::string& fname) -> int {
64 lua_idle_hook_time = get_utime() + L.get_numeric_argument<uint64_t>(1, fname.c_str());
65 return 0;
66 });
68 function_ptr_luafun lua_timer_time(LS, "set_timer_timeout", [](lua_state& L, const std::string& fname) ->
69 int {
70 lua_timer_hook_time = get_utime() + L.get_numeric_argument<uint64_t>(1, fname.c_str());
71 return 0;
72 });
74 function_ptr_luafun lua_busaddr(LS, "bus_address", [](lua_state& L, const std::string& fname) -> int {
75 uint64_t addr = L.get_numeric_argument<uint64_t>(1, fname.c_str());
76 auto busrange = core_get_bus_map();
77 if(!busrange.second) {
78 L.pushstring("This platform does not have bus mapping");
79 L.error();
80 return 0;
82 L.pushnumber(busrange.first + (addr % busrange.second));
83 return 1;
84 });