lauxlib.c 29 KB

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