lauxlib.c 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043
  1. /*
  2. ** $Id: lauxlib.c,v 1.289 2016/12/20 18:37:00 roberto Exp $
  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, "_G.", 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. ** Userdata's metatable manipulation
  245. ** =======================================================
  246. */
  247. LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) {
  248. if (luaL_getmetatable(L, tname) != LUA_TNIL) /* name already in use? */
  249. return 0; /* leave previous value on top, but return 0 */
  250. lua_pop(L, 1);
  251. lua_createtable(L, 0, 2); /* create metatable */
  252. lua_pushstring(L, tname);
  253. lua_setfield(L, -2, "__name"); /* metatable.__name = tname */
  254. lua_pushvalue(L, -1);
  255. lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */
  256. return 1;
  257. }
  258. LUALIB_API void luaL_setmetatable (lua_State *L, const char *tname) {
  259. luaL_getmetatable(L, tname);
  260. lua_setmetatable(L, -2);
  261. }
  262. LUALIB_API void *luaL_testudata (lua_State *L, int ud, const char *tname) {
  263. void *p = lua_touserdata(L, ud);
  264. if (p != NULL) { /* value is a userdata? */
  265. if (lua_getmetatable(L, ud)) { /* does it have a metatable? */
  266. luaL_getmetatable(L, tname); /* get correct metatable */
  267. if (!lua_rawequal(L, -1, -2)) /* not the same? */
  268. p = NULL; /* value is a userdata with wrong metatable */
  269. lua_pop(L, 2); /* remove both metatables */
  270. return p;
  271. }
  272. }
  273. return NULL; /* value is not a userdata with a metatable */
  274. }
  275. LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) {
  276. void *p = luaL_testudata(L, ud, tname);
  277. if (p == NULL) typeerror(L, ud, tname);
  278. return p;
  279. }
  280. /* }====================================================== */
  281. /*
  282. ** {======================================================
  283. ** Argument check functions
  284. ** =======================================================
  285. */
  286. LUALIB_API int luaL_checkoption (lua_State *L, int arg, const char *def,
  287. const char *const lst[]) {
  288. const char *name = (def) ? luaL_optstring(L, arg, def) :
  289. luaL_checkstring(L, arg);
  290. int i;
  291. for (i=0; lst[i]; i++)
  292. if (strcmp(lst[i], name) == 0)
  293. return i;
  294. return luaL_argerror(L, arg,
  295. lua_pushfstring(L, "invalid option '%s'", name));
  296. }
  297. /*
  298. ** Ensures the stack has at least 'space' extra slots, raising an error
  299. ** if it cannot fulfill the request. (The error handling needs a few
  300. ** extra slots to format the error message. In case of an error without
  301. ** this extra space, Lua will generate the same 'stack overflow' error,
  302. ** but without 'msg'.)
  303. */
  304. LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *msg) {
  305. if (!lua_checkstack(L, space)) {
  306. if (msg)
  307. luaL_error(L, "stack overflow (%s)", msg);
  308. else
  309. luaL_error(L, "stack overflow");
  310. }
  311. }
  312. LUALIB_API void luaL_checktype (lua_State *L, int arg, int t) {
  313. if (lua_type(L, arg) != t)
  314. tag_error(L, arg, t);
  315. }
  316. LUALIB_API void luaL_checkany (lua_State *L, int arg) {
  317. if (lua_type(L, arg) == LUA_TNONE)
  318. luaL_argerror(L, arg, "value expected");
  319. }
  320. LUALIB_API const char *luaL_checklstring (lua_State *L, int arg, size_t *len) {
  321. const char *s = lua_tolstring(L, arg, len);
  322. if (!s) tag_error(L, arg, LUA_TSTRING);
  323. return s;
  324. }
  325. LUALIB_API const char *luaL_optlstring (lua_State *L, int arg,
  326. const char *def, size_t *len) {
  327. if (lua_isnoneornil(L, arg)) {
  328. if (len)
  329. *len = (def ? strlen(def) : 0);
  330. return def;
  331. }
  332. else return luaL_checklstring(L, arg, len);
  333. }
  334. LUALIB_API lua_Number luaL_checknumber (lua_State *L, int arg) {
  335. int isnum;
  336. lua_Number d = lua_tonumberx(L, arg, &isnum);
  337. if (!isnum)
  338. tag_error(L, arg, LUA_TNUMBER);
  339. return d;
  340. }
  341. LUALIB_API lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number def) {
  342. return luaL_opt(L, luaL_checknumber, arg, def);
  343. }
  344. static void interror (lua_State *L, int arg) {
  345. if (lua_isnumber(L, arg))
  346. luaL_argerror(L, arg, "number has no integer representation");
  347. else
  348. tag_error(L, arg, LUA_TNUMBER);
  349. }
  350. LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int arg) {
  351. int isnum;
  352. lua_Integer d = lua_tointegerx(L, arg, &isnum);
  353. if (!isnum) {
  354. interror(L, arg);
  355. }
  356. return d;
  357. }
  358. LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int arg,
  359. lua_Integer def) {
  360. return luaL_opt(L, luaL_checkinteger, arg, def);
  361. }
  362. /* }====================================================== */
  363. /*
  364. ** {======================================================
  365. ** Generic Buffer manipulation
  366. ** =======================================================
  367. */
  368. /* userdata to box arbitrary data */
  369. typedef struct UBox {
  370. void *box;
  371. size_t bsize;
  372. } UBox;
  373. static void *resizebox (lua_State *L, int idx, size_t newsize) {
  374. void *ud;
  375. lua_Alloc allocf = lua_getallocf(L, &ud);
  376. UBox *box = (UBox *)lua_touserdata(L, idx);
  377. void *temp = allocf(ud, box->box, box->bsize, newsize);
  378. if (temp == NULL && newsize > 0) { /* allocation error? */
  379. resizebox(L, idx, 0); /* free buffer */
  380. luaL_error(L, "not enough memory for buffer allocation");
  381. }
  382. box->box = temp;
  383. box->bsize = newsize;
  384. return temp;
  385. }
  386. static int boxgc (lua_State *L) {
  387. resizebox(L, 1, 0);
  388. return 0;
  389. }
  390. static void *newbox (lua_State *L, size_t newsize) {
  391. UBox *box = (UBox *)lua_newuserdata(L, sizeof(UBox));
  392. box->box = NULL;
  393. box->bsize = 0;
  394. if (luaL_newmetatable(L, "LUABOX")) { /* creating metatable? */
  395. lua_pushcfunction(L, boxgc);
  396. lua_setfield(L, -2, "__gc"); /* metatable.__gc = boxgc */
  397. }
  398. lua_setmetatable(L, -2);
  399. return resizebox(L, -1, newsize);
  400. }
  401. /*
  402. ** check whether buffer is using a userdata on the stack as a temporary
  403. ** buffer
  404. */
  405. #define buffonstack(B) ((B)->b != (B)->initb)
  406. /*
  407. ** returns a pointer to a free area with at least 'sz' bytes
  408. */
  409. LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) {
  410. lua_State *L = B->L;
  411. if (B->size - B->n < sz) { /* not enough space? */
  412. char *newbuff;
  413. size_t newsize = B->size * 2; /* double buffer size */
  414. if (newsize - B->n < sz) /* not big enough? */
  415. newsize = B->n + sz;
  416. if (newsize < B->n || newsize - B->n < sz)
  417. luaL_error(L, "buffer too large");
  418. /* create larger buffer */
  419. if (buffonstack(B))
  420. newbuff = (char *)resizebox(L, -1, newsize);
  421. else { /* no buffer yet */
  422. newbuff = (char *)newbox(L, newsize);
  423. memcpy(newbuff, B->b, B->n * sizeof(char)); /* copy original content */
  424. }
  425. B->b = newbuff;
  426. B->size = newsize;
  427. }
  428. return &B->b[B->n];
  429. }
  430. LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
  431. if (l > 0) { /* avoid 'memcpy' when 's' can be NULL */
  432. char *b = luaL_prepbuffsize(B, l);
  433. memcpy(b, s, l * sizeof(char));
  434. luaL_addsize(B, l);
  435. }
  436. }
  437. LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {
  438. luaL_addlstring(B, s, strlen(s));
  439. }
  440. LUALIB_API void luaL_pushresult (luaL_Buffer *B) {
  441. lua_State *L = B->L;
  442. lua_pushlstring(L, B->b, B->n);
  443. if (buffonstack(B)) {
  444. resizebox(L, -2, 0); /* delete old buffer */
  445. lua_remove(L, -2); /* remove its header from the stack */
  446. }
  447. }
  448. LUALIB_API void luaL_pushresultsize (luaL_Buffer *B, size_t sz) {
  449. luaL_addsize(B, sz);
  450. luaL_pushresult(B);
  451. }
  452. LUALIB_API void luaL_addvalue (luaL_Buffer *B) {
  453. lua_State *L = B->L;
  454. size_t l;
  455. const char *s = lua_tolstring(L, -1, &l);
  456. if (buffonstack(B))
  457. lua_insert(L, -2); /* put value below buffer */
  458. luaL_addlstring(B, s, l);
  459. lua_remove(L, (buffonstack(B)) ? -2 : -1); /* remove value */
  460. }
  461. LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {
  462. B->L = L;
  463. B->b = B->initb;
  464. B->n = 0;
  465. B->size = LUAL_BUFFERSIZE;
  466. }
  467. LUALIB_API char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz) {
  468. luaL_buffinit(L, B);
  469. return luaL_prepbuffsize(B, sz);
  470. }
  471. /* }====================================================== */
  472. /*
  473. ** {======================================================
  474. ** Reference system
  475. ** =======================================================
  476. */
  477. /* index of free-list header */
  478. #define freelist 0
  479. LUALIB_API int luaL_ref (lua_State *L, int t) {
  480. int ref;
  481. if (lua_isnil(L, -1)) {
  482. lua_pop(L, 1); /* remove from stack */
  483. return LUA_REFNIL; /* 'nil' has a unique fixed reference */
  484. }
  485. t = lua_absindex(L, t);
  486. lua_rawgeti(L, t, freelist); /* get first free element */
  487. ref = (int)lua_tointeger(L, -1); /* ref = t[freelist] */
  488. lua_pop(L, 1); /* remove it from stack */
  489. if (ref != 0) { /* any free element? */
  490. lua_rawgeti(L, t, ref); /* remove it from list */
  491. lua_rawseti(L, t, freelist); /* (t[freelist] = t[ref]) */
  492. }
  493. else /* no free elements */
  494. ref = (int)lua_rawlen(L, t) + 1; /* get a new reference */
  495. lua_rawseti(L, t, ref);
  496. return ref;
  497. }
  498. LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
  499. if (ref >= 0) {
  500. t = lua_absindex(L, t);
  501. lua_rawgeti(L, t, freelist);
  502. lua_rawseti(L, t, ref); /* t[ref] = t[freelist] */
  503. lua_pushinteger(L, ref);
  504. lua_rawseti(L, t, freelist); /* t[freelist] = ref */
  505. }
  506. }
  507. /* }====================================================== */
  508. /*
  509. ** {======================================================
  510. ** Load functions
  511. ** =======================================================
  512. */
  513. typedef struct LoadF {
  514. int n; /* number of pre-read characters */
  515. FILE *f; /* file being read */
  516. char buff[BUFSIZ]; /* area for reading file */
  517. } LoadF;
  518. static const char *getF (lua_State *L, void *ud, size_t *size) {
  519. LoadF *lf = (LoadF *)ud;
  520. (void)L; /* not used */
  521. if (lf->n > 0) { /* are there pre-read characters to be read? */
  522. *size = lf->n; /* return them (chars already in buffer) */
  523. lf->n = 0; /* no more pre-read characters */
  524. }
  525. else { /* read a block from file */
  526. /* 'fread' can return > 0 *and* set the EOF flag. If next call to
  527. 'getF' called 'fread', it might still wait for user input.
  528. The next check avoids this problem. */
  529. if (feof(lf->f)) return NULL;
  530. *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f); /* read block */
  531. }
  532. return lf->buff;
  533. }
  534. static int errfile (lua_State *L, const char *what, int fnameindex) {
  535. const char *serr = strerror(errno);
  536. const char *filename = lua_tostring(L, fnameindex) + 1;
  537. lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr);
  538. lua_remove(L, fnameindex);
  539. return LUA_ERRFILE;
  540. }
  541. static int skipBOM (LoadF *lf) {
  542. const char *p = "\xEF\xBB\xBF"; /* UTF-8 BOM mark */
  543. int c;
  544. lf->n = 0;
  545. do {
  546. c = getc(lf->f);
  547. if (c == EOF || c != *(const unsigned char *)p++) return c;
  548. lf->buff[lf->n++] = c; /* to be read by the parser */
  549. } while (*p != '\0');
  550. lf->n = 0; /* prefix matched; discard it */
  551. return getc(lf->f); /* return next character */
  552. }
  553. /*
  554. ** reads the first character of file 'f' and skips an optional BOM mark
  555. ** in its beginning plus its first line if it starts with '#'. Returns
  556. ** true if it skipped the first line. In any case, '*cp' has the
  557. ** first "valid" character of the file (after the optional BOM and
  558. ** a first-line comment).
  559. */
  560. static int skipcomment (LoadF *lf, int *cp) {
  561. int c = *cp = skipBOM(lf);
  562. if (c == '#') { /* first line is a comment (Unix exec. file)? */
  563. do { /* skip first line */
  564. c = getc(lf->f);
  565. } while (c != EOF && c != '\n');
  566. *cp = getc(lf->f); /* skip end-of-line, if present */
  567. return 1; /* there was a comment */
  568. }
  569. else return 0; /* no comment */
  570. }
  571. LUALIB_API int luaL_loadfilex (lua_State *L, const char *filename,
  572. const char *mode) {
  573. LoadF lf;
  574. int status, readstatus;
  575. int c;
  576. int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */
  577. if (filename == NULL) {
  578. lua_pushliteral(L, "=stdin");
  579. lf.f = stdin;
  580. }
  581. else {
  582. lua_pushfstring(L, "@%s", filename);
  583. lf.f = fopen(filename, "r");
  584. if (lf.f == NULL) return errfile(L, "open", fnameindex);
  585. }
  586. if (skipcomment(&lf, &c)) /* read initial portion */
  587. lf.buff[lf.n++] = '\n'; /* add line to correct line numbers */
  588. if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */
  589. lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */
  590. if (lf.f == NULL) return errfile(L, "reopen", fnameindex);
  591. skipcomment(&lf, &c); /* re-read initial portion */
  592. }
  593. if (c != EOF)
  594. lf.buff[lf.n++] = c; /* 'c' is the first character of the stream */
  595. status = lua_load(L, getF, &lf, lua_tostring(L, -1), mode);
  596. readstatus = ferror(lf.f);
  597. if (filename) fclose(lf.f); /* close file (even in case of errors) */
  598. if (readstatus) {
  599. lua_settop(L, fnameindex); /* ignore results from 'lua_load' */
  600. return errfile(L, "read", fnameindex);
  601. }
  602. lua_remove(L, fnameindex);
  603. return status;
  604. }
  605. typedef struct LoadS {
  606. const char *s;
  607. size_t size;
  608. } LoadS;
  609. static const char *getS (lua_State *L, void *ud, size_t *size) {
  610. LoadS *ls = (LoadS *)ud;
  611. (void)L; /* not used */
  612. if (ls->size == 0) return NULL;
  613. *size = ls->size;
  614. ls->size = 0;
  615. return ls->s;
  616. }
  617. LUALIB_API int luaL_loadbufferx (lua_State *L, const char *buff, size_t size,
  618. const char *name, const char *mode) {
  619. LoadS ls;
  620. ls.s = buff;
  621. ls.size = size;
  622. return lua_load(L, getS, &ls, name, mode);
  623. }
  624. LUALIB_API int luaL_loadstring (lua_State *L, const char *s) {
  625. return luaL_loadbuffer(L, s, strlen(s), s);
  626. }
  627. /* }====================================================== */
  628. LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {
  629. if (!lua_getmetatable(L, obj)) /* no metatable? */
  630. return LUA_TNIL;
  631. else {
  632. int tt;
  633. lua_pushstring(L, event);
  634. tt = lua_rawget(L, -2);
  635. if (tt == LUA_TNIL) /* is metafield nil? */
  636. lua_pop(L, 2); /* remove metatable and metafield */
  637. else
  638. lua_remove(L, -2); /* remove only metatable */
  639. return tt; /* return metafield type */
  640. }
  641. }
  642. LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {
  643. obj = lua_absindex(L, obj);
  644. if (luaL_getmetafield(L, obj, event) == LUA_TNIL) /* no metafield? */
  645. return 0;
  646. lua_pushvalue(L, obj);
  647. lua_call(L, 1, 1);
  648. return 1;
  649. }
  650. LUALIB_API lua_Integer luaL_len (lua_State *L, int idx) {
  651. lua_Integer l;
  652. int isnum;
  653. lua_len(L, idx);
  654. l = lua_tointegerx(L, -1, &isnum);
  655. if (!isnum)
  656. luaL_error(L, "object length is not an integer");
  657. lua_pop(L, 1); /* remove object */
  658. return l;
  659. }
  660. LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) {
  661. if (luaL_callmeta(L, idx, "__tostring")) { /* metafield? */
  662. if (!lua_isstring(L, -1))
  663. luaL_error(L, "'__tostring' must return a string");
  664. }
  665. else {
  666. switch (lua_type(L, idx)) {
  667. case LUA_TNUMBER: {
  668. if (lua_isinteger(L, idx))
  669. lua_pushfstring(L, "%I", (LUAI_UACINT)lua_tointeger(L, idx));
  670. else
  671. lua_pushfstring(L, "%f", (LUAI_UACNUMBER)lua_tonumber(L, idx));
  672. break;
  673. }
  674. case LUA_TSTRING:
  675. lua_pushvalue(L, idx);
  676. break;
  677. case LUA_TBOOLEAN:
  678. lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false"));
  679. break;
  680. case LUA_TNIL:
  681. lua_pushliteral(L, "nil");
  682. break;
  683. default: {
  684. int tt = luaL_getmetafield(L, idx, "__name"); /* try name */
  685. const char *kind = (tt == LUA_TSTRING) ? lua_tostring(L, -1) :
  686. luaL_typename(L, idx);
  687. lua_pushfstring(L, "%s: %p", kind, lua_topointer(L, idx));
  688. if (tt != LUA_TNIL)
  689. lua_remove(L, -2); /* remove '__name' */
  690. break;
  691. }
  692. }
  693. }
  694. return lua_tolstring(L, -1, len);
  695. }
  696. /*
  697. ** {======================================================
  698. ** Compatibility with 5.1 module functions
  699. ** =======================================================
  700. */
  701. #if defined(LUA_COMPAT_MODULE)
  702. static const char *luaL_findtable (lua_State *L, int idx,
  703. const char *fname, int szhint) {
  704. const char *e;
  705. if (idx) lua_pushvalue(L, idx);
  706. do {
  707. e = strchr(fname, '.');
  708. if (e == NULL) e = fname + strlen(fname);
  709. lua_pushlstring(L, fname, e - fname);
  710. if (lua_rawget(L, -2) == LUA_TNIL) { /* no such field? */
  711. lua_pop(L, 1); /* remove this nil */
  712. lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */
  713. lua_pushlstring(L, fname, e - fname);
  714. lua_pushvalue(L, -2);
  715. lua_settable(L, -4); /* set new table into field */
  716. }
  717. else if (!lua_istable(L, -1)) { /* field has a non-table value? */
  718. lua_pop(L, 2); /* remove table and value */
  719. return fname; /* return problematic part of the name */
  720. }
  721. lua_remove(L, -2); /* remove previous table */
  722. fname = e + 1;
  723. } while (*e == '.');
  724. return NULL;
  725. }
  726. /*
  727. ** Count number of elements in a luaL_Reg list.
  728. */
  729. static int libsize (const luaL_Reg *l) {
  730. int size = 0;
  731. for (; l && l->name; l++) size++;
  732. return size;
  733. }
  734. /*
  735. ** Find or create a module table with a given name. The function
  736. ** first looks at the LOADED table and, if that fails, try a
  737. ** global variable with that name. In any case, leaves on the stack
  738. ** the module table.
  739. */
  740. LUALIB_API void luaL_pushmodule (lua_State *L, const char *modname,
  741. int sizehint) {
  742. luaL_findtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE, 1);
  743. if (lua_getfield(L, -1, modname) != LUA_TTABLE) { /* no LOADED[modname]? */
  744. lua_pop(L, 1); /* remove previous result */
  745. /* try global variable (and create one if it does not exist) */
  746. lua_pushglobaltable(L);
  747. if (luaL_findtable(L, 0, modname, sizehint) != NULL)
  748. luaL_error(L, "name conflict for module '%s'", modname);
  749. lua_pushvalue(L, -1);
  750. lua_setfield(L, -3, modname); /* LOADED[modname] = new table */
  751. }
  752. lua_remove(L, -2); /* remove LOADED table */
  753. }
  754. LUALIB_API void luaL_openlib (lua_State *L, const char *libname,
  755. const luaL_Reg *l, int nup) {
  756. luaL_checkversion(L);
  757. if (libname) {
  758. luaL_pushmodule(L, libname, libsize(l)); /* get/create library table */
  759. lua_insert(L, -(nup + 1)); /* move library table to below upvalues */
  760. }
  761. if (l)
  762. luaL_setfuncs(L, l, nup);
  763. else
  764. lua_pop(L, nup); /* remove upvalues */
  765. }
  766. #endif
  767. /* }====================================================== */
  768. /*
  769. ** set functions from list 'l' into table at top - 'nup'; each
  770. ** function gets the 'nup' elements at the top as upvalues.
  771. ** Returns with only the table at the stack.
  772. */
  773. LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) {
  774. luaL_checkstack(L, nup, "too many upvalues");
  775. for (; l->name != NULL; l++) { /* fill the table with given functions */
  776. int i;
  777. for (i = 0; i < nup; i++) /* copy upvalues to the top */
  778. lua_pushvalue(L, -nup);
  779. lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */
  780. lua_setfield(L, -(nup + 2), l->name);
  781. }
  782. lua_pop(L, nup); /* remove upvalues */
  783. }
  784. /*
  785. ** ensure that stack[idx][fname] has a table and push that table
  786. ** into the stack
  787. */
  788. LUALIB_API int luaL_getsubtable (lua_State *L, int idx, const char *fname) {
  789. if (lua_getfield(L, idx, fname) == LUA_TTABLE)
  790. return 1; /* table already there */
  791. else {
  792. lua_pop(L, 1); /* remove previous result */
  793. idx = lua_absindex(L, idx);
  794. lua_newtable(L);
  795. lua_pushvalue(L, -1); /* copy to be left at top */
  796. lua_setfield(L, idx, fname); /* assign new table to field */
  797. return 0; /* false, because did not find table there */
  798. }
  799. }
  800. /*
  801. ** Stripped-down 'require': After checking "loaded" table, calls 'openf'
  802. ** to open a module, registers the result in 'package.loaded' table and,
  803. ** if 'glb' is true, also registers the result in the global table.
  804. ** Leaves resulting module on the top.
  805. */
  806. LUALIB_API void luaL_requiref (lua_State *L, const char *modname,
  807. lua_CFunction openf, int glb) {
  808. luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);
  809. lua_getfield(L, -1, modname); /* LOADED[modname] */
  810. if (!lua_toboolean(L, -1)) { /* package not already loaded? */
  811. lua_pop(L, 1); /* remove field */
  812. lua_pushcfunction(L, openf);
  813. lua_pushstring(L, modname); /* argument to open function */
  814. lua_call(L, 1, 1); /* call 'openf' to open module */
  815. lua_pushvalue(L, -1); /* make copy of module (call result) */
  816. lua_setfield(L, -3, modname); /* LOADED[modname] = module */
  817. }
  818. lua_remove(L, -2); /* remove LOADED table */
  819. if (glb) {
  820. lua_pushvalue(L, -1); /* copy of module */
  821. lua_setglobal(L, modname); /* _G[modname] = module */
  822. }
  823. }
  824. LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p,
  825. const char *r) {
  826. const char *wild;
  827. size_t l = strlen(p);
  828. luaL_Buffer b;
  829. luaL_buffinit(L, &b);
  830. while ((wild = strstr(s, p)) != NULL) {
  831. luaL_addlstring(&b, s, wild - s); /* push prefix */
  832. luaL_addstring(&b, r); /* push replacement in place of pattern */
  833. s = wild + l; /* continue after 'p' */
  834. }
  835. luaL_addstring(&b, s); /* push last suffix */
  836. luaL_pushresult(&b);
  837. return lua_tostring(L, -1);
  838. }
  839. static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
  840. (void)ud; (void)osize; /* not used */
  841. if (nsize == 0) {
  842. free(ptr);
  843. return NULL;
  844. }
  845. else
  846. return realloc(ptr, nsize);
  847. }
  848. static int panic (lua_State *L) {
  849. lua_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n",
  850. lua_tostring(L, -1));
  851. return 0; /* return to Lua to abort */
  852. }
  853. LUALIB_API lua_State *luaL_newstate (void) {
  854. lua_State *L = lua_newstate(l_alloc, NULL);
  855. if (L) lua_atpanic(L, &panic);
  856. return L;
  857. }
  858. LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver, size_t sz) {
  859. const lua_Number *v = lua_version(L);
  860. if (sz != LUAL_NUMSIZES) /* check numeric types */
  861. luaL_error(L, "core and library have incompatible numeric types");
  862. if (v != lua_version(NULL))
  863. luaL_error(L, "multiple Lua VMs detected");
  864. else if (*v != ver)
  865. luaL_error(L, "version mismatch: app. needs %f, Lua core provides %f",
  866. (LUAI_UACNUMBER)ver, (LUAI_UACNUMBER)*v);
  867. }