lauxlib.c 27 KB

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