2 ** $Id: lbaselib.c,v 1.130a 2003/04/03 13:35:34 roberto Exp $
4 ** See Copyright Notice in lua.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 */
33 lua_getglobal(L
, "tostring");
34 for (i
=1; i
<=n
; i
++) {
36 lua_pushvalue(L
, -1); /* function to be called */
37 lua_pushvalue(L
, i
); /* value to print */
39 s
= lua_tostring(L
, -1); /* get result */
41 return luaL_error(L
, "`tostring' must return a string to `print'");
42 if (i
>1) fputs("\t", stdout
);
44 lua_pop(L
, 1); /* pop result */
51 static int luaB_tonumber (lua_State
*L
) {
52 int base
= luaL_optint(L
, 2, 10);
53 if (base
== 10) { /* standard conversion */
55 if (lua_isnumber(L
, 1)) {
56 lua_pushnumber(L
, lua_tonumber(L
, 1));
61 const char *s1
= luaL_checkstring(L
, 1);
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
);
74 lua_pushnil(L
); /* else not a number */
79 static int luaB_error (lua_State
*L
) {
80 int level
= luaL_optint(L
, 2, 1);
82 if (!lua_isstring(L
, 1) || level
== 0)
83 lua_pushvalue(L
, 1); /* propagate error message without changes */
84 else { /* add extra information */
93 static int luaB_getmetatable (lua_State
*L
) {
95 if (!lua_getmetatable(L
, 1)) {
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");
112 lua_setmetatable(L
, 1);
117 static void getfunc (lua_State
*L
) {
118 if (lua_isfunction(L
, 1)) lua_pushvalue(L
, 1);
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",
133 static int aux_getfenv (lua_State
*L
) {
135 lua_pushliteral(L
, "__fenv");
137 return !lua_isnil(L
, -1);
141 static int luaB_getfenv (lua_State
*L
) {
143 if (!aux_getfenv(L
)) /* __fenv not defined? */
144 lua_pop(L
, 1); /* remove it, to return real environment */
149 static int luaB_setfenv (lua_State
*L
) {
150 luaL_checktype(L
, 2, LUA_TTABLE
);
152 if (aux_getfenv(L
)) /* __fenv defined? */
153 luaL_error(L
, "`setfenv' cannot change a protected environment");
155 lua_pop(L
, 2); /* remove __fenv and real environment table */
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");
165 static int luaB_rawequal (lua_State
*L
) {
168 lua_pushboolean(L
, lua_rawequal(L
, 1, 2));
173 static int luaB_rawget (lua_State
*L
) {
174 luaL_checktype(L
, 1, LUA_TTABLE
);
180 static int luaB_rawset (lua_State
*L
) {
181 luaL_checktype(L
, 1, LUA_TTABLE
);
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
));
196 static int luaB_collectgarbage (lua_State
*L
) {
197 lua_setgcthreshold(L
, luaL_optint(L
, 1, 0));
202 static int luaB_type (lua_State
*L
) {
204 lua_pushstring(L
, lua_typename(L
, lua_type(L
, 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 */
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 */
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 */
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? */
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
) {
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
) {
286 if (!lua_toboolean(L
, 1))
287 return luaL_error(L
, "%s", luaL_optstring(L
, 2, "assertion failed!"));
293 static int luaB_unpack (lua_State
*L
) {
295 luaL_checktype(L
, 1, LUA_TTABLE
);
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
);
304 static int luaB_pcall (lua_State
*L
) {
307 status
= lua_pcall(L
, lua_gettop(L
) - 1, LUA_MULTRET
, 0);
308 lua_pushboolean(L
, (status
== 0));
310 return lua_gettop(L
); /* return status + all results */
314 static int luaB_xpcall (lua_State
*L
) {
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));
322 return lua_gettop(L
); /* return status + all results */
326 static int luaB_tostring (lua_State
*L
) {
329 if (luaL_callmeta(L
, 1, "__tostring")) /* is there a metafield? */
330 return 1; /* use its value */
331 switch (lua_type(L
, 1)) {
333 lua_pushstring(L
, lua_tostring(L
, 1));
339 lua_pushstring(L
, (lua_toboolean(L
, 1) ? "true" : "false"));
342 sprintf(buff
, "table: %p", lua_topointer(L
, 1));
345 sprintf(buff
, "function: %p", lua_topointer(L
, 1));
348 case LUA_TLIGHTUSERDATA
:
349 sprintf(buff
, "userdata: %p", lua_touserdata(L
, 1));
352 sprintf(buff
, "thread: %p", (void *)lua_tothread(L
, 1));
355 lua_pushliteral(L
, "nil");
358 lua_pushstring(L
, buff
);
363 static int luaB_newproxy (lua_State
*L
) {
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 */
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);
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"
403 #define LUA_PATH_SEP ';'
406 #ifndef LUA_PATH_MARK
407 #define LUA_PATH_MARK '?'
410 #ifndef LUA_PATH_DEFAULT
411 #define LUA_PATH_DEFAULT "?;?.lua"
415 static const char *getpath (lua_State
*L
) {
417 lua_getglobal(L
, LUA_PATH
); /* try global variable */
418 path
= lua_tostring(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
) {
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 */
438 static void pushcomposename (lua_State
*L
) {
439 const char *path
= lua_tostring(L
, -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 */
450 lua_pushstring(L
, path
); /* push last sufix (`n' already includes this) */
455 static int luaB_require (lua_State
*L
) {
457 int status
= LUA_ERRFILE
; /* not found (yet) */
458 luaL_checkstring(L
, 1);
460 lua_getglobal(L
, REQTAB
);
461 if (!lua_istable(L
, 2)) return luaL_error(L
, "`" REQTAB
"' is not a table");
463 lua_pushvalue(L
, 1); /* check package's name in book-keeping table */
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;
472 status
= luaL_loadfile(L
, lua_tostring(L
, -1)); /* try to load it */
477 lua_getglobal(L
, "_REQUIREDNAME"); /* save previous name */
478 lua_insert(L
, -2); /* put it below function */
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 */
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
));
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
},
514 {"ipairs", luaB_ipairs
},
515 {"pairs", luaB_pairs
},
516 {"print", luaB_print
},
517 {"tonumber", luaB_tonumber
},
518 {"tostring", luaB_tostring
},
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
},
538 ** {======================================================
540 ** =======================================================
543 static int auxresume (lua_State
*L
, lua_State
*co
, int narg
) {
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
);
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 */
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);
566 luaL_argcheck(L
, co
, 1, "coroutine expected");
567 r
= auxresume(L
, co
, lua_gettop(L
) - 1);
569 lua_pushboolean(L
, 0);
571 return 2; /* return false + error message */
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
));
585 if (lua_isstring(L
, -1)) { /* error object is a string? */
586 luaL_where(L
, 1); /* add extra info */
590 lua_error(L
); /* propagate error */
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 */
606 static int luaB_cowrap (lua_State
*L
) {
608 lua_pushcclosure(L
, luaB_auxwrap
, 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");
624 if (lua_getstack(co
, 0, &ar
) == 0 && lua_gettop(co
) == 0)
625 lua_pushliteral(L
, "dead");
627 lua_pushliteral(L
, "suspended");
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
},
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
) {
669 luaL_openlib(L
, LUA_COLIBNAME
, co_funcs
, 0);
671 lua_setglobal(L
, REQTAB
);