lauxlib.c 29 KB

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