runtime.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  1. /**
  2. * Copyright (c) 2006-2015 LOVE Development Team
  3. *
  4. * This software is provided 'as-is', without any express or implied
  5. * warranty. In no event will the authors be held liable for any damages
  6. * arising from the use of this software.
  7. *
  8. * Permission is granted to anyone to use this software for any purpose,
  9. * including commercial applications, and to alter it and redistribute it
  10. * freely, subject to the following restrictions:
  11. *
  12. * 1. The origin of this software must not be misrepresented; you must not
  13. * claim that you wrote the original software. If you use this software
  14. * in a product, an acknowledgment in the product documentation would be
  15. * appreciated but is not required.
  16. * 2. Altered source versions must be plainly marked as such, and must not be
  17. * misrepresented as being the original software.
  18. * 3. This notice may not be removed or altered from any source distribution.
  19. **/
  20. #include "config.h"
  21. #include "runtime.h"
  22. // LOVE
  23. #include "Module.h"
  24. #include "Object.h"
  25. #include "Reference.h"
  26. #include "StringMap.h"
  27. // C++
  28. #include <algorithm>
  29. #include <iostream>
  30. #include <cstdio>
  31. namespace love
  32. {
  33. /**
  34. * Called when an object is collected. The object is released
  35. * once in this function, possibly deleting it.
  36. **/
  37. static int w__gc(lua_State *L)
  38. {
  39. Proxy *p = (Proxy *) lua_touserdata(L, 1);
  40. p->object->release();
  41. return 0;
  42. }
  43. static int w__tostring(lua_State *L)
  44. {
  45. lua_pushvalue(L, lua_upvalueindex(1));
  46. return 1;
  47. }
  48. static int w__typeOf(lua_State *L)
  49. {
  50. Proxy *p = (Proxy *)lua_touserdata(L, 1);
  51. Type t = luax_type(L, 2);
  52. luax_pushboolean(L, typeFlags[p->type][t]);
  53. return 1;
  54. }
  55. static int w__eq(lua_State *L)
  56. {
  57. Proxy *p1 = (Proxy *)lua_touserdata(L, 1);
  58. Proxy *p2 = (Proxy *)lua_touserdata(L, 2);
  59. luax_pushboolean(L, p1->object == p2->object);
  60. return 1;
  61. }
  62. Reference *luax_refif(lua_State *L, int type)
  63. {
  64. Reference *r = nullptr;
  65. // Create a reference only if the test succeeds.
  66. if (lua_type(L, -1) == type)
  67. r = new Reference(L);
  68. else // Pop the value even if it fails (but also if it succeeds).
  69. lua_pop(L, 1);
  70. return r;
  71. }
  72. void luax_printstack(lua_State *L)
  73. {
  74. for (int i = 1; i <= lua_gettop(L); i++)
  75. std::cout << i << " - " << luaL_typename(L, i) << std::endl;
  76. }
  77. bool luax_toboolean(lua_State *L, int idx)
  78. {
  79. return (lua_toboolean(L, idx) != 0);
  80. }
  81. void luax_pushboolean(lua_State *L, bool b)
  82. {
  83. lua_pushboolean(L, b ? 1 : 0);
  84. }
  85. bool luax_optboolean(lua_State *L, int idx, bool b)
  86. {
  87. if (lua_isboolean(L, idx) == 1)
  88. return (lua_toboolean(L, idx) == 1 ? true : false);
  89. return b;
  90. }
  91. std::string luax_tostring(lua_State *L, int idx)
  92. {
  93. size_t len;
  94. const char *str = lua_tolstring(L, idx, &len);
  95. return std::string(str, len);
  96. }
  97. std::string luax_checkstring(lua_State *L, int idx)
  98. {
  99. size_t len;
  100. const char *str = luaL_checklstring(L, idx, &len);
  101. return std::string(str, len);
  102. }
  103. void luax_pushstring(lua_State *L, const std::string &str)
  104. {
  105. lua_pushlstring(L, str.data(), str.size());
  106. }
  107. bool luax_boolflag(lua_State *L, int table_index, const char *key, bool defaultValue)
  108. {
  109. lua_getfield(L, table_index, key);
  110. bool retval;
  111. if (lua_isnoneornil(L, -1))
  112. retval = defaultValue;
  113. else
  114. retval = lua_toboolean(L, -1) != 0;
  115. lua_pop(L, 1);
  116. return retval;
  117. }
  118. int luax_intflag(lua_State *L, int table_index, const char *key, int defaultValue)
  119. {
  120. lua_getfield(L, table_index, key);
  121. int retval;
  122. if (!lua_isnumber(L, -1))
  123. retval = defaultValue;
  124. else
  125. retval = (int) lua_tointeger(L, -1);
  126. lua_pop(L, 1);
  127. return retval;
  128. }
  129. int luax_assert_argc(lua_State *L, int min)
  130. {
  131. int argc = lua_gettop(L);
  132. if (argc < min)
  133. return luaL_error(L, "Incorrect number of arguments. Got [%d], expected at least [%d]", argc, min);
  134. return 0;
  135. }
  136. int luax_assert_argc(lua_State *L, int min, int max)
  137. {
  138. int argc = lua_gettop(L);
  139. if (argc < min || argc > max)
  140. return luaL_error(L, "Incorrect number of arguments. Got [%d], expected [%d-%d]", argc, min, max);
  141. return 0;
  142. }
  143. int luax_assert_function(lua_State *L, int idx)
  144. {
  145. if (!lua_isfunction(L, idx))
  146. return luaL_error(L, "Argument must be of type \"function\".");
  147. return 0;
  148. }
  149. int luax_assert_nilerror(lua_State *L, int idx)
  150. {
  151. if (lua_isnoneornil(L, idx))
  152. {
  153. if (lua_isstring(L, idx + 1))
  154. return luaL_error(L, lua_tostring(L, idx + 1));
  155. else
  156. return luaL_error(L, "assertion failed!");
  157. }
  158. return 0;
  159. }
  160. void luax_setfuncs(lua_State *L, const luaL_Reg *l)
  161. {
  162. if (l == nullptr)
  163. return;
  164. for (; l->name != nullptr; l++)
  165. {
  166. lua_pushcfunction(L, l->func);
  167. lua_setfield(L, -2, l->name);
  168. }
  169. }
  170. int luax_require(lua_State *L, const char *name)
  171. {
  172. lua_getglobal(L, "require");
  173. lua_pushstring(L, name);
  174. lua_call(L, 1, 1);
  175. return 1;
  176. }
  177. int luax_register_module(lua_State *L, const WrappedModule &m)
  178. {
  179. // Put a reference to the C++ module in Lua.
  180. luax_insistregistry(L, REGISTRY_MODULES);
  181. Proxy *p = (Proxy *)lua_newuserdata(L, sizeof(Proxy));
  182. p->object = m.module;
  183. p->type = m.type;
  184. luaL_newmetatable(L, m.module->getName());
  185. lua_pushvalue(L, -1);
  186. lua_setfield(L, -2, "__index");
  187. lua_pushcfunction(L, w__gc);
  188. lua_setfield(L, -2, "__gc");
  189. lua_setmetatable(L, -2);
  190. lua_setfield(L, -2, m.name); // _modules[name] = proxy
  191. lua_pop(L, 1);
  192. // Gets the love table.
  193. luax_insistglobal(L, "love");
  194. // Create new table for module.
  195. lua_newtable(L);
  196. // Register all the functions.
  197. if (m.functions != nullptr)
  198. luax_setfuncs(L, m.functions);
  199. // Register types.
  200. if (m.types != nullptr)
  201. {
  202. for (const lua_CFunction *t = m.types; *t != nullptr; t++)
  203. (*t)(L);
  204. }
  205. lua_pushvalue(L, -1);
  206. lua_setfield(L, -3, m.name); // love.graphics = table
  207. lua_remove(L, -2); // love
  208. // Register module instance
  209. Module::registerInstance(m.module);
  210. return 1;
  211. }
  212. int luax_preload(lua_State *L, lua_CFunction f, const char *name)
  213. {
  214. lua_getglobal(L, "package");
  215. lua_getfield(L, -1, "preload");
  216. lua_pushcfunction(L, f);
  217. lua_setfield(L, -2, name);
  218. lua_pop(L, 2);
  219. return 0;
  220. }
  221. int luax_register_type(lua_State *L, love::Type type, const luaL_Reg *f, bool pushmetatable)
  222. {
  223. // Verify that this type name has a matching Type ID and type name mapping.
  224. const char *tname = "Invalid";
  225. if (!love::getType(type, tname))
  226. printf("Missing type name entry for type ID %d\n", type);
  227. // Get the place for storing and re-using instantiated love types.
  228. luax_getregistry(L, REGISTRY_OBJECTS);
  229. // Create registry._loveobjects if it doesn't exist yet.
  230. if (!lua_istable(L, -1))
  231. {
  232. lua_newtable(L);
  233. lua_replace(L, -2);
  234. // Create a metatable.
  235. lua_newtable(L);
  236. // metatable.__mode = "v". Weak userdata values.
  237. lua_pushliteral(L, "v");
  238. lua_setfield(L, -2, "__mode");
  239. // setmetatable(newtable, metatable)
  240. lua_setmetatable(L, -2);
  241. // registry._loveobjects = newtable
  242. lua_setfield(L, LUA_REGISTRYINDEX, "_loveobjects");
  243. }
  244. else
  245. lua_pop(L, 1);
  246. luaL_newmetatable(L, tname);
  247. // m.__index = m
  248. lua_pushvalue(L, -1);
  249. lua_setfield(L, -2, "__index");
  250. // setup gc
  251. lua_pushcfunction(L, w__gc);
  252. lua_setfield(L, -2, "__gc");
  253. // Add equality
  254. lua_pushcfunction(L, w__eq);
  255. lua_setfield(L, -2, "__eq");
  256. // Add tostring function.
  257. lua_pushstring(L, tname);
  258. lua_pushcclosure(L, w__tostring, 1);
  259. lua_setfield(L, -2, "__tostring");
  260. // Add tostring to as type() as well.
  261. lua_pushstring(L, tname);
  262. lua_pushcclosure(L, w__tostring, 1);
  263. lua_setfield(L, -2, "type");
  264. // Add typeOf
  265. lua_pushcfunction(L, w__typeOf);
  266. lua_setfield(L, -2, "typeOf");
  267. if (f != nullptr)
  268. luax_setfuncs(L, f);
  269. if (pushmetatable)
  270. return 1; // leave the metatable on the stack.
  271. lua_pop(L, 1); // Pops metatable.
  272. return 0;
  273. }
  274. int luax_table_insert(lua_State *L, int tindex, int vindex, int pos)
  275. {
  276. if (tindex < 0)
  277. tindex = lua_gettop(L)+1+tindex;
  278. if (vindex < 0)
  279. vindex = lua_gettop(L)+1+vindex;
  280. if (pos == -1)
  281. {
  282. lua_pushvalue(L, vindex);
  283. lua_rawseti(L, tindex, (int) luax_objlen(L, tindex)+1);
  284. return 0;
  285. }
  286. else if (pos < 0)
  287. pos = (int) luax_objlen(L, tindex)+1+pos;
  288. for (int i = (int) luax_objlen(L, tindex)+1; i > pos; i--)
  289. {
  290. lua_rawgeti(L, tindex, i-1);
  291. lua_rawseti(L, tindex, i);
  292. }
  293. lua_pushvalue(L, vindex);
  294. lua_rawseti(L, tindex, pos);
  295. return 0;
  296. }
  297. int luax_register_searcher(lua_State *L, lua_CFunction f, int pos)
  298. {
  299. // Add the package loader to the package.loaders table.
  300. lua_getglobal(L, "package");
  301. if (lua_isnil(L, -1))
  302. return luaL_error(L, "Can't register searcher: package table does not exist.");
  303. lua_getfield(L, -1, "loaders");
  304. // Lua 5.2 renamed package.loaders to package.searchers.
  305. if (lua_isnil(L, -1))
  306. {
  307. lua_pop(L, 1);
  308. lua_getfield(L, -1, "searchers");
  309. }
  310. if (lua_isnil(L, -1))
  311. return luaL_error(L, "Can't register searcher: package.loaders table does not exist.");
  312. lua_pushcfunction(L, f);
  313. luax_table_insert(L, -2, -1, pos);
  314. lua_pop(L, 3);
  315. return 0;
  316. }
  317. void luax_rawnewtype(lua_State *L, love::Type type, love::Object *object)
  318. {
  319. Proxy *u = (Proxy *)lua_newuserdata(L, sizeof(Proxy));
  320. object->retain();
  321. u->object = object;
  322. u->type = type;
  323. const char *name = "Invalid";
  324. getType(type, name);
  325. luaL_newmetatable(L, name);
  326. lua_setmetatable(L, -2);
  327. }
  328. void luax_pushtype(lua_State *L, love::Type type, love::Object *object)
  329. {
  330. if (object == nullptr)
  331. {
  332. lua_pushnil(L);
  333. return;
  334. }
  335. // Fetch the registry table of instantiated objects.
  336. luax_getregistry(L, REGISTRY_OBJECTS);
  337. // The table might not exist - it should be insisted in luax_register_type.
  338. if (!lua_istable(L, -1))
  339. {
  340. lua_pop(L, 1);
  341. return luax_rawnewtype(L, type, object);
  342. }
  343. // Get the value of loveobjects[object] on the stack.
  344. lua_pushlightuserdata(L, object);
  345. lua_gettable(L, -2);
  346. // If the Proxy userdata isn't in the instantiated types table yet, add it.
  347. if (lua_type(L, -1) != LUA_TUSERDATA)
  348. {
  349. lua_pop(L, 1);
  350. luax_rawnewtype(L, type, object);
  351. lua_pushlightuserdata(L, object);
  352. lua_pushvalue(L, -2);
  353. // loveobjects[object] = Proxy.
  354. lua_settable(L, -4);
  355. }
  356. // Remove the loveobjects table from the stack.
  357. lua_remove(L, -2);
  358. // Keep the Proxy userdata on the stack.
  359. }
  360. bool luax_istype(lua_State *L, int idx, love::Type type)
  361. {
  362. if (lua_type(L, idx) != LUA_TUSERDATA)
  363. return false;
  364. Proxy *p = (Proxy *) lua_touserdata(L, idx);
  365. return typeFlags[p->type][type];
  366. }
  367. int luax_getfunction(lua_State *L, const char *mod, const char *fn)
  368. {
  369. lua_getglobal(L, "love");
  370. if (lua_isnil(L, -1)) return luaL_error(L, "Could not find global love!");
  371. lua_getfield(L, -1, mod);
  372. if (lua_isnil(L, -1)) return luaL_error(L, "Could not find love.%s!", mod);
  373. lua_getfield(L, -1, fn);
  374. if (lua_isnil(L, -1)) return luaL_error(L, "Could not find love.%s.%s!", mod, fn);
  375. lua_remove(L, -2); // remove mod
  376. lua_remove(L, -2); // remove fn
  377. return 0;
  378. }
  379. int luax_convobj(lua_State *L, int idx, const char *mod, const char *fn)
  380. {
  381. // Convert to absolute index if necessary.
  382. if (idx < 0 && idx > LUA_REGISTRYINDEX)
  383. idx += lua_gettop(L) + 1;
  384. // Convert string to a file.
  385. luax_getfunction(L, mod, fn);
  386. lua_pushvalue(L, idx); // The initial argument.
  387. lua_call(L, 1, 2); // Call the function, one arg, one return value (plus optional errstring.)
  388. luax_assert_nilerror(L, -2); // Make sure the function returned something.
  389. lua_pop(L, 1); // Pop the second return value now that we don't need it.
  390. lua_replace(L, idx); // Replace the initial argument with the new object.
  391. return 0;
  392. }
  393. int luax_convobj(lua_State *L, int idxs[], int n, const char *mod, const char *fn)
  394. {
  395. luax_getfunction(L, mod, fn);
  396. for (int i = 0; i < n; i++)
  397. {
  398. lua_pushvalue(L, idxs[i]); // The arguments.
  399. }
  400. lua_call(L, n, 2); // Call the function, n args, one return value (plus optional errstring.)
  401. luax_assert_nilerror(L, -2); // Make sure the function returned something.
  402. lua_pop(L, 1); // Pop the second return value now that we don't need it.
  403. if (n > 0)
  404. lua_replace(L, idxs[0]); // Replace the initial argument with the new object.
  405. return 0;
  406. }
  407. int luax_pconvobj(lua_State *L, int idx, const char *mod, const char *fn)
  408. {
  409. // Convert string to a file.
  410. luax_getfunction(L, mod, fn);
  411. lua_pushvalue(L, idx); // The initial argument.
  412. int ret = lua_pcall(L, 1, 1, 0); // Call the function, one arg, one return value.
  413. if (ret == 0)
  414. lua_replace(L, idx); // Replace the initial argument with the new object.
  415. return ret;
  416. }
  417. int luax_pconvobj(lua_State *L, int idxs[], int n, const char *mod, const char *fn)
  418. {
  419. luax_getfunction(L, mod, fn);
  420. for (int i = 0; i < n; i++)
  421. {
  422. lua_pushvalue(L, idxs[i]); // The arguments.
  423. }
  424. int ret = lua_pcall(L, n, 1, 0); // Call the function, n args, one return value.
  425. if (ret == 0)
  426. lua_replace(L, idxs[0]); // Replace the initial argument with the new object.
  427. return ret;
  428. }
  429. int luax_insist(lua_State *L, int idx, const char *k)
  430. {
  431. // Convert to absolute index if necessary.
  432. if (idx < 0 && idx > LUA_REGISTRYINDEX)
  433. idx += lua_gettop(L) + 1;
  434. lua_getfield(L, idx, k);
  435. // Create if necessary.
  436. if (!lua_istable(L, -1))
  437. {
  438. lua_pop(L, 1); // Pop the non-table.
  439. lua_newtable(L);
  440. lua_pushvalue(L, -1); // Duplicate the table to leave on top.
  441. lua_setfield(L, idx, k); // lua_stack[idx][k] = lua_stack[-1] (table)
  442. }
  443. return 1;
  444. }
  445. int luax_insistglobal(lua_State *L, const char *k)
  446. {
  447. lua_getglobal(L, k);
  448. if (!lua_istable(L, -1))
  449. {
  450. lua_pop(L, 1); // Pop the non-table.
  451. lua_newtable(L);
  452. lua_pushvalue(L, -1);
  453. lua_setglobal(L, k);
  454. }
  455. return 1;
  456. }
  457. int luax_c_insistglobal(lua_State *L, const char *k)
  458. {
  459. return luax_insistglobal(L, k);
  460. }
  461. int luax_insistlove(lua_State *L, const char *k)
  462. {
  463. luax_insistglobal(L, "love");
  464. luax_insist(L, -1, k);
  465. // The love table should be replaced with the top stack
  466. // item. Only the reqested table should remain on the stack.
  467. lua_replace(L, -2);
  468. return 1;
  469. }
  470. int luax_getlove(lua_State *L, const char *k)
  471. {
  472. lua_getglobal(L, "love");
  473. if (!lua_isnil(L, -1))
  474. {
  475. lua_getfield(L, -1, k);
  476. lua_replace(L, -2);
  477. }
  478. return 1;
  479. }
  480. int luax_insistregistry(lua_State *L, Registry r)
  481. {
  482. switch (r)
  483. {
  484. case REGISTRY_MODULES:
  485. return luax_insistlove(L, "_modules");
  486. case REGISTRY_OBJECTS:
  487. return luax_insist(L, LUA_REGISTRYINDEX, "_loveobjects");
  488. default:
  489. return luaL_error(L, "Attempted to use invalid registry.");
  490. }
  491. }
  492. int luax_getregistry(lua_State *L, Registry r)
  493. {
  494. switch (r)
  495. {
  496. case REGISTRY_MODULES:
  497. return luax_getlove(L, "_modules");
  498. case REGISTRY_OBJECTS:
  499. lua_getfield(L, LUA_REGISTRYINDEX, "_loveobjects");
  500. return 1;
  501. default:
  502. return luaL_error(L, "Attempted to use invalid registry.");
  503. }
  504. }
  505. static const char *MAIN_THREAD_KEY = "_love_mainthread";
  506. lua_State *luax_insistpinnedthread(lua_State *L)
  507. {
  508. lua_getfield(L, LUA_REGISTRYINDEX, MAIN_THREAD_KEY);
  509. if (lua_isnoneornil(L, -1))
  510. {
  511. lua_pop(L, 1);
  512. // lua_pushthread returns 1 if it's actually the main thread, but we
  513. // can't actually get the real main thread if lua_pushthread doesn't
  514. // return it (in Lua 5.1 at least), so we ignore that for now...
  515. // We do store a strong reference to the current thread/coroutine in
  516. // the registry, however.
  517. lua_pushthread(L);
  518. lua_pushvalue(L, -1);
  519. lua_setfield(L, LUA_REGISTRYINDEX, MAIN_THREAD_KEY);
  520. }
  521. lua_State *thread = lua_tothread(L, -1);
  522. lua_pop(L, 1);
  523. return thread;
  524. }
  525. lua_State *luax_getpinnedthread(lua_State *L)
  526. {
  527. lua_getfield(L, LUA_REGISTRYINDEX, MAIN_THREAD_KEY);
  528. lua_State *thread = lua_tothread(L, -1);
  529. lua_pop(L, 1);
  530. return thread;
  531. }
  532. extern "C" int luax_typerror(lua_State *L, int narg, const char *tname)
  533. {
  534. int argtype = lua_type(L, narg);
  535. const char *argtname = 0;
  536. // We want to use the love type name for userdata, if possible.
  537. if (argtype == LUA_TUSERDATA && luaL_getmetafield(L, narg, "__tostring") != 0)
  538. {
  539. lua_pushvalue(L, narg);
  540. if (lua_pcall(L, 1, 1, 0) == 0 && lua_type(L, -1) == LUA_TSTRING)
  541. {
  542. argtname = lua_tostring(L, -1);
  543. // Non-love userdata might have a tostring metamethod which doesn't
  544. // describe its type, so we only use __tostring for love types.
  545. love::Type t;
  546. if (!love::getType(argtname, t))
  547. argtname = 0;
  548. }
  549. }
  550. if (argtname == 0)
  551. argtname = lua_typename(L, argtype);
  552. const char *msg = lua_pushfstring(L, "%s expected, got %s", tname, argtname);
  553. return luaL_argerror(L, narg, msg);
  554. }
  555. size_t luax_objlen(lua_State *L, int ndx)
  556. {
  557. #if LUA_VERSION_NUM == 501
  558. return lua_objlen(L, ndx);
  559. #else
  560. return lua_rawlen(L, ndx);
  561. #endif
  562. }
  563. void luax_register(lua_State *L, const char *name, const luaL_Reg *l)
  564. {
  565. if (name)
  566. lua_newtable(L);
  567. luax_setfuncs(L, l);
  568. if (name)
  569. {
  570. lua_pushvalue(L, -1);
  571. lua_setglobal(L, name);
  572. }
  573. }
  574. Type luax_type(lua_State *L, int idx)
  575. {
  576. Type t = INVALID_ID;
  577. getType(luaL_checkstring(L, idx), t);
  578. return t;
  579. }
  580. } // love