runtime.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  1. /**
  2. * Copyright (c) 2006-2019 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. #include <cstddef>
  32. #include <cmath>
  33. #include <sstream>
  34. // VS2013 doesn't support alignof
  35. #if defined(_MSC_VER) && _MSC_VER <= 1800
  36. #define LOVE_ALIGNOF(x) __alignof(x)
  37. #else
  38. #define LOVE_ALIGNOF(x) alignof(x)
  39. #endif
  40. namespace love
  41. {
  42. /**
  43. * Called when an object is collected. The object is released
  44. * once in this function, possibly deleting it.
  45. **/
  46. static int w__gc(lua_State *L)
  47. {
  48. Proxy *p = (Proxy *) lua_touserdata(L, 1);
  49. if (p->object != nullptr)
  50. {
  51. p->object->release();
  52. p->object = nullptr;
  53. }
  54. return 0;
  55. }
  56. static int w__tostring(lua_State *L)
  57. {
  58. Proxy *p = (Proxy *) lua_touserdata(L, 1);
  59. const char *typname = lua_tostring(L, lua_upvalueindex(1));
  60. lua_pushfstring(L, "%s: %p", typname, p->object);
  61. return 1;
  62. }
  63. static int w__type(lua_State *L)
  64. {
  65. lua_pushvalue(L, lua_upvalueindex(1));
  66. return 1;
  67. }
  68. static int w__typeOf(lua_State *L)
  69. {
  70. Proxy *p = (Proxy *)lua_touserdata(L, 1);
  71. Type *t = luax_type(L, 2);
  72. if (!t)
  73. luax_pushboolean(L, false);
  74. else
  75. luax_pushboolean(L, p->type->isa(*t));
  76. return 1;
  77. }
  78. static int w__eq(lua_State *L)
  79. {
  80. Proxy *p1 = (Proxy *)lua_touserdata(L, 1);
  81. Proxy *p2 = (Proxy *)lua_touserdata(L, 2);
  82. luax_pushboolean(L, p1->object == p2->object && p1->object != nullptr);
  83. return 1;
  84. }
  85. // For use with the love object pointer -> Proxy pointer registry.
  86. // Using the pointer directly via lightuserdata would be ideal, but LuaJIT
  87. // cannot use lightuserdata with more than 47 bits whereas some newer arm64
  88. // architectures allow pointers which use more than that.
  89. static lua_Number luax_computeloveobjectkey(lua_State *L, love::Object *object)
  90. {
  91. // love objects should be allocated on the heap, and thus are subject
  92. // to the alignment rules of operator new / malloc. Lua numbers (doubles)
  93. // can store all possible integers up to 2^53. We can store pointers that
  94. // use more than 53 bits if their alignment is guaranteed to be more than 1.
  95. // For example an alignment requirement of 8 means we can shift the
  96. // pointer's bits by 3.
  97. const size_t minalign = LOVE_ALIGNOF(std::max_align_t);
  98. uintptr_t key = (uintptr_t) object;
  99. if ((key & (minalign - 1)) != 0)
  100. {
  101. luaL_error(L, "Cannot push love object to Lua: unexpected alignment "
  102. "(pointer is %p but alignment should be %d)", object, minalign);
  103. }
  104. static const size_t shift = (size_t) log2(LOVE_ALIGNOF(std::max_align_t));
  105. key >>= shift;
  106. // Make sure our key isn't larger than 2^53.
  107. if (key > 0x20000000000000ULL)
  108. luaL_error(L, "Cannot push love object to Lua: pointer value %p is too large", object);
  109. return (lua_Number) key;
  110. }
  111. static int w__release(lua_State *L)
  112. {
  113. Proxy *p = (Proxy *) lua_touserdata(L, 1);
  114. Object *object = p->object;
  115. if (object != nullptr)
  116. {
  117. p->object = nullptr;
  118. object->release();
  119. // Fetch the registry table of instantiated objects.
  120. luax_getregistry(L, REGISTRY_OBJECTS);
  121. if (lua_istable(L, -1))
  122. {
  123. // loveobjects[object] = nil
  124. lua_Number objectkey = luax_computeloveobjectkey(L, object);
  125. lua_pushnumber(L, objectkey);
  126. lua_pushnil(L);
  127. lua_settable(L, -3);
  128. }
  129. lua_pop(L, 1);
  130. }
  131. luax_pushboolean(L, object != nullptr);
  132. return 1;
  133. }
  134. Reference *luax_refif(lua_State *L, int type)
  135. {
  136. Reference *r = nullptr;
  137. // Create a reference only if the test succeeds.
  138. if (lua_type(L, -1) == type)
  139. r = new Reference(L);
  140. else // Pop the value manually if it fails (done by Reference if it succeeds).
  141. lua_pop(L, 1);
  142. return r;
  143. }
  144. void luax_printstack(lua_State *L)
  145. {
  146. for (int i = 1; i <= lua_gettop(L); i++)
  147. std::cout << i << " - " << luaL_typename(L, i) << std::endl;
  148. }
  149. int luax_traceback(lua_State *L)
  150. {
  151. if (!lua_isstring(L, 1)) // 'message' not a string?
  152. return 1; // keep it intact
  153. lua_getglobal(L, "debug");
  154. if (!lua_istable(L, -1))
  155. {
  156. lua_pop(L, 1);
  157. return 1;
  158. }
  159. lua_getfield(L, -1, "traceback");
  160. if (!lua_isfunction(L, -1))
  161. {
  162. lua_pop(L, 2);
  163. return 1;
  164. }
  165. lua_pushvalue(L, 1); // pass error message
  166. lua_pushinteger(L, 2); // skip this function and traceback
  167. lua_call(L, 2, 1); // call debug.traceback
  168. return 1;
  169. }
  170. bool luax_isarrayoftables(lua_State *L, int idx)
  171. {
  172. if (!lua_istable(L, idx))
  173. return false;
  174. lua_rawgeti(L, idx, 1);
  175. bool tableoftables = lua_istable(L, -1);
  176. lua_pop(L, 1);
  177. return tableoftables;
  178. }
  179. bool luax_toboolean(lua_State *L, int idx)
  180. {
  181. return (lua_toboolean(L, idx) != 0);
  182. }
  183. bool luax_checkboolean(lua_State *L, int idx)
  184. {
  185. luaL_checktype(L, idx, LUA_TBOOLEAN);
  186. return luax_toboolean(L, idx);
  187. }
  188. void luax_pushboolean(lua_State *L, bool b)
  189. {
  190. lua_pushboolean(L, b ? 1 : 0);
  191. }
  192. bool luax_optboolean(lua_State *L, int idx, bool b)
  193. {
  194. if (lua_isboolean(L, idx) == 1)
  195. return (lua_toboolean(L, idx) == 1 ? true : false);
  196. return b;
  197. }
  198. std::string luax_tostring(lua_State *L, int idx)
  199. {
  200. size_t len;
  201. const char *str = lua_tolstring(L, idx, &len);
  202. return std::string(str, len);
  203. }
  204. std::string luax_checkstring(lua_State *L, int idx)
  205. {
  206. size_t len;
  207. const char *str = luaL_checklstring(L, idx, &len);
  208. return std::string(str, len);
  209. }
  210. void luax_pushstring(lua_State *L, const std::string &str)
  211. {
  212. lua_pushlstring(L, str.data(), str.size());
  213. }
  214. void luax_pushpointerasstring(lua_State *L, const void *pointer)
  215. {
  216. char str[sizeof(void *)];
  217. memcpy(str, &pointer, sizeof(void *));
  218. lua_pushlstring(L, str, sizeof(void *));
  219. }
  220. bool luax_boolflag(lua_State *L, int table_index, const char *key, bool defaultValue)
  221. {
  222. lua_getfield(L, table_index, key);
  223. bool retval;
  224. if (lua_isnoneornil(L, -1))
  225. retval = defaultValue;
  226. else
  227. retval = lua_toboolean(L, -1) != 0;
  228. lua_pop(L, 1);
  229. return retval;
  230. }
  231. int luax_intflag(lua_State *L, int table_index, const char *key, int defaultValue)
  232. {
  233. lua_getfield(L, table_index, key);
  234. int retval;
  235. if (!lua_isnumber(L, -1))
  236. retval = defaultValue;
  237. else
  238. retval = (int) lua_tointeger(L, -1);
  239. lua_pop(L, 1);
  240. return retval;
  241. }
  242. double luax_numberflag(lua_State *L, int table_index, const char *key, double defaultValue)
  243. {
  244. lua_getfield(L, table_index, key);
  245. double retval;
  246. if (!lua_isnumber(L, -1))
  247. retval = defaultValue;
  248. else
  249. retval = lua_tonumber(L, -1);
  250. lua_pop(L, 1);
  251. return retval;
  252. }
  253. int luax_checkintflag(lua_State *L, int table_index, const char *key)
  254. {
  255. lua_getfield(L, table_index, key);
  256. int retval;
  257. if (!lua_isnumber(L, -1))
  258. {
  259. std::string err = "expected integer field " + std::string(key) + " in table";
  260. return luaL_argerror(L, table_index, err.c_str());
  261. }
  262. else
  263. retval = (int) luaL_checkinteger(L, -1);
  264. lua_pop(L, 1);
  265. return retval;
  266. }
  267. int luax_assert_argc(lua_State *L, int min)
  268. {
  269. int argc = lua_gettop(L);
  270. if (argc < min)
  271. return luaL_error(L, "Incorrect number of arguments. Got [%d], expected at least [%d]", argc, min);
  272. return 0;
  273. }
  274. int luax_assert_argc(lua_State *L, int min, int max)
  275. {
  276. int argc = lua_gettop(L);
  277. if (argc < min || argc > max)
  278. return luaL_error(L, "Incorrect number of arguments. Got [%d], expected [%d-%d]", argc, min, max);
  279. return 0;
  280. }
  281. int luax_assert_function(lua_State *L, int idx)
  282. {
  283. if (!lua_isfunction(L, idx))
  284. return luaL_error(L, "Argument must be of type \"function\".");
  285. return 0;
  286. }
  287. int luax_assert_nilerror(lua_State *L, int idx)
  288. {
  289. if (lua_isnoneornil(L, idx))
  290. {
  291. if (lua_isstring(L, idx + 1))
  292. return luaL_error(L, lua_tostring(L, idx + 1));
  293. else
  294. return luaL_error(L, "assertion failed!");
  295. }
  296. return 0;
  297. }
  298. void luax_setfuncs(lua_State *L, const luaL_Reg *l)
  299. {
  300. if (l == nullptr)
  301. return;
  302. for (; l->name != nullptr; l++)
  303. {
  304. lua_pushcfunction(L, l->func);
  305. lua_setfield(L, -2, l->name);
  306. }
  307. }
  308. int luax_require(lua_State *L, const char *name)
  309. {
  310. lua_getglobal(L, "require");
  311. lua_pushstring(L, name);
  312. lua_call(L, 1, 1);
  313. return 1;
  314. }
  315. int luax_register_module(lua_State *L, const WrappedModule &m)
  316. {
  317. m.type->init();
  318. // Put a reference to the C++ module in Lua.
  319. luax_insistregistry(L, REGISTRY_MODULES);
  320. Proxy *p = (Proxy *)lua_newuserdata(L, sizeof(Proxy));
  321. p->object = m.module;
  322. p->type = m.type;
  323. luaL_newmetatable(L, m.module->getName());
  324. lua_pushvalue(L, -1);
  325. lua_setfield(L, -2, "__index");
  326. lua_pushcfunction(L, w__gc);
  327. lua_setfield(L, -2, "__gc");
  328. lua_setmetatable(L, -2);
  329. lua_setfield(L, -2, m.name); // _modules[name] = proxy
  330. lua_pop(L, 1);
  331. // Gets the love table.
  332. luax_insistglobal(L, "love");
  333. // Create new table for module.
  334. lua_newtable(L);
  335. // Register all the functions.
  336. if (m.functions != nullptr)
  337. luax_setfuncs(L, m.functions);
  338. // Register types.
  339. if (m.types != nullptr)
  340. {
  341. for (const lua_CFunction *t = m.types; *t != nullptr; t++)
  342. (*t)(L);
  343. }
  344. lua_pushvalue(L, -1);
  345. lua_setfield(L, -3, m.name); // love.graphics = table
  346. lua_remove(L, -2); // love
  347. // Register module instance
  348. Module::registerInstance(m.module);
  349. return 1;
  350. }
  351. int luax_preload(lua_State *L, lua_CFunction f, const char *name)
  352. {
  353. lua_getglobal(L, "package");
  354. lua_getfield(L, -1, "preload");
  355. lua_pushcfunction(L, f);
  356. lua_setfield(L, -2, name);
  357. lua_pop(L, 2);
  358. return 0;
  359. }
  360. int luax_register_type(lua_State *L, love::Type *type, ...)
  361. {
  362. type->init();
  363. // Get the place for storing and re-using instantiated love types.
  364. luax_getregistry(L, REGISTRY_OBJECTS);
  365. // Create registry._loveobjects if it doesn't exist yet.
  366. if (!lua_istable(L, -1))
  367. {
  368. lua_newtable(L);
  369. lua_replace(L, -2);
  370. // Create a metatable.
  371. lua_newtable(L);
  372. // metatable.__mode = "v". Weak userdata values.
  373. lua_pushliteral(L, "v");
  374. lua_setfield(L, -2, "__mode");
  375. // setmetatable(newtable, metatable)
  376. lua_setmetatable(L, -2);
  377. // registry._loveobjects = newtable
  378. lua_setfield(L, LUA_REGISTRYINDEX, "_loveobjects");
  379. }
  380. else
  381. lua_pop(L, 1);
  382. luaL_newmetatable(L, type->getName());
  383. // m.__index = m
  384. lua_pushvalue(L, -1);
  385. lua_setfield(L, -2, "__index");
  386. // setup gc
  387. lua_pushcfunction(L, w__gc);
  388. lua_setfield(L, -2, "__gc");
  389. // Add equality
  390. lua_pushcfunction(L, w__eq);
  391. lua_setfield(L, -2, "__eq");
  392. // Add tostring function.
  393. lua_pushstring(L, type->getName());
  394. lua_pushcclosure(L, w__tostring, 1);
  395. lua_setfield(L, -2, "__tostring");
  396. // Add type
  397. lua_pushstring(L, type->getName());
  398. lua_pushcclosure(L, w__type, 1);
  399. lua_setfield(L, -2, "type");
  400. // Add typeOf
  401. lua_pushcfunction(L, w__typeOf);
  402. lua_setfield(L, -2, "typeOf");
  403. // Add release
  404. lua_pushcfunction(L, w__release);
  405. lua_setfield(L, -2, "release");
  406. va_list fs;
  407. va_start(fs, type);
  408. for (const luaL_Reg *f = va_arg(fs, const luaL_Reg *); f; f = va_arg(fs, const luaL_Reg *))
  409. luax_setfuncs(L, f);
  410. va_end(fs);
  411. lua_pop(L, 1); // Pops metatable.
  412. return 0;
  413. }
  414. void luax_gettypemetatable(lua_State *L, const love::Type &type)
  415. {
  416. const char *name = type.getName();
  417. lua_getfield(L, LUA_REGISTRYINDEX, name);
  418. }
  419. int luax_table_insert(lua_State *L, int tindex, int vindex, int pos)
  420. {
  421. if (tindex < 0)
  422. tindex = lua_gettop(L)+1+tindex;
  423. if (vindex < 0)
  424. vindex = lua_gettop(L)+1+vindex;
  425. if (pos == -1)
  426. {
  427. lua_pushvalue(L, vindex);
  428. lua_rawseti(L, tindex, (int) luax_objlen(L, tindex)+1);
  429. return 0;
  430. }
  431. else if (pos < 0)
  432. pos = (int) luax_objlen(L, tindex)+1+pos;
  433. for (int i = (int) luax_objlen(L, tindex)+1; i > pos; i--)
  434. {
  435. lua_rawgeti(L, tindex, i-1);
  436. lua_rawseti(L, tindex, i);
  437. }
  438. lua_pushvalue(L, vindex);
  439. lua_rawseti(L, tindex, pos);
  440. return 0;
  441. }
  442. int luax_register_searcher(lua_State *L, lua_CFunction f, int pos)
  443. {
  444. // Add the package loader to the package.loaders table.
  445. lua_getglobal(L, "package");
  446. if (lua_isnil(L, -1))
  447. return luaL_error(L, "Can't register searcher: package table does not exist.");
  448. lua_getfield(L, -1, "loaders");
  449. // Lua 5.2 renamed package.loaders to package.searchers.
  450. if (lua_isnil(L, -1))
  451. {
  452. lua_pop(L, 1);
  453. lua_getfield(L, -1, "searchers");
  454. }
  455. if (lua_isnil(L, -1))
  456. return luaL_error(L, "Can't register searcher: package.loaders table does not exist.");
  457. lua_pushcfunction(L, f);
  458. luax_table_insert(L, -2, -1, pos);
  459. lua_pop(L, 3);
  460. return 0;
  461. }
  462. void luax_rawnewtype(lua_State *L, love::Type &type, love::Object *object)
  463. {
  464. Proxy *u = (Proxy *)lua_newuserdata(L, sizeof(Proxy));
  465. object->retain();
  466. u->object = object;
  467. u->type = &type;
  468. const char *name = type.getName();
  469. luaL_newmetatable(L, name);
  470. lua_getfield(L, -1, "__gc");
  471. bool has_gc = !lua_isnoneornil(L, -1);
  472. lua_pop(L, 1);
  473. // Make sure mt.__gc exists, so Lua states which don't have the object's
  474. // module loaded will still clean the object up when it's collected.
  475. if (!has_gc)
  476. {
  477. lua_pushcfunction(L, w__gc);
  478. lua_setfield(L, -2, "__gc");
  479. }
  480. lua_setmetatable(L, -2);
  481. }
  482. void luax_pushtype(lua_State *L, love::Type &type, love::Object *object)
  483. {
  484. if (object == nullptr)
  485. {
  486. lua_pushnil(L);
  487. return;
  488. }
  489. // Fetch the registry table of instantiated objects.
  490. luax_getregistry(L, REGISTRY_OBJECTS);
  491. // The table might not exist - it should be insisted in luax_register_type.
  492. if (lua_isnoneornil(L, -1))
  493. {
  494. lua_pop(L, 1);
  495. return luax_rawnewtype(L, type, object);
  496. }
  497. lua_Number objectkey = luax_computeloveobjectkey(L, object);
  498. // Get the value of loveobjects[object] on the stack.
  499. lua_pushnumber(L, objectkey);
  500. lua_gettable(L, -2);
  501. // If the Proxy userdata isn't in the instantiated types table yet, add it.
  502. if (lua_type(L, -1) != LUA_TUSERDATA)
  503. {
  504. lua_pop(L, 1);
  505. luax_rawnewtype(L, type, object);
  506. lua_pushnumber(L, objectkey);
  507. lua_pushvalue(L, -2);
  508. // loveobjects[object] = Proxy.
  509. lua_settable(L, -4);
  510. }
  511. // Remove the loveobjects table from the stack.
  512. lua_remove(L, -2);
  513. // Keep the Proxy userdata on the stack.
  514. }
  515. bool luax_istype(lua_State *L, int idx, love::Type &type)
  516. {
  517. if (lua_type(L, idx) != LUA_TUSERDATA)
  518. return false;
  519. Proxy *p = (Proxy *) lua_touserdata(L, idx);
  520. if (p->type != nullptr)
  521. return p->type->isa(type);
  522. else
  523. return false;
  524. }
  525. int luax_getfunction(lua_State *L, const char *mod, const char *fn)
  526. {
  527. lua_getglobal(L, "love");
  528. if (lua_isnil(L, -1)) return luaL_error(L, "Could not find global love!");
  529. lua_getfield(L, -1, mod);
  530. if (lua_isnil(L, -1)) return luaL_error(L, "Could not find love.%s!", mod);
  531. lua_getfield(L, -1, fn);
  532. if (lua_isnil(L, -1)) return luaL_error(L, "Could not find love.%s.%s!", mod, fn);
  533. lua_remove(L, -2); // remove mod
  534. lua_remove(L, -2); // remove fn
  535. return 0;
  536. }
  537. int luax_convobj(lua_State *L, int idx, const char *mod, const char *fn)
  538. {
  539. // Convert to absolute index if necessary.
  540. if (idx < 0 && idx > LUA_REGISTRYINDEX)
  541. idx += lua_gettop(L) + 1;
  542. // Convert string to a file.
  543. luax_getfunction(L, mod, fn);
  544. lua_pushvalue(L, idx); // The initial argument.
  545. lua_call(L, 1, 2); // Call the function, one arg, one return value (plus optional errstring.)
  546. luax_assert_nilerror(L, -2); // Make sure the function returned something.
  547. lua_pop(L, 1); // Pop the second return value now that we don't need it.
  548. lua_replace(L, idx); // Replace the initial argument with the new object.
  549. return 0;
  550. }
  551. int luax_convobj(lua_State *L, const int idxs[], int n, const char *mod, const char *fn)
  552. {
  553. luax_getfunction(L, mod, fn);
  554. for (int i = 0; i < n; i++)
  555. {
  556. lua_pushvalue(L, idxs[i]); // The arguments.
  557. }
  558. lua_call(L, n, 2); // Call the function, n args, one return value (plus optional errstring.)
  559. luax_assert_nilerror(L, -2); // Make sure the function returned something.
  560. lua_pop(L, 1); // Pop the second return value now that we don't need it.
  561. if (n > 0)
  562. lua_replace(L, idxs[0]); // Replace the initial argument with the new object.
  563. return 0;
  564. }
  565. int luax_convobj(lua_State *L, const std::vector<int>& idxs, const char *module, const char *function)
  566. {
  567. const int *idxPtr = idxs.size() > 0 ? &idxs[0] : nullptr;
  568. return luax_convobj(L, idxPtr, (int) idxs.size(), module, function);
  569. }
  570. int luax_pconvobj(lua_State *L, int idx, const char *mod, const char *fn)
  571. {
  572. // Convert string to a file.
  573. luax_getfunction(L, mod, fn);
  574. lua_pushvalue(L, idx); // The initial argument.
  575. int ret = lua_pcall(L, 1, 1, 0); // Call the function, one arg, one return value.
  576. if (ret == 0)
  577. lua_replace(L, idx); // Replace the initial argument with the new object.
  578. return ret;
  579. }
  580. int luax_pconvobj(lua_State *L, const int idxs[], int n, const char *mod, const char *fn)
  581. {
  582. luax_getfunction(L, mod, fn);
  583. for (int i = 0; i < n; i++)
  584. {
  585. lua_pushvalue(L, idxs[i]); // The arguments.
  586. }
  587. int ret = lua_pcall(L, n, 1, 0); // Call the function, n args, one return value.
  588. if (ret == 0)
  589. lua_replace(L, idxs[0]); // Replace the initial argument with the new object.
  590. return ret;
  591. }
  592. int luax_pconvobj(lua_State *L, const std::vector<int>& idxs, const char *module, const char *function)
  593. {
  594. const int *idxPtr = idxs.size() > 0 ? &idxs[0] : nullptr;
  595. return luax_pconvobj(L, idxPtr, (int) idxs.size(), module, function);
  596. }
  597. int luax_insist(lua_State *L, int idx, const char *k)
  598. {
  599. // Convert to absolute index if necessary.
  600. if (idx < 0 && idx > LUA_REGISTRYINDEX)
  601. idx += lua_gettop(L) + 1;
  602. lua_getfield(L, idx, k);
  603. // Create if necessary.
  604. if (!lua_istable(L, -1))
  605. {
  606. lua_pop(L, 1); // Pop the non-table.
  607. lua_newtable(L);
  608. lua_pushvalue(L, -1); // Duplicate the table to leave on top.
  609. lua_setfield(L, idx, k); // lua_stack[idx][k] = lua_stack[-1] (table)
  610. }
  611. return 1;
  612. }
  613. int luax_insistglobal(lua_State *L, const char *k)
  614. {
  615. lua_getglobal(L, k);
  616. if (!lua_istable(L, -1))
  617. {
  618. lua_pop(L, 1); // Pop the non-table.
  619. lua_newtable(L);
  620. lua_pushvalue(L, -1);
  621. lua_setglobal(L, k);
  622. }
  623. return 1;
  624. }
  625. int luax_c_insistglobal(lua_State *L, const char *k)
  626. {
  627. return luax_insistglobal(L, k);
  628. }
  629. int luax_insistlove(lua_State *L, const char *k)
  630. {
  631. luax_insistglobal(L, "love");
  632. luax_insist(L, -1, k);
  633. // The love table should be replaced with the top stack
  634. // item. Only the reqested table should remain on the stack.
  635. lua_replace(L, -2);
  636. return 1;
  637. }
  638. int luax_getlove(lua_State *L, const char *k)
  639. {
  640. lua_getglobal(L, "love");
  641. if (!lua_isnil(L, -1))
  642. {
  643. lua_getfield(L, -1, k);
  644. lua_replace(L, -2);
  645. }
  646. return 1;
  647. }
  648. int luax_insistregistry(lua_State *L, Registry r)
  649. {
  650. switch (r)
  651. {
  652. case REGISTRY_MODULES:
  653. return luax_insistlove(L, "_modules");
  654. case REGISTRY_OBJECTS:
  655. return luax_insist(L, LUA_REGISTRYINDEX, "_loveobjects");
  656. default:
  657. return luaL_error(L, "Attempted to use invalid registry.");
  658. }
  659. }
  660. int luax_getregistry(lua_State *L, Registry r)
  661. {
  662. switch (r)
  663. {
  664. case REGISTRY_MODULES:
  665. return luax_getlove(L, "_modules");
  666. case REGISTRY_OBJECTS:
  667. lua_getfield(L, LUA_REGISTRYINDEX, "_loveobjects");
  668. return 1;
  669. default:
  670. return luaL_error(L, "Attempted to use invalid registry.");
  671. }
  672. }
  673. static const char *MAIN_THREAD_KEY = "_love_mainthread";
  674. lua_State *luax_insistpinnedthread(lua_State *L)
  675. {
  676. lua_getfield(L, LUA_REGISTRYINDEX, MAIN_THREAD_KEY);
  677. if (lua_isnoneornil(L, -1))
  678. {
  679. lua_pop(L, 1);
  680. // lua_pushthread returns 1 if it's actually the main thread, but we
  681. // can't actually get the real main thread if lua_pushthread doesn't
  682. // return it (in Lua 5.1 at least), so we ignore that for now...
  683. // We do store a strong reference to the current thread/coroutine in
  684. // the registry, however.
  685. lua_pushthread(L);
  686. lua_pushvalue(L, -1);
  687. lua_setfield(L, LUA_REGISTRYINDEX, MAIN_THREAD_KEY);
  688. }
  689. lua_State *thread = lua_tothread(L, -1);
  690. lua_pop(L, 1);
  691. return thread;
  692. }
  693. lua_State *luax_getpinnedthread(lua_State *L)
  694. {
  695. lua_getfield(L, LUA_REGISTRYINDEX, MAIN_THREAD_KEY);
  696. lua_State *thread = lua_tothread(L, -1);
  697. lua_pop(L, 1);
  698. return thread;
  699. }
  700. void luax_markdeprecated(lua_State *L, const char *name, APIType api)
  701. {
  702. luax_markdeprecated(L, name, api, DEPRECATED_NO_REPLACEMENT, nullptr);
  703. }
  704. void luax_markdeprecated(lua_State *L, const char *name, APIType api, DeprecationType type, const char *replacement)
  705. {
  706. MarkDeprecated deprecated(name, api, type, replacement);
  707. if (deprecated.info != nullptr && deprecated.info->uses == 1)
  708. {
  709. luaL_where(L, 1);
  710. const char *where = lua_tostring(L, -1);
  711. if (where != nullptr)
  712. deprecated.info->where = where;
  713. lua_pop(L, 1);
  714. }
  715. }
  716. extern "C" int luax_typerror(lua_State *L, int narg, const char *tname)
  717. {
  718. int argtype = lua_type(L, narg);
  719. const char *argtname = nullptr;
  720. // We want to use the love type name for userdata, if possible.
  721. if (argtype == LUA_TUSERDATA && luaL_getmetafield(L, narg, "type") != 0)
  722. {
  723. lua_pushvalue(L, narg);
  724. if (lua_pcall(L, 1, 1, 0) == 0 && lua_type(L, -1) == LUA_TSTRING)
  725. {
  726. argtname = lua_tostring(L, -1);
  727. // Non-love userdata might have a type metamethod which doesn't
  728. // describe its type properly, so we only use it for love types.
  729. if (!Type::byName(argtname))
  730. argtname = nullptr;
  731. }
  732. }
  733. if (argtname == nullptr)
  734. argtname = lua_typename(L, argtype);
  735. const char *msg = lua_pushfstring(L, "%s expected, got %s", tname, argtname);
  736. return luaL_argerror(L, narg, msg);
  737. }
  738. int luax_enumerror(lua_State *L, const char *enumName, const char *value)
  739. {
  740. return luaL_error(L, "Invalid %s: %s", enumName, value);
  741. }
  742. int luax_enumerror(lua_State *L, const char *enumName, const std::vector<std::string> &values, const char *value)
  743. {
  744. std::stringstream valueStream;
  745. bool first = true;
  746. for (auto value : values)
  747. {
  748. valueStream << (first ? "'" : ", '") << value << "'";
  749. first = false;
  750. }
  751. std::string valueString = valueStream.str();
  752. return luaL_error(L, "Invalid %s '%s', expected one of: %s", enumName, value, valueString.c_str());
  753. }
  754. size_t luax_objlen(lua_State *L, int ndx)
  755. {
  756. #if LUA_VERSION_NUM == 501
  757. return lua_objlen(L, ndx);
  758. #else
  759. return lua_rawlen(L, ndx);
  760. #endif
  761. }
  762. void luax_register(lua_State *L, const char *name, const luaL_Reg *l)
  763. {
  764. if (name)
  765. lua_newtable(L);
  766. luax_setfuncs(L, l);
  767. if (name)
  768. {
  769. lua_pushvalue(L, -1);
  770. lua_setglobal(L, name);
  771. }
  772. }
  773. void luax_runwrapper(lua_State *L, const char *filedata, size_t datalen, const char *filename, const love::Type &type, void *ffifuncs)
  774. {
  775. luax_gettypemetatable(L, type);
  776. // Load and execute the given Lua file, sending the metatable and the ffi
  777. // functions struct pointer as arguments.
  778. if (lua_istable(L, -1))
  779. {
  780. luaL_loadbuffer(L, filedata, datalen, filename);
  781. lua_pushvalue(L, -2);
  782. if (ffifuncs != nullptr)
  783. luax_pushpointerasstring(L, ffifuncs);
  784. else
  785. lua_pushnil(L);
  786. lua_call(L, 2, 0);
  787. }
  788. // Pop the metatable.
  789. lua_pop(L, 1);
  790. }
  791. Type *luax_type(lua_State *L, int idx)
  792. {
  793. return Type::byName(luaL_checkstring(L, idx));
  794. }
  795. int luax_resume(lua_State *L, int nargs)
  796. {
  797. #if LUA_VERSION_NUM >= 502
  798. return lua_resume(L, nullptr, nargs);
  799. #else
  800. return lua_resume(L, nargs);
  801. #endif
  802. }
  803. } // love