1 /* $NetBSD: lbaselib.c,v 1.6 2016/01/28 14:41:39 lneto Exp $ */ 2 3 /* 4 ** Id: lbaselib.c,v 1.312 2015/10/29 15:21:04 roberto Exp 5 ** Basic library 6 ** See Copyright Notice in lua.h 7 */ 8 9 #define lbaselib_c 10 #define LUA_LIB 11 12 #include "lprefix.h" 13 14 15 #ifndef _KERNEL 16 #include <ctype.h> 17 #include <stdio.h> 18 #include <stdlib.h> 19 #include <string.h> 20 #endif /* _KERNEL */ 21 22 #include "lua.h" 23 24 #include "lauxlib.h" 25 #include "lualib.h" 26 27 28 static int luaB_print (lua_State *L) { 29 int n = lua_gettop(L); /* number of arguments */ 30 int i; 31 lua_getglobal(L, "tostring"); 32 for (i=1; i<=n; i++) { 33 const char *s; 34 size_t l; 35 lua_pushvalue(L, -1); /* function to be called */ 36 lua_pushvalue(L, i); /* value to print */ 37 lua_call(L, 1, 1); 38 s = lua_tolstring(L, -1, &l); /* get result */ 39 if (s == NULL) 40 return luaL_error(L, "'tostring' must return a string to 'print'"); 41 if (i>1) lua_writestring("\t", 1); 42 lua_writestring(s, l); 43 lua_pop(L, 1); /* pop result */ 44 } 45 lua_writeline(); 46 return 0; 47 } 48 49 50 #define SPACECHARS " \f\n\r\t\v" 51 52 static const char *b_str2int (const char *s, int base, lua_Integer *pn) { 53 lua_Unsigned n = 0; 54 int neg = 0; 55 s += strspn(s, SPACECHARS); /* skip initial spaces */ 56 if (*s == '-') { s++; neg = 1; } /* handle signal */ 57 else if (*s == '+') s++; 58 if (!isalnum((unsigned char)*s)) /* no digit? */ 59 return NULL; 60 do { 61 int digit = (isdigit((unsigned char)*s)) ? *s - '0' 62 : (toupper((unsigned char)*s) - 'A') + 10; 63 if (digit >= base) return NULL; /* invalid numeral */ 64 n = n * base + digit; 65 s++; 66 } while (isalnum((unsigned char)*s)); 67 s += strspn(s, SPACECHARS); /* skip trailing spaces */ 68 *pn = (lua_Integer)((neg) ? (0u - n) : n); 69 return s; 70 } 71 72 73 static int luaB_tonumber (lua_State *L) { 74 if (lua_isnoneornil(L, 2)) { /* standard conversion? */ 75 luaL_checkany(L, 1); 76 if (lua_type(L, 1) == LUA_TNUMBER) { /* already a number? */ 77 lua_settop(L, 1); /* yes; return it */ 78 return 1; 79 } 80 else { 81 size_t l; 82 const char *s = lua_tolstring(L, 1, &l); 83 if (s != NULL && lua_stringtonumber(L, s) == l + 1) 84 return 1; /* successful conversion to number */ 85 /* else not a number */ 86 } 87 } 88 else { 89 size_t l; 90 const char *s; 91 lua_Integer n = 0; /* to avoid warnings */ 92 lua_Integer base = luaL_checkinteger(L, 2); 93 luaL_checktype(L, 1, LUA_TSTRING); /* no numbers as strings */ 94 s = lua_tolstring(L, 1, &l); 95 luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range"); 96 if (b_str2int(s, (int)base, &n) == s + l) { 97 lua_pushinteger(L, n); 98 return 1; 99 } /* else not a number */ 100 } /* else not a number */ 101 lua_pushnil(L); /* not a number */ 102 return 1; 103 } 104 105 106 static int luaB_error (lua_State *L) { 107 int level = (int)luaL_optinteger(L, 2, 1); 108 lua_settop(L, 1); 109 if (lua_isstring(L, 1) && level > 0) { /* add extra information? */ 110 luaL_where(L, level); 111 lua_pushvalue(L, 1); 112 lua_concat(L, 2); 113 } 114 return lua_error(L); 115 } 116 117 118 static int luaB_getmetatable (lua_State *L) { 119 luaL_checkany(L, 1); 120 if (!lua_getmetatable(L, 1)) { 121 lua_pushnil(L); 122 return 1; /* no metatable */ 123 } 124 luaL_getmetafield(L, 1, "__metatable"); 125 return 1; /* returns either __metatable field (if present) or metatable */ 126 } 127 128 129 static int luaB_setmetatable (lua_State *L) { 130 int t = lua_type(L, 2); 131 luaL_checktype(L, 1, LUA_TTABLE); 132 luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2, 133 "nil or table expected"); 134 if (luaL_getmetafield(L, 1, "__metatable") != LUA_TNIL) 135 return luaL_error(L, "cannot change a protected metatable"); 136 lua_settop(L, 2); 137 lua_setmetatable(L, 1); 138 return 1; 139 } 140 141 142 static int luaB_rawequal (lua_State *L) { 143 luaL_checkany(L, 1); 144 luaL_checkany(L, 2); 145 lua_pushboolean(L, lua_rawequal(L, 1, 2)); 146 return 1; 147 } 148 149 150 static int luaB_rawlen (lua_State *L) { 151 int t = lua_type(L, 1); 152 luaL_argcheck(L, t == LUA_TTABLE || t == LUA_TSTRING, 1, 153 "table or string expected"); 154 lua_pushinteger(L, lua_rawlen(L, 1)); 155 return 1; 156 } 157 158 159 static int luaB_rawget (lua_State *L) { 160 luaL_checktype(L, 1, LUA_TTABLE); 161 luaL_checkany(L, 2); 162 lua_settop(L, 2); 163 lua_rawget(L, 1); 164 return 1; 165 } 166 167 static int luaB_rawset (lua_State *L) { 168 luaL_checktype(L, 1, LUA_TTABLE); 169 luaL_checkany(L, 2); 170 luaL_checkany(L, 3); 171 lua_settop(L, 3); 172 lua_rawset(L, 1); 173 return 1; 174 } 175 176 177 static int luaB_collectgarbage (lua_State *L) { 178 static const char *const opts[] = {"stop", "restart", "collect", 179 "count", "step", "setpause", "setstepmul", 180 "isrunning", NULL}; 181 static const int optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT, 182 LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL, 183 LUA_GCISRUNNING}; 184 int o = optsnum[luaL_checkoption(L, 1, "collect", opts)]; 185 int ex = (int)luaL_optinteger(L, 2, 0); 186 int res = lua_gc(L, o, ex); 187 switch (o) { 188 case LUA_GCCOUNT: { 189 int b = lua_gc(L, LUA_GCCOUNTB, 0); 190 lua_pushnumber(L, (lua_Number)res + ((lua_Number)b/1024)); 191 return 1; 192 } 193 case LUA_GCSTEP: case LUA_GCISRUNNING: { 194 lua_pushboolean(L, res); 195 return 1; 196 } 197 default: { 198 lua_pushinteger(L, res); 199 return 1; 200 } 201 } 202 } 203 204 205 static int luaB_type (lua_State *L) { 206 int t = lua_type(L, 1); 207 luaL_argcheck(L, t != LUA_TNONE, 1, "value expected"); 208 lua_pushstring(L, lua_typename(L, t)); 209 return 1; 210 } 211 212 213 static int pairsmeta (lua_State *L, const char *method, int iszero, 214 lua_CFunction iter) { 215 if (luaL_getmetafield(L, 1, method) == LUA_TNIL) { /* no metamethod? */ 216 luaL_checktype(L, 1, LUA_TTABLE); /* argument must be a table */ 217 lua_pushcfunction(L, iter); /* will return generator, */ 218 lua_pushvalue(L, 1); /* state, */ 219 if (iszero) lua_pushinteger(L, 0); /* and initial value */ 220 else lua_pushnil(L); 221 } 222 else { 223 lua_pushvalue(L, 1); /* argument 'self' to metamethod */ 224 lua_call(L, 1, 3); /* get 3 values from metamethod */ 225 } 226 return 3; 227 } 228 229 230 static int luaB_next (lua_State *L) { 231 luaL_checktype(L, 1, LUA_TTABLE); 232 lua_settop(L, 2); /* create a 2nd argument if there isn't one */ 233 if (lua_next(L, 1)) 234 return 2; 235 else { 236 lua_pushnil(L); 237 return 1; 238 } 239 } 240 241 242 static int luaB_pairs (lua_State *L) { 243 return pairsmeta(L, "__pairs", 0, luaB_next); 244 } 245 246 247 /* 248 ** Traversal function for 'ipairs' 249 */ 250 static int ipairsaux (lua_State *L) { 251 lua_Integer i = luaL_checkinteger(L, 2) + 1; 252 lua_pushinteger(L, i); 253 return (lua_geti(L, 1, i) == LUA_TNIL) ? 1 : 2; 254 } 255 256 257 /* 258 ** This function will use either 'ipairsaux' or 'ipairsaux_raw' to 259 ** traverse a table, depending on whether the table has metamethods 260 ** that can affect the traversal. 261 */ 262 static int luaB_ipairs (lua_State *L) { 263 #if defined(LUA_COMPAT_IPAIRS) 264 return pairsmeta(L, "__ipairs", 1, ipairsaux); 265 #else 266 luaL_checkany(L, 1); 267 lua_pushcfunction(L, ipairsaux); /* iteration function */ 268 lua_pushvalue(L, 1); /* state */ 269 lua_pushinteger(L, 0); /* initial value */ 270 return 3; 271 #endif 272 } 273 274 275 static int load_aux (lua_State *L, int status, int envidx) { 276 if (status == LUA_OK) { 277 if (envidx != 0) { /* 'env' parameter? */ 278 lua_pushvalue(L, envidx); /* environment for loaded function */ 279 if (!lua_setupvalue(L, -2, 1)) /* set it as 1st upvalue */ 280 lua_pop(L, 1); /* remove 'env' if not used by previous call */ 281 } 282 return 1; 283 } 284 else { /* error (message is on top of the stack) */ 285 lua_pushnil(L); 286 lua_insert(L, -2); /* put before error message */ 287 return 2; /* return nil plus error message */ 288 } 289 } 290 291 292 #ifndef _KERNEL 293 static int luaB_loadfile (lua_State *L) { 294 const char *fname = luaL_optstring(L, 1, NULL); 295 const char *mode = luaL_optstring(L, 2, NULL); 296 int env = (!lua_isnone(L, 3) ? 3 : 0); /* 'env' index or 0 if no 'env' */ 297 int status = luaL_loadfilex(L, fname, mode); 298 return load_aux(L, status, env); 299 } 300 #endif /* _KERNEL */ 301 302 303 /* 304 ** {====================================================== 305 ** Generic Read function 306 ** ======================================================= 307 */ 308 309 310 /* 311 ** reserved slot, above all arguments, to hold a copy of the returned 312 ** string to avoid it being collected while parsed. 'load' has four 313 ** optional arguments (chunk, source name, mode, and environment). 314 */ 315 #define RESERVEDSLOT 5 316 317 318 /* 319 ** Reader for generic 'load' function: 'lua_load' uses the 320 ** stack for internal stuff, so the reader cannot change the 321 ** stack top. Instead, it keeps its resulting string in a 322 ** reserved slot inside the stack. 323 */ 324 static const char *generic_reader (lua_State *L, void *ud, size_t *size) { 325 (void)(ud); /* not used */ 326 luaL_checkstack(L, 2, "too many nested functions"); 327 lua_pushvalue(L, 1); /* get function */ 328 lua_call(L, 0, 1); /* call it */ 329 if (lua_isnil(L, -1)) { 330 lua_pop(L, 1); /* pop result */ 331 *size = 0; 332 return NULL; 333 } 334 else if (!lua_isstring(L, -1)) 335 luaL_error(L, "reader function must return a string"); 336 lua_replace(L, RESERVEDSLOT); /* save string in reserved slot */ 337 return lua_tolstring(L, RESERVEDSLOT, size); 338 } 339 340 341 static int luaB_load (lua_State *L) { 342 int status; 343 size_t l; 344 const char *s = lua_tolstring(L, 1, &l); 345 const char *mode = luaL_optstring(L, 3, "bt"); 346 int env = (!lua_isnone(L, 4) ? 4 : 0); /* 'env' index or 0 if no 'env' */ 347 if (s != NULL) { /* loading a string? */ 348 const char *chunkname = luaL_optstring(L, 2, s); 349 status = luaL_loadbufferx(L, s, l, chunkname, mode); 350 } 351 else { /* loading from a reader function */ 352 const char *chunkname = luaL_optstring(L, 2, "=(load)"); 353 luaL_checktype(L, 1, LUA_TFUNCTION); 354 lua_settop(L, RESERVEDSLOT); /* create reserved slot */ 355 status = lua_load(L, generic_reader, NULL, chunkname, mode); 356 } 357 return load_aux(L, status, env); 358 } 359 360 /* }====================================================== */ 361 362 363 #ifndef _KERNEL 364 static int dofilecont (lua_State *L, int d1, lua_KContext d2) { 365 (void)d1; (void)d2; /* only to match 'lua_Kfunction' prototype */ 366 return lua_gettop(L) - 1; 367 } 368 369 370 static int luaB_dofile (lua_State *L) { 371 const char *fname = luaL_optstring(L, 1, NULL); 372 lua_settop(L, 1); 373 if (luaL_loadfile(L, fname) != LUA_OK) 374 return lua_error(L); 375 lua_callk(L, 0, LUA_MULTRET, 0, dofilecont); 376 return dofilecont(L, 0, 0); 377 } 378 #endif /* _KERNEL */ 379 380 381 static int luaB_assert (lua_State *L) { 382 if (lua_toboolean(L, 1)) /* condition is true? */ 383 return lua_gettop(L); /* return all arguments */ 384 else { /* error */ 385 luaL_checkany(L, 1); /* there must be a condition */ 386 lua_remove(L, 1); /* remove it */ 387 lua_pushliteral(L, "assertion failed!"); /* default message */ 388 lua_settop(L, 1); /* leave only message (default if no other one) */ 389 return luaB_error(L); /* call 'error' */ 390 } 391 } 392 393 394 static int luaB_select (lua_State *L) { 395 int n = lua_gettop(L); 396 if (lua_type(L, 1) == LUA_TSTRING && *lua_tostring(L, 1) == '#') { 397 lua_pushinteger(L, n-1); 398 return 1; 399 } 400 else { 401 lua_Integer i = luaL_checkinteger(L, 1); 402 if (i < 0) i = n + i; 403 else if (i > n) i = n; 404 luaL_argcheck(L, 1 <= i, 1, "index out of range"); 405 return n - (int)i; 406 } 407 } 408 409 410 /* 411 ** Continuation function for 'pcall' and 'xpcall'. Both functions 412 ** already pushed a 'true' before doing the call, so in case of success 413 ** 'finishpcall' only has to return everything in the stack minus 414 ** 'extra' values (where 'extra' is exactly the number of items to be 415 ** ignored). 416 */ 417 static int finishpcall (lua_State *L, int status, lua_KContext extra) { 418 if (status != LUA_OK && status != LUA_YIELD) { /* error? */ 419 lua_pushboolean(L, 0); /* first result (false) */ 420 lua_pushvalue(L, -2); /* error message */ 421 return 2; /* return false, msg */ 422 } 423 else 424 return lua_gettop(L) - (int)extra; /* return all results */ 425 } 426 427 428 static int luaB_pcall (lua_State *L) { 429 int status; 430 luaL_checkany(L, 1); 431 lua_pushboolean(L, 1); /* first result if no errors */ 432 lua_insert(L, 1); /* put it in place */ 433 status = lua_pcallk(L, lua_gettop(L) - 2, LUA_MULTRET, 0, 0, finishpcall); 434 return finishpcall(L, status, 0); 435 } 436 437 438 /* 439 ** Do a protected call with error handling. After 'lua_rotate', the 440 ** stack will have <f, err, true, f, [args...]>; so, the function passes 441 ** 2 to 'finishpcall' to skip the 2 first values when returning results. 442 */ 443 static int luaB_xpcall (lua_State *L) { 444 int status; 445 int n = lua_gettop(L); 446 luaL_checktype(L, 2, LUA_TFUNCTION); /* check error function */ 447 lua_pushboolean(L, 1); /* first result */ 448 lua_pushvalue(L, 1); /* function */ 449 lua_rotate(L, 3, 2); /* move them below function's arguments */ 450 status = lua_pcallk(L, n - 2, LUA_MULTRET, 2, 2, finishpcall); 451 return finishpcall(L, status, 2); 452 } 453 454 455 static int luaB_tostring (lua_State *L) { 456 luaL_checkany(L, 1); 457 luaL_tolstring(L, 1, NULL); 458 return 1; 459 } 460 461 462 static const luaL_Reg base_funcs[] = { 463 {"assert", luaB_assert}, 464 {"collectgarbage", luaB_collectgarbage}, 465 #ifndef _KERNEL 466 {"dofile", luaB_dofile}, 467 #endif /* _KERNEL */ 468 {"error", luaB_error}, 469 {"getmetatable", luaB_getmetatable}, 470 {"ipairs", luaB_ipairs}, 471 #ifndef _KERNEL 472 {"loadfile", luaB_loadfile}, 473 #endif /* _KERNEL */ 474 {"load", luaB_load}, 475 #if defined(LUA_COMPAT_LOADSTRING) 476 {"loadstring", luaB_load}, 477 #endif 478 {"next", luaB_next}, 479 {"pairs", luaB_pairs}, 480 {"pcall", luaB_pcall}, 481 {"print", luaB_print}, 482 {"rawequal", luaB_rawequal}, 483 {"rawlen", luaB_rawlen}, 484 {"rawget", luaB_rawget}, 485 {"rawset", luaB_rawset}, 486 {"select", luaB_select}, 487 {"setmetatable", luaB_setmetatable}, 488 {"tonumber", luaB_tonumber}, 489 {"tostring", luaB_tostring}, 490 {"type", luaB_type}, 491 {"xpcall", luaB_xpcall}, 492 /* placeholders */ 493 {"_G", NULL}, 494 {"_VERSION", NULL}, 495 {NULL, NULL} 496 }; 497 498 499 LUAMOD_API int luaopen_base (lua_State *L) { 500 /* open lib into global table */ 501 lua_pushglobaltable(L); 502 luaL_setfuncs(L, base_funcs, 0); 503 /* set global _G */ 504 lua_pushvalue(L, -1); 505 lua_setfield(L, -2, "_G"); 506 /* set global _VERSION */ 507 lua_pushliteral(L, LUA_VERSION); 508 lua_setfield(L, -2, "_VERSION"); 509 return 1; 510 } 511 512