Imported from ../lua-5.0.1.tar.gz.
[lua.git] / src / lib / lbaselib.c
blob45bc7cfe57f47277334a46df72ce1d2d75acf771
1 /*
2 ** $Id: lbaselib.c,v 1.130a 2003/04/03 13:35:34 roberto Exp $
3 ** Basic library
4 ** See Copyright Notice in lua.h
5 */
9 #include <ctype.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
14 #define lbaselib_c
16 #include "lua.h"
18 #include "lauxlib.h"
19 #include "lualib.h"
25 ** If your system does not support `stdout', you can just remove this function.
26 ** If you need, you can define your own `print' function, following this
27 ** model but changing `fputs' to put the strings at a proper place
28 ** (a console window or a log file, for instance).
30 static int luaB_print (lua_State *L) {
31 int n = lua_gettop(L); /* number of arguments */
32 int i;
33 lua_getglobal(L, "tostring");
34 for (i=1; i<=n; i++) {
35 const char *s;
36 lua_pushvalue(L, -1); /* function to be called */
37 lua_pushvalue(L, i); /* value to print */
38 lua_call(L, 1, 1);
39 s = lua_tostring(L, -1); /* get result */
40 if (s == NULL)
41 return luaL_error(L, "`tostring' must return a string to `print'");
42 if (i>1) fputs("\t", stdout);
43 fputs(s, stdout);
44 lua_pop(L, 1); /* pop result */
46 fputs("\n", stdout);
47 return 0;
51 static int luaB_tonumber (lua_State *L) {
52 int base = luaL_optint(L, 2, 10);
53 if (base == 10) { /* standard conversion */
54 luaL_checkany(L, 1);
55 if (lua_isnumber(L, 1)) {
56 lua_pushnumber(L, lua_tonumber(L, 1));
57 return 1;
60 else {
61 const char *s1 = luaL_checkstring(L, 1);
62 char *s2;
63 unsigned long n;
64 luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range");
65 n = strtoul(s1, &s2, base);
66 if (s1 != s2) { /* at least one valid digit? */
67 while (isspace((unsigned char)(*s2))) s2++; /* skip trailing spaces */
68 if (*s2 == '\0') { /* no invalid trailing characters? */
69 lua_pushnumber(L, (lua_Number)n);
70 return 1;
74 lua_pushnil(L); /* else not a number */
75 return 1;
79 static int luaB_error (lua_State *L) {
80 int level = luaL_optint(L, 2, 1);
81 luaL_checkany(L, 1);
82 if (!lua_isstring(L, 1) || level == 0)
83 lua_pushvalue(L, 1); /* propagate error message without changes */
84 else { /* add extra information */
85 luaL_where(L, level);
86 lua_pushvalue(L, 1);
87 lua_concat(L, 2);
89 return lua_error(L);
93 static int luaB_getmetatable (lua_State *L) {
94 luaL_checkany(L, 1);
95 if (!lua_getmetatable(L, 1)) {
96 lua_pushnil(L);
97 return 1; /* no metatable */
99 luaL_getmetafield(L, 1, "__metatable");
100 return 1; /* returns either __metatable field (if present) or metatable */
104 static int luaB_setmetatable (lua_State *L) {
105 int t = lua_type(L, 2);
106 luaL_checktype(L, 1, LUA_TTABLE);
107 luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2,
108 "nil or table expected");
109 if (luaL_getmetafield(L, 1, "__metatable"))
110 luaL_error(L, "cannot change a protected metatable");
111 lua_settop(L, 2);
112 lua_setmetatable(L, 1);
113 return 1;
117 static void getfunc (lua_State *L) {
118 if (lua_isfunction(L, 1)) lua_pushvalue(L, 1);
119 else {
120 lua_Debug ar;
121 int level = luaL_optint(L, 1, 1);
122 luaL_argcheck(L, level >= 0, 1, "level must be non-negative");
123 if (lua_getstack(L, level, &ar) == 0)
124 luaL_argerror(L, 1, "invalid level");
125 lua_getinfo(L, "f", &ar);
126 if (lua_isnil(L, -1))
127 luaL_error(L, "no function environment for tail call at level %d",
128 level);
133 static int aux_getfenv (lua_State *L) {
134 lua_getfenv(L, -1);
135 lua_pushliteral(L, "__fenv");
136 lua_rawget(L, -2);
137 return !lua_isnil(L, -1);
141 static int luaB_getfenv (lua_State *L) {
142 getfunc(L);
143 if (!aux_getfenv(L)) /* __fenv not defined? */
144 lua_pop(L, 1); /* remove it, to return real environment */
145 return 1;
149 static int luaB_setfenv (lua_State *L) {
150 luaL_checktype(L, 2, LUA_TTABLE);
151 getfunc(L);
152 if (aux_getfenv(L)) /* __fenv defined? */
153 luaL_error(L, "`setfenv' cannot change a protected environment");
154 else
155 lua_pop(L, 2); /* remove __fenv and real environment table */
156 lua_pushvalue(L, 2);
157 if (lua_isnumber(L, 1) && lua_tonumber(L, 1) == 0)
158 lua_replace(L, LUA_GLOBALSINDEX);
159 else if (lua_setfenv(L, -2) == 0)
160 luaL_error(L, "`setfenv' cannot change environment of given function");
161 return 0;
165 static int luaB_rawequal (lua_State *L) {
166 luaL_checkany(L, 1);
167 luaL_checkany(L, 2);
168 lua_pushboolean(L, lua_rawequal(L, 1, 2));
169 return 1;
173 static int luaB_rawget (lua_State *L) {
174 luaL_checktype(L, 1, LUA_TTABLE);
175 luaL_checkany(L, 2);
176 lua_rawget(L, 1);
177 return 1;
180 static int luaB_rawset (lua_State *L) {
181 luaL_checktype(L, 1, LUA_TTABLE);
182 luaL_checkany(L, 2);
183 luaL_checkany(L, 3);
184 lua_rawset(L, 1);
185 return 1;
189 static int luaB_gcinfo (lua_State *L) {
190 lua_pushnumber(L, (lua_Number)lua_getgccount(L));
191 lua_pushnumber(L, (lua_Number)lua_getgcthreshold(L));
192 return 2;
196 static int luaB_collectgarbage (lua_State *L) {
197 lua_setgcthreshold(L, luaL_optint(L, 1, 0));
198 return 0;
202 static int luaB_type (lua_State *L) {
203 luaL_checkany(L, 1);
204 lua_pushstring(L, lua_typename(L, lua_type(L, 1)));
205 return 1;
209 static int luaB_next (lua_State *L) {
210 luaL_checktype(L, 1, LUA_TTABLE);
211 lua_settop(L, 2); /* create a 2nd argument if there isn't one */
212 if (lua_next(L, 1))
213 return 2;
214 else {
215 lua_pushnil(L);
216 return 1;
221 static int luaB_pairs (lua_State *L) {
222 luaL_checktype(L, 1, LUA_TTABLE);
223 lua_pushliteral(L, "next");
224 lua_rawget(L, LUA_GLOBALSINDEX); /* return generator, */
225 lua_pushvalue(L, 1); /* state, */
226 lua_pushnil(L); /* and initial value */
227 return 3;
231 static int luaB_ipairs (lua_State *L) {
232 lua_Number i = lua_tonumber(L, 2);
233 luaL_checktype(L, 1, LUA_TTABLE);
234 if (i == 0 && lua_isnone(L, 2)) { /* `for' start? */
235 lua_pushliteral(L, "ipairs");
236 lua_rawget(L, LUA_GLOBALSINDEX); /* return generator, */
237 lua_pushvalue(L, 1); /* state, */
238 lua_pushnumber(L, 0); /* and initial value */
239 return 3;
241 else { /* `for' step */
242 i++; /* next value */
243 lua_pushnumber(L, i);
244 lua_rawgeti(L, 1, (int)i);
245 return (lua_isnil(L, -1)) ? 0 : 2;
250 static int load_aux (lua_State *L, int status) {
251 if (status == 0) /* OK? */
252 return 1;
253 else {
254 lua_pushnil(L);
255 lua_insert(L, -2); /* put before error message */
256 return 2; /* return nil plus error message */
261 static int luaB_loadstring (lua_State *L) {
262 size_t l;
263 const char *s = luaL_checklstring(L, 1, &l);
264 const char *chunkname = luaL_optstring(L, 2, s);
265 return load_aux(L, luaL_loadbuffer(L, s, l, chunkname));
269 static int luaB_loadfile (lua_State *L) {
270 const char *fname = luaL_optstring(L, 1, NULL);
271 return load_aux(L, luaL_loadfile(L, fname));
275 static int luaB_dofile (lua_State *L) {
276 const char *fname = luaL_optstring(L, 1, NULL);
277 int status = luaL_loadfile(L, fname);
278 if (status != 0) lua_error(L);
279 lua_call(L, 0, LUA_MULTRET);
280 return lua_gettop(L) - 1;
284 static int luaB_assert (lua_State *L) {
285 luaL_checkany(L, 1);
286 if (!lua_toboolean(L, 1))
287 return luaL_error(L, "%s", luaL_optstring(L, 2, "assertion failed!"));
288 lua_settop(L, 1);
289 return 1;
293 static int luaB_unpack (lua_State *L) {
294 int n, i;
295 luaL_checktype(L, 1, LUA_TTABLE);
296 n = luaL_getn(L, 1);
297 luaL_checkstack(L, n, "table too big to unpack");
298 for (i=1; i<=n; i++) /* push arg[1...n] */
299 lua_rawgeti(L, 1, i);
300 return n;
304 static int luaB_pcall (lua_State *L) {
305 int status;
306 luaL_checkany(L, 1);
307 status = lua_pcall(L, lua_gettop(L) - 1, LUA_MULTRET, 0);
308 lua_pushboolean(L, (status == 0));
309 lua_insert(L, 1);
310 return lua_gettop(L); /* return status + all results */
314 static int luaB_xpcall (lua_State *L) {
315 int status;
316 luaL_checkany(L, 2);
317 lua_settop(L, 2);
318 lua_insert(L, 1); /* put error function under function to be called */
319 status = lua_pcall(L, 0, LUA_MULTRET, 1);
320 lua_pushboolean(L, (status == 0));
321 lua_replace(L, 1);
322 return lua_gettop(L); /* return status + all results */
326 static int luaB_tostring (lua_State *L) {
327 char buff[128];
328 luaL_checkany(L, 1);
329 if (luaL_callmeta(L, 1, "__tostring")) /* is there a metafield? */
330 return 1; /* use its value */
331 switch (lua_type(L, 1)) {
332 case LUA_TNUMBER:
333 lua_pushstring(L, lua_tostring(L, 1));
334 return 1;
335 case LUA_TSTRING:
336 lua_pushvalue(L, 1);
337 return 1;
338 case LUA_TBOOLEAN:
339 lua_pushstring(L, (lua_toboolean(L, 1) ? "true" : "false"));
340 return 1;
341 case LUA_TTABLE:
342 sprintf(buff, "table: %p", lua_topointer(L, 1));
343 break;
344 case LUA_TFUNCTION:
345 sprintf(buff, "function: %p", lua_topointer(L, 1));
346 break;
347 case LUA_TUSERDATA:
348 case LUA_TLIGHTUSERDATA:
349 sprintf(buff, "userdata: %p", lua_touserdata(L, 1));
350 break;
351 case LUA_TTHREAD:
352 sprintf(buff, "thread: %p", (void *)lua_tothread(L, 1));
353 break;
354 case LUA_TNIL:
355 lua_pushliteral(L, "nil");
356 return 1;
358 lua_pushstring(L, buff);
359 return 1;
363 static int luaB_newproxy (lua_State *L) {
364 lua_settop(L, 1);
365 lua_newuserdata(L, 0); /* create proxy */
366 if (lua_toboolean(L, 1) == 0)
367 return 1; /* no metatable */
368 else if (lua_isboolean(L, 1)) {
369 lua_newtable(L); /* create a new metatable `m' ... */
370 lua_pushvalue(L, -1); /* ... and mark `m' as a valid metatable */
371 lua_pushboolean(L, 1);
372 lua_rawset(L, lua_upvalueindex(1)); /* weaktable[m] = true */
374 else {
375 int validproxy = 0; /* to check if weaktable[metatable(u)] == true */
376 if (lua_getmetatable(L, 1)) {
377 lua_rawget(L, lua_upvalueindex(1));
378 validproxy = lua_toboolean(L, -1);
379 lua_pop(L, 1); /* remove value */
381 luaL_argcheck(L, validproxy, 1, "boolean or proxy expected");
382 lua_getmetatable(L, 1); /* metatable is valid; get it */
384 lua_setmetatable(L, 2);
385 return 1;
390 ** {======================================================
391 ** `require' function
392 ** =======================================================
396 /* name of global that holds table with loaded packages */
397 #define REQTAB "_LOADED"
399 /* name of global that holds the search path for packages */
400 #define LUA_PATH "LUA_PATH"
402 #ifndef LUA_PATH_SEP
403 #define LUA_PATH_SEP ';'
404 #endif
406 #ifndef LUA_PATH_MARK
407 #define LUA_PATH_MARK '?'
408 #endif
410 #ifndef LUA_PATH_DEFAULT
411 #define LUA_PATH_DEFAULT "?;?.lua"
412 #endif
415 static const char *getpath (lua_State *L) {
416 const char *path;
417 lua_getglobal(L, LUA_PATH); /* try global variable */
418 path = lua_tostring(L, -1);
419 lua_pop(L, 1);
420 if (path) return path;
421 path = getenv(LUA_PATH); /* else try environment variable */
422 if (path) return path;
423 return LUA_PATH_DEFAULT; /* else use default */
427 static const char *pushnextpath (lua_State *L, const char *path) {
428 const char *l;
429 if (*path == '\0') return NULL; /* no more paths */
430 if (*path == LUA_PATH_SEP) path++; /* skip separator */
431 l = strchr(path, LUA_PATH_SEP); /* find next separator */
432 if (l == NULL) l = path+strlen(path);
433 lua_pushlstring(L, path, l - path); /* directory name */
434 return l;
438 static void pushcomposename (lua_State *L) {
439 const char *path = lua_tostring(L, -1);
440 const char *wild;
441 int n = 1;
442 while ((wild = strchr(path, LUA_PATH_MARK)) != NULL) {
443 /* is there stack space for prefix, name, and eventual last sufix? */
444 luaL_checkstack(L, 3, "too many marks in a path component");
445 lua_pushlstring(L, path, wild - path); /* push prefix */
446 lua_pushvalue(L, 1); /* push package name (in place of MARK) */
447 path = wild + 1; /* continue after MARK */
448 n += 2;
450 lua_pushstring(L, path); /* push last sufix (`n' already includes this) */
451 lua_concat(L, n);
455 static int luaB_require (lua_State *L) {
456 const char *path;
457 int status = LUA_ERRFILE; /* not found (yet) */
458 luaL_checkstring(L, 1);
459 lua_settop(L, 1);
460 lua_getglobal(L, REQTAB);
461 if (!lua_istable(L, 2)) return luaL_error(L, "`" REQTAB "' is not a table");
462 path = getpath(L);
463 lua_pushvalue(L, 1); /* check package's name in book-keeping table */
464 lua_rawget(L, 2);
465 if (lua_toboolean(L, -1)) /* is it there? */
466 return 1; /* package is already loaded; return its result */
467 else { /* must load it */
468 while (status == LUA_ERRFILE) {
469 lua_settop(L, 3); /* reset stack position */
470 if ((path = pushnextpath(L, path)) == NULL) break;
471 pushcomposename(L);
472 status = luaL_loadfile(L, lua_tostring(L, -1)); /* try to load it */
475 switch (status) {
476 case 0: {
477 lua_getglobal(L, "_REQUIREDNAME"); /* save previous name */
478 lua_insert(L, -2); /* put it below function */
479 lua_pushvalue(L, 1);
480 lua_setglobal(L, "_REQUIREDNAME"); /* set new name */
481 lua_call(L, 0, 1); /* run loaded module */
482 lua_insert(L, -2); /* put result below previous name */
483 lua_setglobal(L, "_REQUIREDNAME"); /* reset to previous name */
484 if (lua_isnil(L, -1)) { /* no/nil return? */
485 lua_pushboolean(L, 1);
486 lua_replace(L, -2); /* replace to true */
488 lua_pushvalue(L, 1);
489 lua_pushvalue(L, -2);
490 lua_rawset(L, 2); /* mark it as loaded */
491 return 1; /* return value */
493 case LUA_ERRFILE: { /* file not found */
494 return luaL_error(L, "could not load package `%s' from path `%s'",
495 lua_tostring(L, 1), getpath(L));
497 default: {
498 return luaL_error(L, "error loading package `%s' (%s)",
499 lua_tostring(L, 1), lua_tostring(L, -1));
504 /* }====================================================== */
507 static const luaL_reg base_funcs[] = {
508 {"error", luaB_error},
509 {"getmetatable", luaB_getmetatable},
510 {"setmetatable", luaB_setmetatable},
511 {"getfenv", luaB_getfenv},
512 {"setfenv", luaB_setfenv},
513 {"next", luaB_next},
514 {"ipairs", luaB_ipairs},
515 {"pairs", luaB_pairs},
516 {"print", luaB_print},
517 {"tonumber", luaB_tonumber},
518 {"tostring", luaB_tostring},
519 {"type", luaB_type},
520 {"assert", luaB_assert},
521 {"unpack", luaB_unpack},
522 {"rawequal", luaB_rawequal},
523 {"rawget", luaB_rawget},
524 {"rawset", luaB_rawset},
525 {"pcall", luaB_pcall},
526 {"xpcall", luaB_xpcall},
527 {"collectgarbage", luaB_collectgarbage},
528 {"gcinfo", luaB_gcinfo},
529 {"loadfile", luaB_loadfile},
530 {"dofile", luaB_dofile},
531 {"loadstring", luaB_loadstring},
532 {"require", luaB_require},
533 {NULL, NULL}
538 ** {======================================================
539 ** Coroutine library
540 ** =======================================================
543 static int auxresume (lua_State *L, lua_State *co, int narg) {
544 int status;
545 if (!lua_checkstack(co, narg))
546 luaL_error(L, "too many arguments to resume");
547 lua_xmove(L, co, narg);
548 status = lua_resume(co, narg);
549 if (status == 0) {
550 int nres = lua_gettop(co);
551 if (!lua_checkstack(L, nres))
552 luaL_error(L, "too many results to resume");
553 lua_xmove(co, L, nres); /* move yielded values */
554 return nres;
556 else {
557 lua_xmove(co, L, 1); /* move error message */
558 return -1; /* error flag */
563 static int luaB_coresume (lua_State *L) {
564 lua_State *co = lua_tothread(L, 1);
565 int r;
566 luaL_argcheck(L, co, 1, "coroutine expected");
567 r = auxresume(L, co, lua_gettop(L) - 1);
568 if (r < 0) {
569 lua_pushboolean(L, 0);
570 lua_insert(L, -2);
571 return 2; /* return false + error message */
573 else {
574 lua_pushboolean(L, 1);
575 lua_insert(L, -(r + 1));
576 return r + 1; /* return true + `resume' returns */
581 static int luaB_auxwrap (lua_State *L) {
582 lua_State *co = lua_tothread(L, lua_upvalueindex(1));
583 int r = auxresume(L, co, lua_gettop(L));
584 if (r < 0) {
585 if (lua_isstring(L, -1)) { /* error object is a string? */
586 luaL_where(L, 1); /* add extra info */
587 lua_insert(L, -2);
588 lua_concat(L, 2);
590 lua_error(L); /* propagate error */
592 return r;
596 static int luaB_cocreate (lua_State *L) {
597 lua_State *NL = lua_newthread(L);
598 luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1), 1,
599 "Lua function expected");
600 lua_pushvalue(L, 1); /* move function to top */
601 lua_xmove(L, NL, 1); /* move function from L to NL */
602 return 1;
606 static int luaB_cowrap (lua_State *L) {
607 luaB_cocreate(L);
608 lua_pushcclosure(L, luaB_auxwrap, 1);
609 return 1;
613 static int luaB_yield (lua_State *L) {
614 return lua_yield(L, lua_gettop(L));
618 static int luaB_costatus (lua_State *L) {
619 lua_State *co = lua_tothread(L, 1);
620 luaL_argcheck(L, co, 1, "coroutine expected");
621 if (L == co) lua_pushliteral(L, "running");
622 else {
623 lua_Debug ar;
624 if (lua_getstack(co, 0, &ar) == 0 && lua_gettop(co) == 0)
625 lua_pushliteral(L, "dead");
626 else
627 lua_pushliteral(L, "suspended");
629 return 1;
633 static const luaL_reg co_funcs[] = {
634 {"create", luaB_cocreate},
635 {"wrap", luaB_cowrap},
636 {"resume", luaB_coresume},
637 {"yield", luaB_yield},
638 {"status", luaB_costatus},
639 {NULL, NULL}
642 /* }====================================================== */
646 static void base_open (lua_State *L) {
647 lua_pushliteral(L, "_G");
648 lua_pushvalue(L, LUA_GLOBALSINDEX);
649 luaL_openlib(L, NULL, base_funcs, 0); /* open lib into global table */
650 lua_pushliteral(L, "_VERSION");
651 lua_pushliteral(L, LUA_VERSION);
652 lua_rawset(L, -3); /* set global _VERSION */
653 /* `newproxy' needs a weaktable as upvalue */
654 lua_pushliteral(L, "newproxy");
655 lua_newtable(L); /* new table `w' */
656 lua_pushvalue(L, -1); /* `w' will be its own metatable */
657 lua_setmetatable(L, -2);
658 lua_pushliteral(L, "__mode");
659 lua_pushliteral(L, "k");
660 lua_rawset(L, -3); /* metatable(w).__mode = "k" */
661 lua_pushcclosure(L, luaB_newproxy, 1);
662 lua_rawset(L, -3); /* set global `newproxy' */
663 lua_rawset(L, -1); /* set global _G */
667 LUALIB_API int luaopen_base (lua_State *L) {
668 base_open(L);
669 luaL_openlib(L, LUA_COLIBNAME, co_funcs, 0);
670 lua_newtable(L);
671 lua_setglobal(L, REQTAB);
672 return 0;