runtime.cpp 24 KB

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