lauxlib.c 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  1. /*
  2. ** $Id: lauxlib.c $
  3. ** Auxiliary functions for building Lua libraries
  4. ** See Copyright Notice in lua.h
  5. */
  6. #define lauxlib_c
  7. #define LUA_LIB
  8. #include "lprefix.h"
  9. #include <errno.h>
  10. #include <stdarg.h>
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <string.h>
  14. /*
  15. ** This file uses only the official API of Lua.
  16. ** Any function declared here could be written as an application function.
  17. */
  18. #include "lua.h"
  19. #include "lauxlib.h"
  20. /*
  21. ** {======================================================
  22. ** Traceback
  23. ** =======================================================
  24. */
  25. #define LEVELS1 10 /* size of the first part of the stack */
  26. #define LEVELS2 11 /* size of the second part of the stack */
  27. /*
  28. ** search for 'objidx' in table at index -1.
  29. ** return 1 + string at top if find a good name.
  30. */
  31. static int findfield (lua_State *L, int objidx, int level) {
  32. if (level == 0 || !lua_istable(L, -1))
  33. return 0; /* not found */
  34. lua_pushnil(L); /* start 'next' loop */
  35. while (lua_next(L, -2)) { /* for each pair in table */
  36. if (lua_type(L, -2) == LUA_TSTRING) { /* ignore non-string keys */
  37. if (lua_rawequal(L, objidx, -1)) { /* found object? */
  38. lua_pop(L, 1); /* remove value (but keep name) */
  39. return 1;
  40. }
  41. else if (findfield(L, objidx, level - 1)) { /* try recursively */
  42. lua_remove(L, -2); /* remove table (but keep name) */
  43. lua_pushliteral(L, ".");
  44. lua_insert(L, -2); /* place '.' between the two names */
  45. lua_concat(L, 3);
  46. return 1;
  47. }
  48. }
  49. lua_pop(L, 1); /* remove value */
  50. }
  51. return 0; /* not found */
  52. }
  53. /*
  54. ** Search for a name for a function in all loaded modules
  55. */
  56. static int pushglobalfuncname (lua_State *L, lua_Debug *ar) {
  57. int top = lua_gettop(L);
  58. lua_getinfo(L, "f", ar); /* push function */
  59. lua_getfield(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);
  60. if (findfield(L, top + 1, 2)) {
  61. const char *name = lua_tostring(L, -1);
  62. if (strncmp(name, LUA_GNAME ".", 3) == 0) { /* name start with '_G.'? */
  63. lua_pushstring(L, name + 3); /* push name without prefix */
  64. lua_remove(L, -2); /* remove original name */
  65. }
  66. lua_copy(L, -1, top + 1); /* move name to proper place */
  67. lua_pop(L, 2); /* remove pushed values */
  68. return 1;
  69. }
  70. else {
  71. lua_settop(L, top); /* remove function and global table */
  72. return 0;
  73. }
  74. }
  75. static void pushfuncname (lua_State *L, lua_Debug *ar) {
  76. if (pushglobalfuncname(L, ar)) { /* try first a global name */
  77. lua_pushfstring(L, "function '%s'", lua_tostring(L, -1));
  78. lua_remove(L, -2); /* remove name */
  79. }
  80. else if (*ar->namewhat != '\0') /* is there a name from code? */
  81. lua_pushfstring(L, "%s '%s'", ar->namewhat, ar->name); /* use it */
  82. else if (*ar->what == 'm') /* main? */
  83. lua_pushliteral(L, "main chunk");
  84. else if (*ar->what != 'C') /* for Lua functions, use <file:line> */
  85. lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined);
  86. else /* nothing left... */
  87. lua_pushliteral(L, "?");
  88. }
  89. static int lastlevel (lua_State *L) {
  90. lua_Debug ar;
  91. int li = 1, le = 1;
  92. /* find an upper bound */
  93. while (lua_getstack(L, le, &ar)) { li = le; le *= 2; }
  94. /* do a binary search */
  95. while (li < le) {
  96. int m = (li + le)/2;
  97. if (lua_getstack(L, m, &ar)) li = m + 1;
  98. else le = m;
  99. }
  100. return le - 1;
  101. }
  102. LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1,
  103. const char *msg, int level) {
  104. lua_Debug ar;
  105. int top = lua_gettop(L);
  106. int last = lastlevel(L1);
  107. int n1 = (last - level > LEVELS1 + LEVELS2) ? LEVELS1 : -1;
  108. if (msg)
  109. lua_pushfstring(L, "%s\n", msg);
  110. luaL_checkstack(L, 10, NULL);
  111. lua_pushliteral(L, "stack traceback:");
  112. while (lua_getstack(L1, level++, &ar)) {
  113. if (n1-- == 0) { /* too many levels? */
  114. lua_pushliteral(L, "\n\t..."); /* add a '...' */
  115. level = last - LEVELS2 + 1; /* and skip to last ones */
  116. }
  117. else {
  118. lua_getinfo(L1, "Slnt", &ar);
  119. lua_pushfstring(L, "\n\t%s:", ar.short_src);
  120. if (ar.currentline > 0)
  121. lua_pushfstring(L, "%d:", ar.currentline);
  122. lua_pushliteral(L, " in ");
  123. pushfuncname(L, &ar);
  124. if (ar.istailcall)
  125. lua_pushliteral(L, "\n\t(...tail calls...)");
  126. lua_concat(L, lua_gettop(L) - top);
  127. }
  128. }
  129. lua_concat(L, lua_gettop(L) - top);
  130. }
  131. /* }====================================================== */
  132. /*
  133. ** {======================================================
  134. ** Error-report functions
  135. ** =======================================================
  136. */
  137. LUALIB_API int luaL_argerror (lua_State *L, int arg, const char *extramsg) {
  138. lua_Debug ar;
  139. if (!lua_getstack(L, 0, &ar)) /* no stack frame? */
  140. return luaL_error(L, "bad argument #%d (%s)", arg, extramsg);
  141. lua_getinfo(L, "n", &ar);
  142. if (strcmp(ar.namewhat, "method") == 0) {
  143. arg--; /* do not count 'self' */
  144. if (arg == 0) /* error is in the self argument itself? */
  145. return luaL_error(L, "calling '%s' on bad self (%s)",
  146. ar.name, extramsg);
  147. }
  148. if (ar.name == NULL)
  149. ar.name = (pushglobalfuncname(L, &ar)) ? lua_tostring(L, -1) : "?";
  150. return luaL_error(L, "bad argument #%d to '%s' (%s)",
  151. arg, ar.name, extramsg);
  152. }
  153. static int typeerror (lua_State *L, int arg, const char *tname) {
  154. const char *msg;
  155. const char *typearg; /* name for the type of the actual argument */
  156. if (luaL_getmetafield(L, arg, "__name") == LUA_TSTRING)
  157. typearg = lua_tostring(L, -1); /* use the given type name */
  158. else if (lua_type(L, arg) == LUA_TLIGHTUSERDATA)
  159. typearg = "light userdata"; /* special name for messages */
  160. else
  161. typearg = luaL_typename(L, arg); /* standard name */
  162. msg = lua_pushfstring(L, "%s expected, got %s", tname, typearg);
  163. return luaL_argerror(L, arg, msg);
  164. }
  165. static void tag_error (lua_State *L, int arg, int tag) {
  166. typeerror(L, arg, lua_typename(L, tag));
  167. }
  168. /*
  169. ** The use of 'lua_pushfstring' ensures this function does not
  170. ** need reserved stack space when called.
  171. */
  172. LUALIB_API void luaL_where (lua_State *L, int level) {
  173. lua_Debug ar;
  174. if (lua_getstack(L, level, &ar)) { /* check function at level */
  175. lua_getinfo(L, "Sl", &ar); /* get info about it */
  176. if (ar.currentline > 0) { /* is there info? */
  177. lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline);
  178. return;
  179. }
  180. }
  181. lua_pushfstring(L, ""); /* else, no information available... */
  182. }
  183. /*
  184. ** Again, the use of 'lua_pushvfstring' ensures this function does
  185. ** not need reserved stack space when called. (At worst, it generates
  186. ** an error with "stack overflow" instead of the given message.)
  187. */
  188. LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) {
  189. va_list argp;
  190. va_start(argp, fmt);
  191. luaL_where(L, 1);
  192. lua_pushvfstring(L, fmt, argp);
  193. va_end(argp);
  194. lua_concat(L, 2);
  195. return lua_error(L);
  196. }
  197. LUALIB_API int luaL_fileresult (lua_State *L, int stat, const char *fname) {
  198. int en = errno; /* calls to Lua API may change this value */
  199. if (stat) {
  200. lua_pushboolean(L, 1);
  201. return 1;
  202. }
  203. else {
  204. lua_pushnil(L);
  205. if (fname)
  206. lua_pushfstring(L, "%s: %s", fname, strerror(en));
  207. else
  208. lua_pushstring(L, strerror(en));
  209. lua_pushinteger(L, en);
  210. return 3;
  211. }
  212. }
  213. #if !defined(l_inspectstat) /* { */
  214. #if defined(LUA_USE_POSIX)
  215. #include <sys/wait.h>
  216. /*
  217. ** use appropriate macros to interpret 'pclose' return status
  218. */
  219. #define l_inspectstat(stat,what) \
  220. if (WIFEXITED(stat)) { stat = WEXITSTATUS(stat); } \
  221. else if (WIFSIGNALED(stat)) { stat = WTERMSIG(stat); what = "signal"; }
  222. #else
  223. #define l_inspectstat(stat,what) /* no op */
  224. #endif
  225. #endif /* } */
  226. LUALIB_API int luaL_execresult (lua_State *L, int stat) {
  227. const char *what = "exit"; /* type of termination */
  228. if (stat == -1) /* error? */
  229. return luaL_fileresult(L, 0, NULL);
  230. else {
  231. l_inspectstat(stat, what); /* interpret result */
  232. if (*what == 'e' && stat == 0) /* successful termination? */
  233. lua_pushboolean(L, 1);
  234. else
  235. lua_pushnil(L);
  236. lua_pushstring(L, what);
  237. lua_pushinteger(L, stat);
  238. return 3; /* return true/nil,what,code */
  239. }
  240. }
  241. /* }====================================================== */
  242. /*
  243. ** {======================================================
  244. ** 'luaL_resourcetryagain'
  245. ** This function uses 'errno' to check whether the last error was
  246. ** related to lack of resources (e.g., not enough memory or too many
  247. ** open files). If so, the function performs a full garbage collection
  248. ** to try to release resources, and then it returns 1 to signal to
  249. ** the caller that it is worth trying again the failed operation.
  250. ** Otherwise, it returns 0. Because error codes are not ANSI C, the
  251. ** code must handle any combination of error codes that are defined.
  252. ** =======================================================
  253. */
  254. LUALIB_API int luaL_resourcetryagain (lua_State *L) {
  255. /* these are the resource-related errors in Linux */
  256. #if defined(EMFILE) || defined(ENFILE) || defined(ENOMEM)
  257. #if !defined(EMFILE) /* too many open files in the process */
  258. #define EMFILE -1 /* if not defined, use an impossible value */
  259. #endif
  260. #if !defined(ENFILE) /* too many open files in the system */
  261. #define ENFILE -1
  262. #endif
  263. #if !defined(ENOMEM) /* not enough memory */
  264. #define ENOMEM -1
  265. #endif
  266. if (errno == EMFILE || errno == ENFILE || errno == ENOMEM) {
  267. lua_gc(L, LUA_GCCOLLECT); /* try to release resources with a full GC */
  268. return 1; /* signal to try again the creation */
  269. }
  270. #endif
  271. return 0; /* else, asume errors are not due to lack of resources */
  272. }
  273. /* }====================================================== */
  274. /*
  275. ** {======================================================
  276. ** Userdata's metatable manipulation
  277. ** =======================================================
  278. */
  279. LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) {
  280. if (luaL_getmetatable(L, tname) != LUA_TNIL) /* name already in use? */
  281. return 0; /* leave previous value on top, but return 0 */
  282. lua_pop(L, 1);
  283. lua_createtable(L, 0, 2); /* create metatable */
  284. lua_pushstring(L, tname);
  285. lua_setfield(L, -2, "__name"); /* metatable.__name = tname */
  286. lua_pushvalue(L, -1);
  287. lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */
  288. return 1;
  289. }
  290. LUALIB_API void luaL_setmetatable (lua_State *L, const char *tname) {
  291. luaL_getmetatable(L, tname);
  292. lua_setmetatable(L, -2);
  293. }
  294. LUALIB_API void *luaL_testudata (lua_State *L, int ud, const char *tname) {
  295. void *p = lua_touserdata(L, ud);
  296. if (p != NULL) { /* value is a userdata? */
  297. if (lua_getmetatable(L, ud)) { /* does it have a metatable? */
  298. luaL_getmetatable(L, tname); /* get correct metatable */
  299. if (!lua_rawequal(L, -1, -2)) /* not the same? */
  300. p = NULL; /* value is a userdata with wrong metatable */
  301. lua_pop(L, 2); /* remove both metatables */
  302. return p;
  303. }
  304. }
  305. return NULL; /* value is not a userdata with a metatable */
  306. }
  307. LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) {
  308. void *p = luaL_testudata(L, ud, tname);
  309. if (p == NULL) typeerror(L, ud, tname);
  310. return p;
  311. }
  312. /* }====================================================== */
  313. /*
  314. ** {======================================================
  315. ** Argument check functions
  316. ** =======================================================
  317. */
  318. LUALIB_API int luaL_checkoption (lua_State *L, int arg, const char *def,
  319. const char *const lst[]) {
  320. const char *name = (def) ? luaL_optstring(L, arg, def) :
  321. luaL_checkstring(L, arg);
  322. int i;
  323. for (i=0; lst[i]; i++)
  324. if (strcmp(lst[i], name) == 0)
  325. return i;
  326. return luaL_argerror(L, arg,
  327. lua_pushfstring(L, "invalid option '%s'", name));
  328. }
  329. /*
  330. ** Ensures the stack has at least 'space' extra slots, raising an error
  331. ** if it cannot fulfill the request. (The error handling needs a few
  332. ** extra slots to format the error message. In case of an error without
  333. ** this extra space, Lua will generate the same 'stack overflow' error,
  334. ** but without 'msg'.)
  335. */
  336. LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *msg) {
  337. if (!lua_checkstack(L, space)) {
  338. if (msg)
  339. luaL_error(L, "stack overflow (%s)", msg);
  340. else
  341. luaL_error(L, "stack overflow");
  342. }
  343. }
  344. LUALIB_API void luaL_checktype (lua_State *L, int arg, int t) {
  345. if (lua_type(L, arg) != t)
  346. tag_error(L, arg, t);
  347. }
  348. LUALIB_API void luaL_checkany (lua_State *L, int arg) {
  349. if (lua_type(L, arg) == LUA_TNONE)
  350. luaL_argerror(L, arg, "value expected");
  351. }
  352. LUALIB_API const char *luaL_checklstring (lua_State *L, int arg, size_t *len) {
  353. const char *s = lua_tolstring(L, arg, len);
  354. if (!s) tag_error(L, arg, LUA_TSTRING);
  355. return s;
  356. }
  357. LUALIB_API const char *luaL_optlstring (lua_State *L, int arg,
  358. const char *def, size_t *len) {
  359. if (lua_isnoneornil(L, arg)) {
  360. if (len)
  361. *len = (def ? strlen(def) : 0);
  362. return def;
  363. }
  364. else return luaL_checklstring(L, arg, len);
  365. }
  366. LUALIB_API lua_Number luaL_checknumber (lua_State *L, int arg) {
  367. int isnum;
  368. lua_Number d = lua_tonumberx(L, arg, &isnum);
  369. if (!isnum)
  370. tag_error(L, arg, LUA_TNUMBER);
  371. return d;
  372. }
  373. LUALIB_API lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number def) {
  374. return luaL_opt(L, luaL_checknumber, arg, def);
  375. }
  376. static void interror (lua_State *L, int arg) {
  377. if (lua_isnumber(L, arg))
  378. luaL_argerror(L, arg, "number has no integer representation");
  379. else
  380. tag_error(L, arg, LUA_TNUMBER);
  381. }
  382. LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int arg) {
  383. int isnum;
  384. lua_Integer d = lua_tointegerx(L, arg, &isnum);
  385. if (!isnum) {
  386. interror(L, arg);
  387. }
  388. return d;
  389. }
  390. LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int arg,
  391. lua_Integer def) {
  392. return luaL_opt(L, luaL_checkinteger, arg, def);
  393. }
  394. /* }====================================================== */
  395. /*
  396. ** {======================================================
  397. ** Generic Buffer manipulation
  398. ** =======================================================
  399. */
  400. /* userdata to box arbitrary data */
  401. typedef struct UBox {
  402. void *box;
  403. size_t bsize;
  404. } UBox;
  405. static void *resizebox (lua_State *L, int idx, size_t newsize) {
  406. void *ud;
  407. lua_Alloc allocf = lua_getallocf(L, &ud);
  408. UBox *box = (UBox *)lua_touserdata(L, idx);
  409. void *temp = allocf(ud, box->box, box->bsize, newsize);
  410. if (temp == NULL && newsize > 0) { /* allocation error? */
  411. resizebox(L, idx, 0); /* free buffer */
  412. luaL_error(L, "not enough memory for buffer allocation");
  413. }
  414. box->box = temp;
  415. box->bsize = newsize;
  416. return temp;
  417. }
  418. static int boxgc (lua_State *L) {
  419. resizebox(L, 1, 0);
  420. return 0;
  421. }
  422. static void *newbox (lua_State *L, size_t newsize) {
  423. UBox *box = (UBox *)lua_newuserdatauv(L, sizeof(UBox), 0);
  424. box->box = NULL;
  425. box->bsize = 0;
  426. if (luaL_newmetatable(L, "_UBOX*")) { /* creating metatable? */
  427. lua_pushcfunction(L, boxgc);
  428. lua_setfield(L, -2, "__gc"); /* metatable.__gc = boxgc */
  429. }
  430. lua_setmetatable(L, -2);
  431. return resizebox(L, -1, newsize);
  432. }
  433. /*
  434. ** check whether buffer is using a userdata on the stack as a temporary
  435. ** buffer
  436. */
  437. #define buffonstack(B) ((B)->b != (B)->init.b)
  438. /*
  439. ** returns a pointer to a free area with at least 'sz' bytes
  440. */
  441. LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) {
  442. lua_State *L = B->L;
  443. if (B->size - B->n < sz) { /* not enough space? */
  444. char *newbuff;
  445. size_t newsize = B->size * 2; /* double buffer size */
  446. if (newsize - B->n < sz) /* not big enough? */
  447. newsize = B->n + sz;
  448. if (newsize < B->n || newsize - B->n < sz)
  449. luaL_error(L, "buffer too large");
  450. /* create larger buffer */
  451. if (buffonstack(B))
  452. newbuff = (char *)resizebox(L, -1, newsize);
  453. else { /* no buffer yet */
  454. newbuff = (char *)newbox(L, newsize);
  455. memcpy(newbuff, B->b, B->n * sizeof(char)); /* copy original content */
  456. }
  457. B->b = newbuff;
  458. B->size = newsize;
  459. }
  460. return &B->b[B->n];
  461. }
  462. LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
  463. if (l > 0) { /* avoid 'memcpy' when 's' can be NULL */
  464. char *b = luaL_prepbuffsize(B, l);
  465. memcpy(b, s, l * sizeof(char));
  466. luaL_addsize(B, l);
  467. }
  468. }
  469. LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {
  470. luaL_addlstring(B, s, strlen(s));
  471. }
  472. LUALIB_API void luaL_pushresult (luaL_Buffer *B) {
  473. lua_State *L = B->L;
  474. lua_pushlstring(L, B->b, B->n);
  475. if (buffonstack(B)) {
  476. resizebox(L, -2, 0); /* delete old buffer */
  477. lua_remove(L, -2); /* remove its header from the stack */
  478. }
  479. }
  480. LUALIB_API void luaL_pushresultsize (luaL_Buffer *B, size_t sz) {
  481. luaL_addsize(B, sz);
  482. luaL_pushresult(B);
  483. }
  484. LUALIB_API void luaL_addvalue (luaL_Buffer *B) {
  485. lua_State *L = B->L;
  486. size_t l;
  487. const char *s = lua_tolstring(L, -1, &l);
  488. if (buffonstack(B))
  489. lua_insert(L, -2); /* put value below buffer */
  490. luaL_addlstring(B, s, l);
  491. lua_remove(L, (buffonstack(B)) ? -2 : -1); /* remove value */
  492. }
  493. LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {
  494. B->L = L;
  495. B->b = B->init.b;
  496. B->n = 0;
  497. B->size = LUAL_BUFFERSIZE;
  498. }
  499. LUALIB_API char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz) {
  500. luaL_buffinit(L, B);
  501. return luaL_prepbuffsize(B, sz);
  502. }
  503. /* }====================================================== */
  504. /*
  505. ** {======================================================
  506. ** Reference system
  507. ** =======================================================
  508. */
  509. /* index of free-list header */
  510. #define freelist 0
  511. LUALIB_API int luaL_ref (lua_State *L, int t) {
  512. int ref;
  513. if (lua_isnil(L, -1)) {
  514. lua_pop(L, 1); /* remove from stack */
  515. return LUA_REFNIL; /* 'nil' has a unique fixed reference */
  516. }
  517. t = lua_absindex(L, t);
  518. lua_rawgeti(L, t, freelist); /* get first free element */
  519. ref = (int)lua_tointeger(L, -1); /* ref = t[freelist] */
  520. lua_pop(L, 1); /* remove it from stack */
  521. if (ref != 0) { /* any free element? */
  522. lua_rawgeti(L, t, ref); /* remove it from list */
  523. lua_rawseti(L, t, freelist); /* (t[freelist] = t[ref]) */
  524. }
  525. else /* no free elements */
  526. ref = (int)lua_rawlen(L, t) + 1; /* get a new reference */
  527. lua_rawseti(L, t, ref);
  528. return ref;
  529. }
  530. LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
  531. if (ref >= 0) {
  532. t = lua_absindex(L, t);
  533. lua_rawgeti(L, t, freelist);
  534. lua_rawseti(L, t, ref); /* t[ref] = t[freelist] */
  535. lua_pushinteger(L, ref);
  536. lua_rawseti(L, t, freelist); /* t[freelist] = ref */
  537. }
  538. }
  539. /* }====================================================== */
  540. /*
  541. ** {======================================================
  542. ** Load functions
  543. ** =======================================================
  544. */
  545. typedef struct LoadF {
  546. int n; /* number of pre-read characters */
  547. FILE *f; /* file being read */
  548. char buff[BUFSIZ]; /* area for reading file */
  549. } LoadF;
  550. static const char *getF (lua_State *L, void *ud, size_t *size) {
  551. LoadF *lf = (LoadF *)ud;
  552. (void)L; /* not used */
  553. if (lf->n > 0) { /* are there pre-read characters to be read? */
  554. *size = lf->n; /* return them (chars already in buffer) */
  555. lf->n = 0; /* no more pre-read characters */
  556. }
  557. else { /* read a block from file */
  558. /* 'fread' can return > 0 *and* set the EOF flag. If next call to
  559. 'getF' called 'fread', it might still wait for user input.
  560. The next check avoids this problem. */
  561. if (feof(lf->f)) return NULL;
  562. *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f); /* read block */
  563. }
  564. return lf->buff;
  565. }
  566. static int errfile (lua_State *L, const char *what, int fnameindex) {
  567. const char *serr = strerror(errno);
  568. const char *filename = lua_tostring(L, fnameindex) + 1;
  569. lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr);
  570. lua_remove(L, fnameindex);
  571. return LUA_ERRFILE;
  572. }
  573. static int skipBOM (LoadF *lf) {
  574. const char *p = "\xEF\xBB\xBF"; /* UTF-8 BOM mark */
  575. int c;
  576. lf->n = 0;
  577. do {
  578. c = getc(lf->f);
  579. if (c == EOF || c != *(const unsigned char *)p++) return c;
  580. lf->buff[lf->n++] = c; /* to be read by the parser */
  581. } while (*p != '\0');
  582. lf->n = 0; /* prefix matched; discard it */
  583. return getc(lf->f); /* return next character */
  584. }
  585. /*
  586. ** reads the first character of file 'f' and skips an optional BOM mark
  587. ** in its beginning plus its first line if it starts with '#'. Returns
  588. ** true if it skipped the first line. In any case, '*cp' has the
  589. ** first "valid" character of the file (after the optional BOM and
  590. ** a first-line comment).
  591. */
  592. static int skipcomment (LoadF *lf, int *cp) {
  593. int c = *cp = skipBOM(lf);
  594. if (c == '#') { /* first line is a comment (Unix exec. file)? */
  595. do { /* skip first line */
  596. c = getc(lf->f);
  597. } while (c != EOF && c != '\n');
  598. *cp = getc(lf->f); /* skip end-of-line, if present */
  599. return 1; /* there was a comment */
  600. }
  601. else return 0; /* no comment */
  602. }
  603. LUALIB_API int luaL_loadfilex (lua_State *L, const char *filename,
  604. const char *mode) {
  605. LoadF lf;
  606. int status, readstatus;
  607. int c;
  608. int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */
  609. if (filename == NULL) {
  610. lua_pushliteral(L, "=stdin");
  611. lf.f = stdin;
  612. }
  613. else {
  614. lua_pushfstring(L, "@%s", filename);
  615. lf.f = fopen(filename, "r");
  616. if (lf.f == NULL) return errfile(L, "open", fnameindex);
  617. }
  618. if (skipcomment(&lf, &c)) /* read initial portion */
  619. lf.buff[lf.n++] = '\n'; /* add line to correct line numbers */
  620. if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */
  621. lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */
  622. if (lf.f == NULL) return errfile(L, "reopen", fnameindex);
  623. skipcomment(&lf, &c); /* re-read initial portion */
  624. }
  625. if (c != EOF)
  626. lf.buff[lf.n++] = c; /* 'c' is the first character of the stream */
  627. status = lua_load(L, getF, &lf, lua_tostring(L, -1), mode);
  628. readstatus = ferror(lf.f);
  629. if (filename) fclose(lf.f); /* close file (even in case of errors) */
  630. if (readstatus) {
  631. lua_settop(L, fnameindex); /* ignore results from 'lua_load' */
  632. return errfile(L, "read", fnameindex);
  633. }
  634. lua_remove(L, fnameindex);
  635. return status;
  636. }
  637. typedef struct LoadS {
  638. const char *s;
  639. size_t size;
  640. } LoadS;
  641. static const char *getS (lua_State *L, void *ud, size_t *size) {
  642. LoadS *ls = (LoadS *)ud;
  643. (void)L; /* not used */
  644. if (ls->size == 0) return NULL;
  645. *size = ls->size;
  646. ls->size = 0;
  647. return ls->s;
  648. }
  649. LUALIB_API int luaL_loadbufferx (lua_State *L, const char *buff, size_t size,
  650. const char *name, const char *mode) {
  651. LoadS ls;
  652. ls.s = buff;
  653. ls.size = size;
  654. return lua_load(L, getS, &ls, name, mode);
  655. }
  656. LUALIB_API int luaL_loadstring (lua_State *L, const char *s) {
  657. return luaL_loadbuffer(L, s, strlen(s), s);
  658. }
  659. /* }====================================================== */
  660. LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {
  661. if (!lua_getmetatable(L, obj)) /* no metatable? */
  662. return LUA_TNIL;
  663. else {
  664. int tt;
  665. lua_pushstring(L, event);
  666. tt = lua_rawget(L, -2);
  667. if (tt == LUA_TNIL) /* is metafield nil? */
  668. lua_pop(L, 2); /* remove metatable and metafield */
  669. else
  670. lua_remove(L, -2); /* remove only metatable */
  671. return tt; /* return metafield type */
  672. }
  673. }
  674. LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {
  675. obj = lua_absindex(L, obj);
  676. if (luaL_getmetafield(L, obj, event) == LUA_TNIL) /* no metafield? */
  677. return 0;
  678. lua_pushvalue(L, obj);
  679. lua_call(L, 1, 1);
  680. return 1;
  681. }
  682. LUALIB_API lua_Integer luaL_len (lua_State *L, int idx) {
  683. lua_Integer l;
  684. int isnum;
  685. lua_len(L, idx);
  686. l = lua_tointegerx(L, -1, &isnum);
  687. if (!isnum)
  688. luaL_error(L, "object length is not an integer");
  689. lua_pop(L, 1); /* remove object */
  690. return l;
  691. }
  692. LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) {
  693. if (luaL_callmeta(L, idx, "__tostring")) { /* metafield? */
  694. if (!lua_isstring(L, -1))
  695. luaL_error(L, "'__tostring' must return a string");
  696. }
  697. else {
  698. switch (lua_type(L, idx)) {
  699. case LUA_TNUMBER: {
  700. if (lua_isinteger(L, idx))
  701. lua_pushfstring(L, "%I", (LUAI_UACINT)lua_tointeger(L, idx));
  702. else
  703. lua_pushfstring(L, "%f", (LUAI_UACNUMBER)lua_tonumber(L, idx));
  704. break;
  705. }
  706. case LUA_TSTRING:
  707. lua_pushvalue(L, idx);
  708. break;
  709. case LUA_TBOOLEAN:
  710. lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false"));
  711. break;
  712. case LUA_TNIL:
  713. lua_pushliteral(L, "nil");
  714. break;
  715. default: {
  716. int tt = luaL_getmetafield(L, idx, "__name"); /* try name */
  717. const char *kind = (tt == LUA_TSTRING) ? lua_tostring(L, -1) :
  718. luaL_typename(L, idx);
  719. lua_pushfstring(L, "%s: %p", kind, lua_topointer(L, idx));
  720. if (tt != LUA_TNIL)
  721. lua_remove(L, -2); /* remove '__name' */
  722. break;
  723. }
  724. }
  725. }
  726. return lua_tolstring(L, -1, len);
  727. }
  728. /*
  729. ** set functions from list 'l' into table at top - 'nup'; each
  730. ** function gets the 'nup' elements at the top as upvalues.
  731. ** Returns with only the table at the stack.
  732. */
  733. LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) {
  734. luaL_checkstack(L, nup, "too many upvalues");
  735. for (; l->name != NULL; l++) { /* fill the table with given functions */
  736. int i;
  737. for (i = 0; i < nup; i++) /* copy upvalues to the top */
  738. lua_pushvalue(L, -nup);
  739. lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */
  740. lua_setfield(L, -(nup + 2), l->name);
  741. }
  742. lua_pop(L, nup); /* remove upvalues */
  743. }
  744. /*
  745. ** ensure that stack[idx][fname] has a table and push that table
  746. ** into the stack
  747. */
  748. LUALIB_API int luaL_getsubtable (lua_State *L, int idx, const char *fname) {
  749. if (lua_getfield(L, idx, fname) == LUA_TTABLE)
  750. return 1; /* table already there */
  751. else {
  752. lua_pop(L, 1); /* remove previous result */
  753. idx = lua_absindex(L, idx);
  754. lua_newtable(L);
  755. lua_pushvalue(L, -1); /* copy to be left at top */
  756. lua_setfield(L, idx, fname); /* assign new table to field */
  757. return 0; /* false, because did not find table there */
  758. }
  759. }
  760. /*
  761. ** Stripped-down 'require': After checking "loaded" table, calls 'openf'
  762. ** to open a module, registers the result in 'package.loaded' table and,
  763. ** if 'glb' is true, also registers the result in the global table.
  764. ** Leaves resulting module on the top.
  765. */
  766. LUALIB_API void luaL_requiref (lua_State *L, const char *modname,
  767. lua_CFunction openf, int glb) {
  768. luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);
  769. lua_getfield(L, -1, modname); /* LOADED[modname] */
  770. if (!lua_toboolean(L, -1)) { /* package not already loaded? */
  771. lua_pop(L, 1); /* remove field */
  772. lua_pushcfunction(L, openf);
  773. lua_pushstring(L, modname); /* argument to open function */
  774. lua_call(L, 1, 1); /* call 'openf' to open module */
  775. lua_pushvalue(L, -1); /* make copy of module (call result) */
  776. lua_setfield(L, -3, modname); /* LOADED[modname] = module */
  777. }
  778. lua_remove(L, -2); /* remove LOADED table */
  779. if (glb) {
  780. lua_pushvalue(L, -1); /* copy of module */
  781. lua_setglobal(L, modname); /* _G[modname] = module */
  782. }
  783. }
  784. LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p,
  785. const char *r) {
  786. const char *wild;
  787. size_t l = strlen(p);
  788. luaL_Buffer b;
  789. luaL_buffinit(L, &b);
  790. while ((wild = strstr(s, p)) != NULL) {
  791. luaL_addlstring(&b, s, wild - s); /* push prefix */
  792. luaL_addstring(&b, r); /* push replacement in place of pattern */
  793. s = wild + l; /* continue after 'p' */
  794. }
  795. luaL_addstring(&b, s); /* push last suffix */
  796. luaL_pushresult(&b);
  797. return lua_tostring(L, -1);
  798. }
  799. static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
  800. (void)ud; (void)osize; /* not used */
  801. if (nsize == 0) {
  802. free(ptr);
  803. return NULL;
  804. }
  805. else
  806. return realloc(ptr, nsize);
  807. }
  808. static int panic (lua_State *L) {
  809. lua_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n",
  810. lua_tostring(L, -1));
  811. return 0; /* return to Lua to abort */
  812. }
  813. LUALIB_API lua_State *luaL_newstate (void) {
  814. lua_State *L = lua_newstate(l_alloc, NULL);
  815. if (L) lua_atpanic(L, &panic);
  816. return L;
  817. }
  818. LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver, size_t sz) {
  819. lua_Number v = lua_version(L);
  820. if (sz != LUAL_NUMSIZES) /* check numeric types */
  821. luaL_error(L, "core and library have incompatible numeric types");
  822. else if (v != ver)
  823. luaL_error(L, "version mismatch: app. needs %f, Lua core provides %f",
  824. (LUAI_UACNUMBER)ver, (LUAI_UACNUMBER)v);
  825. }