lauxlib.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956
  1. /*
  2. ** $Id: lauxlib.c,v 1.232 2011/05/03 16:01:57 roberto Exp roberto $
  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. int found = 0;
  31. if (level == 0 || !lua_istable(L, -1))
  32. return 0; /* not found */
  33. lua_pushnil(L); /* start 'next' loop */
  34. while (!found && 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. static int pushglobalfuncname (lua_State *L, lua_Debug *ar) {
  53. int top = lua_gettop(L);
  54. lua_getinfo(L, "f", ar); /* push function */
  55. lua_pushglobaltable(L);
  56. if (findfield(L, top + 1, 2)) {
  57. lua_copy(L, -1, top + 1); /* move name to proper place */
  58. lua_pop(L, 2); /* remove pushed values */
  59. return 1;
  60. }
  61. else {
  62. lua_settop(L, top); /* remove function and global table */
  63. return 0;
  64. }
  65. }
  66. static void pushfuncname (lua_State *L, lua_Debug *ar) {
  67. if (*ar->namewhat != '\0') /* is there a name? */
  68. lua_pushfstring(L, "function " LUA_QS, ar->name);
  69. else if (*ar->what == 'm') /* main? */
  70. lua_pushfstring(L, "main chunk");
  71. else if (*ar->what == 'C' || *ar->what == 't') {
  72. if (pushglobalfuncname(L, ar)) {
  73. lua_pushfstring(L, "function " LUA_QS, lua_tostring(L, -1));
  74. lua_remove(L, -2); /* remove name */
  75. }
  76. else
  77. lua_pushliteral(L, "?");
  78. }
  79. else
  80. lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined);
  81. }
  82. static int countlevels (lua_State *L) {
  83. lua_Debug ar;
  84. int li = 1, le = 1;
  85. /* find an upper bound */
  86. while (lua_getstack(L, le, &ar)) { li = le; le *= 2; }
  87. /* do a binary search */
  88. while (li < le) {
  89. int m = (li + le)/2;
  90. if (lua_getstack(L, m, &ar)) li = m + 1;
  91. else le = m;
  92. }
  93. return le - 1;
  94. }
  95. LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1,
  96. const char *msg, int level) {
  97. lua_Debug ar;
  98. int top = lua_gettop(L);
  99. int numlevels = countlevels(L1);
  100. int mark = (numlevels > LEVELS1 + LEVELS2) ? LEVELS1 : 0;
  101. if (msg) lua_pushfstring(L, "%s\n", msg);
  102. lua_pushliteral(L, "stack traceback:");
  103. while (lua_getstack(L1, level++, &ar)) {
  104. if (level == mark) { /* too many levels? */
  105. lua_pushliteral(L, "\n\t..."); /* add a '...' */
  106. level = numlevels - LEVELS2; /* and skip to last ones */
  107. }
  108. else {
  109. lua_getinfo(L1, "Slnt", &ar);
  110. lua_pushfstring(L, "\n\t%s:", ar.short_src);
  111. if (ar.currentline > 0)
  112. lua_pushfstring(L, "%d:", ar.currentline);
  113. lua_pushliteral(L, " in ");
  114. pushfuncname(L, &ar);
  115. if (ar.istailcall)
  116. lua_pushliteral(L, "\n\t(...tail calls...)");
  117. lua_concat(L, lua_gettop(L) - top);
  118. }
  119. }
  120. lua_concat(L, lua_gettop(L) - top);
  121. }
  122. /* }====================================================== */
  123. /*
  124. ** {======================================================
  125. ** Error-report functions
  126. ** =======================================================
  127. */
  128. LUALIB_API int luaL_argerror (lua_State *L, int narg, const char *extramsg) {
  129. lua_Debug ar;
  130. if (!lua_getstack(L, 0, &ar)) /* no stack frame? */
  131. return luaL_error(L, "bad argument #%d (%s)", narg, extramsg);
  132. lua_getinfo(L, "n", &ar);
  133. if (strcmp(ar.namewhat, "method") == 0) {
  134. narg--; /* do not count `self' */
  135. if (narg == 0) /* error is in the self argument itself? */
  136. return luaL_error(L, "calling " LUA_QS " on bad self", ar.name);
  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_pushfstring(L, "%s", 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. lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get registry.name */
  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. lua_getfield(L, LUA_REGISTRYINDEX, 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. if (!lua_checkstack(L, space)) {
  272. if (msg)
  273. luaL_error(L, "stack overflow (%s)", msg);
  274. else
  275. luaL_error(L, "stack overflow");
  276. }
  277. }
  278. LUALIB_API void luaL_checktype (lua_State *L, int narg, int t) {
  279. if (lua_type(L, narg) != t)
  280. tag_error(L, narg, t);
  281. }
  282. LUALIB_API void luaL_checkany (lua_State *L, int narg) {
  283. if (lua_type(L, narg) == LUA_TNONE)
  284. luaL_argerror(L, narg, "value expected");
  285. }
  286. LUALIB_API const char *luaL_checklstring (lua_State *L, int narg, size_t *len) {
  287. const char *s = lua_tolstring(L, narg, len);
  288. if (!s) tag_error(L, narg, LUA_TSTRING);
  289. return s;
  290. }
  291. LUALIB_API const char *luaL_optlstring (lua_State *L, int narg,
  292. const char *def, size_t *len) {
  293. if (lua_isnoneornil(L, narg)) {
  294. if (len)
  295. *len = (def ? strlen(def) : 0);
  296. return def;
  297. }
  298. else return luaL_checklstring(L, narg, len);
  299. }
  300. LUALIB_API lua_Number luaL_checknumber (lua_State *L, int narg) {
  301. int isnum;
  302. lua_Number d = lua_tonumberx(L, narg, &isnum);
  303. if (!isnum)
  304. tag_error(L, narg, LUA_TNUMBER);
  305. return d;
  306. }
  307. LUALIB_API lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number def) {
  308. return luaL_opt(L, luaL_checknumber, narg, def);
  309. }
  310. LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int narg) {
  311. int isnum;
  312. lua_Integer d = lua_tointegerx(L, narg, &isnum);
  313. if (!isnum)
  314. tag_error(L, narg, LUA_TNUMBER);
  315. return d;
  316. }
  317. LUALIB_API lua_Unsigned luaL_checkunsigned (lua_State *L, int narg) {
  318. int isnum;
  319. lua_Unsigned d = lua_tounsignedx(L, narg, &isnum);
  320. if (!isnum)
  321. tag_error(L, narg, LUA_TNUMBER);
  322. return d;
  323. }
  324. LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int narg,
  325. lua_Integer def) {
  326. return luaL_opt(L, luaL_checkinteger, narg, def);
  327. }
  328. LUALIB_API lua_Unsigned luaL_optunsigned (lua_State *L, int narg,
  329. lua_Unsigned def) {
  330. return luaL_opt(L, luaL_checkunsigned, narg, def);
  331. }
  332. /* }====================================================== */
  333. /*
  334. ** {======================================================
  335. ** Generic Buffer manipulation
  336. ** =======================================================
  337. */
  338. /*
  339. ** check whether buffer is using a userdata on the stack as a temporary
  340. ** buffer
  341. */
  342. #define buffonstack(B) ((B)->b != (B)->initb)
  343. /*
  344. ** returns a pointer to a free area with at least 'sz' bytes
  345. */
  346. LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) {
  347. lua_State *L = B->L;
  348. if (B->size - B->n < sz) { /* not enough space? */
  349. char *newbuff;
  350. size_t newsize = B->size * 2; /* double buffer size */
  351. if (newsize - B->n < sz) /* not bit enough? */
  352. newsize = B->n + sz;
  353. if (newsize < B->n || newsize - B->n < sz)
  354. luaL_error(L, "buffer too large");
  355. /* create larger buffer */
  356. newbuff = (char *)lua_newuserdata(L, newsize * sizeof(char));
  357. /* move content to new buffer */
  358. memcpy(newbuff, B->b, B->n * sizeof(char));
  359. if (buffonstack(B))
  360. lua_remove(L, -2); /* remove old buffer */
  361. B->b = newbuff;
  362. B->size = newsize;
  363. }
  364. return &B->b[B->n];
  365. }
  366. LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
  367. char *b = luaL_prepbuffsize(B, l);
  368. memcpy(b, s, l * sizeof(char));
  369. luaL_addsize(B, l);
  370. }
  371. LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {
  372. luaL_addlstring(B, s, strlen(s));
  373. }
  374. LUALIB_API void luaL_pushresult (luaL_Buffer *B) {
  375. lua_State *L = B->L;
  376. lua_pushlstring(L, B->b, B->n);
  377. if (buffonstack(B))
  378. lua_remove(L, -2); /* remove old buffer */
  379. }
  380. LUALIB_API void luaL_pushresultsize (luaL_Buffer *B, size_t sz) {
  381. luaL_addsize(B, sz);
  382. luaL_pushresult(B);
  383. }
  384. LUALIB_API void luaL_addvalue (luaL_Buffer *B) {
  385. lua_State *L = B->L;
  386. size_t l;
  387. const char *s = lua_tolstring(L, -1, &l);
  388. if (buffonstack(B))
  389. lua_insert(L, -2); /* put value below buffer */
  390. luaL_addlstring(B, s, l);
  391. lua_remove(L, (buffonstack(B)) ? -2 : -1); /* remove value */
  392. }
  393. LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {
  394. B->L = L;
  395. B->b = B->initb;
  396. B->n = 0;
  397. B->size = LUAL_BUFFERSIZE;
  398. }
  399. LUALIB_API char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz) {
  400. luaL_buffinit(L, B);
  401. return luaL_prepbuffsize(B, sz);
  402. }
  403. /* }====================================================== */
  404. /*
  405. ** {======================================================
  406. ** Reference system
  407. ** =======================================================
  408. */
  409. /* index of free-list header */
  410. #define freelist 0
  411. LUALIB_API int luaL_ref (lua_State *L, int t) {
  412. int ref;
  413. t = lua_absindex(L, t);
  414. if (lua_isnil(L, -1)) {
  415. lua_pop(L, 1); /* remove from stack */
  416. return LUA_REFNIL; /* `nil' has a unique fixed reference */
  417. }
  418. lua_rawgeti(L, t, freelist); /* get first free element */
  419. ref = (int)lua_tointeger(L, -1); /* ref = t[freelist] */
  420. lua_pop(L, 1); /* remove it from stack */
  421. if (ref != 0) { /* any free element? */
  422. lua_rawgeti(L, t, ref); /* remove it from list */
  423. lua_rawseti(L, t, freelist); /* (t[freelist] = t[ref]) */
  424. }
  425. else /* no free elements */
  426. ref = (int)lua_rawlen(L, t) + 1; /* get a new reference */
  427. lua_rawseti(L, t, ref);
  428. return ref;
  429. }
  430. LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
  431. if (ref >= 0) {
  432. t = lua_absindex(L, t);
  433. lua_rawgeti(L, t, freelist);
  434. lua_rawseti(L, t, ref); /* t[ref] = t[freelist] */
  435. lua_pushinteger(L, ref);
  436. lua_rawseti(L, t, freelist); /* t[freelist] = ref */
  437. }
  438. }
  439. /* }====================================================== */
  440. /*
  441. ** {======================================================
  442. ** Load functions
  443. ** =======================================================
  444. */
  445. typedef struct LoadF {
  446. int n; /* number of pre-read characters */
  447. FILE *f; /* file being read */
  448. char buff[LUAL_BUFFERSIZE]; /* area for reading file */
  449. } LoadF;
  450. static const char *getF (lua_State *L, void *ud, size_t *size) {
  451. LoadF *lf = (LoadF *)ud;
  452. (void)L;
  453. if (lf->n > 0) { /* are there pre-read characters to be read? */
  454. *size = lf->n; /* return them (chars already in buffer) */
  455. lf->n = 0; /* no more pre-read characters */
  456. }
  457. else { /* read a block from file */
  458. /* 'fread' can return > 0 *and* set the EOF flag. If next call to
  459. 'getF' called 'fread', it might still wait for user input.
  460. The next check avoids this problem. */
  461. if (feof(lf->f)) return NULL;
  462. *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f); /* read block */
  463. }
  464. return lf->buff;
  465. }
  466. static int errfile (lua_State *L, const char *what, int fnameindex) {
  467. const char *serr = strerror(errno);
  468. const char *filename = lua_tostring(L, fnameindex) + 1;
  469. lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr);
  470. lua_remove(L, fnameindex);
  471. return LUA_ERRFILE;
  472. }
  473. static int skipBOM (LoadF *lf) {
  474. const char *p = "\xEF\xBB\xBF"; /* Utf8 BOM mark */
  475. int c;
  476. lf->n = 0;
  477. do {
  478. c = getc(lf->f);
  479. if (c == EOF || c != *(unsigned char *)p++) return c;
  480. lf->buff[lf->n++] = c; /* to be read by the parser */
  481. } while (*p != '\0');
  482. lf->n = 0; /* prefix matched; discard it */
  483. return getc(lf->f); /* return next character */
  484. }
  485. /*
  486. ** reads the first character of file 'f' and skips an optional BOM mark
  487. ** in its beginning plus its first line if it starts with '#'. Returns
  488. ** true if it skipped the first line. In any case, '*cp' has the
  489. ** first "valid" character of the file (after the optional BOM and
  490. ** a first-line comment).
  491. */
  492. static int skipcomment (LoadF *lf, int *cp) {
  493. int c = *cp = skipBOM(lf);
  494. if (c == '#') { /* first line is a comment (Unix exec. file)? */
  495. while ((c = getc(lf->f)) != EOF && c != '\n') ; /* skip first line */
  496. *cp = getc(lf->f); /* skip end-of-line */
  497. return 1; /* there was a comment */
  498. }
  499. else return 0; /* no comment */
  500. }
  501. LUALIB_API int luaL_loadfile (lua_State *L, const char *filename) {
  502. LoadF lf;
  503. int status, readstatus;
  504. int c;
  505. int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */
  506. if (filename == NULL) {
  507. lua_pushliteral(L, "=stdin");
  508. lf.f = stdin;
  509. }
  510. else {
  511. lua_pushfstring(L, "@%s", filename);
  512. lf.f = fopen(filename, "r");
  513. if (lf.f == NULL) return errfile(L, "open", fnameindex);
  514. }
  515. if (skipcomment(&lf, &c)) /* read initial portion */
  516. lf.buff[lf.n++] = '\n'; /* add line to correct line numbers */
  517. if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */
  518. lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */
  519. if (lf.f == NULL) return errfile(L, "reopen", fnameindex);
  520. skipcomment(&lf, &c); /* re-read initial portion */
  521. }
  522. if (c != EOF)
  523. lf.buff[lf.n++] = c; /* 'c' is the first character of the stream */
  524. status = lua_load(L, getF, &lf, lua_tostring(L, -1));
  525. readstatus = ferror(lf.f);
  526. if (filename) fclose(lf.f); /* close file (even in case of errors) */
  527. if (readstatus) {
  528. lua_settop(L, fnameindex); /* ignore results from `lua_load' */
  529. return errfile(L, "read", fnameindex);
  530. }
  531. lua_remove(L, fnameindex);
  532. return status;
  533. }
  534. typedef struct LoadS {
  535. const char *s;
  536. size_t size;
  537. } LoadS;
  538. static const char *getS (lua_State *L, void *ud, size_t *size) {
  539. LoadS *ls = (LoadS *)ud;
  540. (void)L;
  541. if (ls->size == 0) return NULL;
  542. *size = ls->size;
  543. ls->size = 0;
  544. return ls->s;
  545. }
  546. LUALIB_API int luaL_loadbuffer (lua_State *L, const char *buff, size_t size,
  547. const char *name) {
  548. LoadS ls;
  549. ls.s = buff;
  550. ls.size = size;
  551. return lua_load(L, getS, &ls, name);
  552. }
  553. LUALIB_API int luaL_loadstring (lua_State *L, const char *s) {
  554. return luaL_loadbuffer(L, s, strlen(s), s);
  555. }
  556. /* }====================================================== */
  557. LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {
  558. if (!lua_getmetatable(L, obj)) /* no metatable? */
  559. return 0;
  560. lua_pushstring(L, event);
  561. lua_rawget(L, -2);
  562. if (lua_isnil(L, -1)) {
  563. lua_pop(L, 2); /* remove metatable and metafield */
  564. return 0;
  565. }
  566. else {
  567. lua_remove(L, -2); /* remove only metatable */
  568. return 1;
  569. }
  570. }
  571. LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {
  572. obj = lua_absindex(L, obj);
  573. if (!luaL_getmetafield(L, obj, event)) /* no metafield? */
  574. return 0;
  575. lua_pushvalue(L, obj);
  576. lua_call(L, 1, 1);
  577. return 1;
  578. }
  579. LUALIB_API int luaL_len (lua_State *L, int idx) {
  580. int l;
  581. int isnum;
  582. lua_len(L, idx);
  583. l = (int)lua_tointegerx(L, -1, &isnum);
  584. if (!isnum)
  585. luaL_error(L, "object length is not a number");
  586. lua_pop(L, 1); /* remove object */
  587. return l;
  588. }
  589. LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) {
  590. if (!luaL_callmeta(L, idx, "__tostring")) { /* no metafield? */
  591. switch (lua_type(L, idx)) {
  592. case LUA_TNUMBER:
  593. case LUA_TSTRING:
  594. lua_pushvalue(L, idx);
  595. break;
  596. case LUA_TBOOLEAN:
  597. lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false"));
  598. break;
  599. case LUA_TNIL:
  600. lua_pushliteral(L, "nil");
  601. break;
  602. default:
  603. lua_pushfstring(L, "%s: %p", luaL_typename(L, idx),
  604. lua_topointer(L, idx));
  605. break;
  606. }
  607. }
  608. return lua_tolstring(L, -1, len);
  609. }
  610. /*
  611. ** {======================================================
  612. ** Compatibility with 5.1 module functions
  613. ** =======================================================
  614. */
  615. #if defined(LUA_COMPAT_MODULE)
  616. static const char *luaL_findtable (lua_State *L, int idx,
  617. const char *fname, int szhint) {
  618. const char *e;
  619. if (idx) lua_pushvalue(L, idx);
  620. do {
  621. e = strchr(fname, '.');
  622. if (e == NULL) e = fname + strlen(fname);
  623. lua_pushlstring(L, fname, e - fname);
  624. lua_rawget(L, -2);
  625. if (lua_isnil(L, -1)) { /* no such field? */
  626. lua_pop(L, 1); /* remove this nil */
  627. lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */
  628. lua_pushlstring(L, fname, e - fname);
  629. lua_pushvalue(L, -2);
  630. lua_settable(L, -4); /* set new table into field */
  631. }
  632. else if (!lua_istable(L, -1)) { /* field has a non-table value? */
  633. lua_pop(L, 2); /* remove table and value */
  634. return fname; /* return problematic part of the name */
  635. }
  636. lua_remove(L, -2); /* remove previous table */
  637. fname = e + 1;
  638. } while (*e == '.');
  639. return NULL;
  640. }
  641. /*
  642. ** Count number of elements in a luaL_Reg list.
  643. */
  644. static int libsize (const luaL_Reg *l) {
  645. int size = 0;
  646. for (; l && l->name; l++) size++;
  647. return size;
  648. }
  649. /*
  650. ** Find or create a module table with a given name. The function
  651. ** first looks at the _LOADED table and, if that fails, try a
  652. ** global variable with that name. In any case, leaves on the stack
  653. ** the module table.
  654. */
  655. LUALIB_API void luaL_pushmodule (lua_State *L, const char *modname,
  656. int sizehint) {
  657. luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 1); /* get _LOADED table */
  658. lua_getfield(L, -1, modname); /* get _LOADED[modname] */
  659. if (!lua_istable(L, -1)) { /* not found? */
  660. lua_pop(L, 1); /* remove previous result */
  661. /* try global variable (and create one if it does not exist) */
  662. lua_pushglobaltable(L);
  663. if (luaL_findtable(L, 0, modname, sizehint) != NULL)
  664. luaL_error(L, "name conflict for module " LUA_QS, modname);
  665. lua_pushvalue(L, -1);
  666. lua_setfield(L, -3, modname); /* _LOADED[modname] = new table */
  667. }
  668. lua_remove(L, -2); /* remove _LOADED table */
  669. }
  670. LUALIB_API void luaL_openlib (lua_State *L, const char *libname,
  671. const luaL_Reg *l, int nup) {
  672. luaL_checkversion(L);
  673. if (libname) {
  674. luaL_pushmodule(L, libname, libsize(l)); /* get/create library table */
  675. lua_insert(L, -(nup + 1)); /* move library table to below upvalues */
  676. }
  677. if (l)
  678. luaL_setfuncs(L, l, nup);
  679. else
  680. lua_pop(L, nup); /* remove upvalues */
  681. }
  682. #endif
  683. /* }====================================================== */
  684. /*
  685. ** set functions from list 'l' into table at top - 'nup'; each
  686. ** function gets the 'nup' elements at the top as upvalues.
  687. ** Returns with only the table at the stack.
  688. */
  689. LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) {
  690. luaL_checkstack(L, nup, "too many upvalues");
  691. for (; l->name != NULL; l++) { /* fill the table with given functions */
  692. int i;
  693. for (i = 0; i < nup; i++) /* copy upvalues to the top */
  694. lua_pushvalue(L, -nup);
  695. lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */
  696. lua_setfield(L, -(nup + 2), l->name);
  697. }
  698. lua_pop(L, nup); /* remove upvalues */
  699. }
  700. /*
  701. ** ensure that stack[idx][fname] has a table and push that table
  702. ** into the stack
  703. */
  704. LUALIB_API int luaL_getsubtable (lua_State *L, int idx, const char *fname) {
  705. lua_getfield(L, idx, fname);
  706. if (lua_istable(L, -1)) return 1; /* table already there */
  707. else {
  708. idx = lua_absindex(L, idx);
  709. lua_pop(L, 1); /* remove previous result */
  710. lua_newtable(L);
  711. lua_pushvalue(L, -1); /* copy to be left at top */
  712. lua_setfield(L, idx, fname); /* assign new table to field */
  713. return 0; /* false, because did not find table there */
  714. }
  715. }
  716. /*
  717. ** stripped-down 'require'. Calls 'openf' to open a module,
  718. ** registers the result in 'package.loaded' table and, if 'glb'
  719. ** is true, also registers the result in the global table.
  720. ** Leaves resulting module on the top.
  721. */
  722. LUALIB_API void luaL_requiref (lua_State *L, const char *modname,
  723. lua_CFunction openf, int glb) {
  724. lua_pushcfunction(L, openf);
  725. lua_pushstring(L, modname); /* argument to open function */
  726. lua_call(L, 1, 1); /* open module */
  727. luaL_getsubtable(L, LUA_REGISTRYINDEX, "_LOADED");
  728. lua_pushvalue(L, -2); /* make copy of module (call result) */
  729. lua_setfield(L, -2, modname); /* _LOADED[modname] = module */
  730. lua_pop(L, 1); /* remove _LOADED table */
  731. if (glb) {
  732. lua_pushglobaltable(L);
  733. lua_pushvalue(L, -2); /* copy of 'mod' */
  734. lua_setfield(L, -2, modname); /* _G[modname] = module */
  735. lua_pop(L, 1); /* remove _G table */
  736. }
  737. }
  738. LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p,
  739. const char *r) {
  740. const char *wild;
  741. size_t l = strlen(p);
  742. luaL_Buffer b;
  743. luaL_buffinit(L, &b);
  744. while ((wild = strstr(s, p)) != NULL) {
  745. luaL_addlstring(&b, s, wild - s); /* push prefix */
  746. luaL_addstring(&b, r); /* push replacement in place of pattern */
  747. s = wild + l; /* continue after `p' */
  748. }
  749. luaL_addstring(&b, s); /* push last suffix */
  750. luaL_pushresult(&b);
  751. return lua_tostring(L, -1);
  752. }
  753. static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
  754. (void)ud;
  755. (void)osize;
  756. if (nsize == 0) {
  757. free(ptr);
  758. return NULL;
  759. }
  760. else
  761. return realloc(ptr, nsize);
  762. }
  763. static int panic (lua_State *L) {
  764. luai_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n",
  765. lua_tostring(L, -1));
  766. return 0; /* return to Lua to abort */
  767. }
  768. LUALIB_API lua_State *luaL_newstate (void) {
  769. lua_State *L = lua_newstate(l_alloc, NULL);
  770. if (L) lua_atpanic(L, &panic);
  771. return L;
  772. }
  773. LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver) {
  774. const lua_Number *v = lua_version(L);
  775. if (v != lua_version(NULL))
  776. luaL_error(L, "multiple Lua VMs detected");
  777. else if (*v != ver)
  778. luaL_error(L, "version mismatch: app. needs %d, Lua core provides %f",
  779. ver, *v);
  780. /* check conversions number -> integer types */
  781. lua_pushnumber(L, -(lua_Number)0x1234);
  782. if (lua_tointeger(L, -1) != -0x1234 ||
  783. lua_tounsigned(L, -1) != (lua_Unsigned)-0x1234)
  784. luaL_error(L, "bad conversion number->int;"
  785. " must recompile Lua with proper settings");
  786. lua_pop(L, 1);
  787. }