Compare commits

..

400 Commits

Author SHA1 Message Date
Roberto Ierusalimschy
b9c98cd4d9 entry for new version (4.0a) 2000-04-25 13:45:39 -03:00
Roberto Ierusalimschy
0e8855e171 final version (by lhf) 2000-04-25 13:44:31 -03:00
Roberto Ierusalimschy
2ae9c856cf more uniform names 2000-04-24 18:05:11 -03:00
Roberto Ierusalimschy
c4409f69ab details 2000-04-19 10:41:37 -03:00
Roberto Ierusalimschy
89a9c36281 no more `register' declarations: leave it to the compiler. 2000-04-19 10:36:25 -03:00
Roberto Ierusalimschy
8f2fba5877 using new constructs (for & break) in the examples and code fragments 2000-04-17 16:23:48 -03:00
Roberto Ierusalimschy
62824137d6 no more `seterrormethod' function 2000-04-17 16:23:12 -03:00
Roberto Ierusalimschy
71219ccc39 simpler version of `luaK_tostack' 2000-04-17 11:05:34 -03:00
Roberto Ierusalimschy
870f61d299 code redistribution 2000-04-14 15:12:35 -03:00
Roberto Ierusalimschy
c845ec777a new order for modules (better locality??) 2000-04-14 14:52:09 -03:00
Roberto Ierusalimschy
e408cf61a2 new version number 2000-04-14 14:48:20 -03:00
Roberto Ierusalimschy
4e90768635 lots of changes (almost ready for 4.0) 2000-04-14 14:47:55 -03:00
Roberto Ierusalimschy
c1666a13e3 better code organization 2000-04-14 14:47:24 -03:00
Roberto Ierusalimschy
e02750ec60 new type for CFunction (for "pure" C) 2000-04-14 14:46:37 -03:00
Roberto Ierusalimschy
0b56646baf new function `getargs' 2000-04-14 14:46:29 -03:00
Roberto Ierusalimschy
634c3d57e9 optimization for SETLOCAL was too specific. 2000-04-14 14:46:15 -03:00
Roberto Ierusalimschy
4aa9ad6514 functions must return explicit `nil' on failure 2000-04-14 14:44:20 -03:00
Roberto Ierusalimschy
d76b1a0eef base' for tonumber' must be >= 2. 2000-04-13 15:08:18 -03:00
Roberto Ierusalimschy
e7c8393682 optimization INCLOCAL is not necessary, with `for' 2000-04-13 13:51:01 -03:00
Roberto Ierusalimschy
ceaa97ff5b tonumber must return `nil' when convertion fails. 2000-04-13 13:46:43 -03:00
Roberto Ierusalimschy
2bb77cdaed keep opcodes in the right order 2000-04-12 16:56:50 -03:00
Roberto Ierusalimschy
f9cf402fbd first implementation of FOR 2000-04-12 15:57:19 -03:00
Roberto Ierusalimschy
0c3fe2c44b comment 2000-04-12 15:47:03 -03:00
Roberto Ierusalimschy
0433e42023 no more repeat ... end. 2000-04-11 15:37:18 -03:00
Roberto Ierusalimschy
0810bc707f new syntax: |label| 2000-04-10 16:21:14 -03:00
Roberto Ierusalimschy
c3b73cbeb8 comments (detail) 2000-04-10 16:20:24 -03:00
Roberto Ierusalimschy
1eabd0549e comments 2000-04-07 16:35:31 -03:00
Roberto Ierusalimschy
54dd5cc7fd reorganization of lcode.c 2000-04-07 16:35:20 -03:00
Roberto Ierusalimschy
031978798c more optimizations 2000-04-07 10:13:11 -03:00
Roberto Ierusalimschy
14251c5a56 name changes + new operation - old operation 2000-04-07 10:12:50 -03:00
Roberto Ierusalimschy
42130ed712 name changes 2000-04-07 10:11:49 -03:00
Roberto Ierusalimschy
d615e78e08 new optimization: jumps to jumps 2000-04-06 14:36:52 -03:00
Roberto Ierusalimschy
c6965ce551 new functions: disassembler and get limit. 2000-04-06 14:35:23 -03:00
Roberto Ierusalimschy
22329e4cdf implementation of BREAK 2000-04-05 14:51:58 -03:00
Roberto Ierusalimschy
9f734094f9 `nil' is optional for next and nextvar (and is not for tonumber & tag). 2000-04-04 17:49:32 -03:00
Roberto Ierusalimschy
4e7e9e8de5 new opcode INCLOCAL. 2000-04-04 17:48:44 -03:00
Roberto Ierusalimschy
3e45496295 syntactical details 2000-04-03 10:44:55 -03:00
Roberto Ierusalimschy
e30327728c BUG: tostring() without arguments gives seg. fault. 2000-04-03 10:20:33 -03:00
Roberto Ierusalimschy
36e1390631 details. 2000-03-31 13:28:45 -03:00
Roberto Ierusalimschy
8f0f54ec38 name change 2000-03-30 17:55:50 -03:00
Roberto Ierusalimschy
556a89e537 new names for debug types 2000-03-30 14:19:48 -03:00
Roberto Ierusalimschy
e2c60eda16 `luaT_validevent' is exported, because compatibility module for fallbacks
uses it.
2000-03-30 13:41:51 -03:00
Roberto Ierusalimschy
a69356e9e0 no more special cases for closures with 0 upvalues (performance is the same,
memory use a little higher, code much simpler).
2000-03-29 17:19:20 -03:00
Roberto Ierusalimschy
b53dc0c485 TAG_ARRAY -> TAG_TABLE 2000-03-27 17:10:21 -03:00
Roberto Ierusalimschy
63e230a16b comments 2000-03-27 17:08:33 -03:00
Roberto Ierusalimschy
102a1be615 no more support for gc TM for tables 2000-03-27 17:08:02 -03:00
Roberto Ierusalimschy
4c03196697 lua_setstate makes no sense with explicit multiple states 2000-03-27 11:00:35 -03:00
Roberto Ierusalimschy
54633d7c7d new name for llimits.h 2000-03-24 16:49:23 -03:00
Roberto Ierusalimschy
13578517c7 new file to keep all limits and instalation-dependent definitions 2000-03-24 14:26:08 -03:00
Roberto Ierusalimschy
213e9febc8 limits now are in `llims.n' 2000-03-24 14:26:08 -03:00
Roberto Ierusalimschy
47b4bf5964 small refactoring. 2000-03-24 09:18:30 -03:00
Roberto Ierusalimschy
415ee1a24f SETLINEs for reserved words, too. 2000-03-24 09:17:53 -03:00
Roberto Ierusalimschy
5f3c5ace95 message detail 2000-03-22 13:24:13 -03:00
Roberto Ierusalimschy
441469f803 new option `-s' + argv ends with NULL (so we don't need argc). 2000-03-20 17:27:32 -03:00
Roberto Ierusalimschy
1157c2a7e4 better(?) treatment for SETLINE + while optimization is too complex for
only 3% of maximum improvement.
2000-03-20 16:15:37 -03:00
Roberto Ierusalimschy
374cc888f4 better(?) treatment for SETLINE 2000-03-20 16:15:37 -03:00
Roberto Ierusalimschy
bb9605bbc9 tags can be positive values 2000-03-20 16:14:54 -03:00
Roberto Ierusalimschy
6759299880 new implementation for handling I/O tags + setglobal TM for tracing
changes in _INPUT/_OUTPUT
2000-03-20 16:13:45 -03:00
Roberto Ierusalimschy
da7eb34cd6 optimization for "while 1" and "repeat until nil" 2000-03-17 11:46:04 -03:00
Roberto Ierusalimschy
2c8e28d75a small changes 2000-03-17 10:09:46 -03:00
Roberto Ierusalimschy
4fb8e93c36 small optimization for i..'' 2000-03-17 10:09:12 -03:00
Roberto Ierusalimschy
7f77431950 detail 2000-03-16 18:06:16 -03:00
Roberto Ierusalimschy
87367e97f3 more information about memory use 2000-03-16 17:35:07 -03:00
Roberto Ierusalimschy
06f08f5634 small problems with limits and jumps 2000-03-16 15:03:09 -03:00
Roberto Ierusalimschy
3860c5934e details. 2000-03-15 17:50:33 -03:00
Roberto Ierusalimschy
f0b697e01c details 2000-03-13 17:37:16 -03:00
Roberto Ierusalimschy
73aa465a8e some name changes 2000-03-10 15:37:44 -03:00
Roberto Ierusalimschy
3d0577f4b9 small optimizations. 2000-03-10 11:38:10 -03:00
Roberto Ierusalimschy
977b8f65f0 comment detail. 2000-03-10 11:01:05 -03:00
Roberto Ierusalimschy
e3cf93ddb6 first implementation of "threaded code" for boolean operations 2000-03-09 10:57:37 -03:00
Roberto Ierusalimschy
88b306f495 some optimizations 2000-03-08 21:19:22 -03:00
Roberto Ierusalimschy
563de491be a better way to control optimizations. 2000-03-04 17:18:15 -03:00
Roberto Ierusalimschy
29e0193425 details 2000-03-03 17:30:47 -03:00
Roberto Ierusalimschy
61f97a8ace maybe a concat right associative allows some optimizations... 2000-03-03 17:29:25 -03:00
Roberto Ierusalimschy
d1ea38580a change of code generation design (independent functions for each opcode) 2000-03-03 15:53:17 -03:00
Roberto Ierusalimschy
3c9d999424 many details (most by lhf). 2000-03-03 11:58:26 -03:00
Roberto Ierusalimschy
f7840a3e0b new algorithm to parse expressions + distribution of code between lparser
and lcode.
2000-03-03 09:33:59 -03:00
Roberto Ierusalimschy
1780e2c977 lua_settable should check stack space (it could call a T.M.) 2000-03-02 09:44:29 -03:00
Roberto Ierusalimschy
fa14cbf8e8 comments 2000-03-02 09:32:53 -03:00
Roberto Ierusalimschy
4d4e6f07c0 all order operators use a single tag method (<) 2000-02-22 16:12:46 -02:00
Roberto Ierusalimschy
5cecf0ea9f it is better to control stack space where it is needed. 2000-02-22 15:54:16 -02:00
Roberto Ierusalimschy
3bc925138e first version of code optimizer 2000-02-22 11:31:43 -02:00
Roberto Ierusalimschy
39e1f079bd code generator (and optimizer) for Lua 2000-02-22 11:31:19 -02:00
Roberto Ierusalimschy
075da266e5 there is no need to use shorts... 2000-02-21 16:33:26 -02:00
Roberto Ierusalimschy
228a62f799 details 2000-02-21 16:30:42 -02:00
Roberto Ierusalimschy
7c2fb15bec need "string.h" to use "strchr". 2000-02-21 16:30:06 -02:00
Roberto Ierusalimschy
1f01998516 nobody uses memmove any more. 2000-02-17 16:30:36 -02:00
Roberto Ierusalimschy
c929376d59 must include a definition for NULL 2000-02-17 16:30:36 -02:00
Roberto Ierusalimschy
3afe85b2ce new version for INSTRUCTION formats 2000-02-14 14:51:08 -02:00
Roberto Ierusalimschy
52aad0ab59 removing implementation for better error messages (must rethink it...) 2000-02-11 14:52:54 -02:00
Roberto Ierusalimschy
74f1c3d025 small changes for "clean C" 2000-02-08 14:39:42 -02:00
Roberto Ierusalimschy
1f691a4fcd renaming of some opcodes and fields 2000-01-28 14:53:00 -02:00
Roberto Ierusalimschy
d6b9f49aaf only need to reset buffer for strings, numbers, and names. 2000-01-26 16:51:49 -02:00
Roberto Ierusalimschy
d83c2a8455 performance details. 2000-01-25 16:44:21 -02:00
Roberto Ierusalimschy
d11e5adf55 `const' array in protos breaked in 3 arrays (for strings, numbers, and
prototypes).
2000-01-25 11:57:18 -02:00
Roberto Ierusalimschy
99e340b2ba keep `top' in registers when running basic tasks (settable, getglobal, ...) 2000-01-24 18:14:07 -02:00
Roberto Ierusalimschy
9744255ae9 error in call must be propagated 2000-01-24 18:11:26 -02:00
Roberto Ierusalimschy
512b15b601 small optimizations (relational operators) 2000-01-19 14:50:30 -02:00
Roberto Ierusalimschy
33d3504889 new debug API 2000-01-19 14:50:14 -02:00
Roberto Ierusalimschy
2877bad4c2 new debug API (first version) 2000-01-19 10:00:45 -02:00
Roberto Ierusalimschy
27163f032e Auxiliary functions from Debug Interface module 2000-01-14 15:15:44 -02:00
Roberto Ierusalimschy
eab57ed6fd details 2000-01-13 14:30:47 -02:00
Roberto Ierusalimschy
ea45f3eb28 better separation between debug code and regular code 2000-01-13 14:30:47 -02:00
Roberto Ierusalimschy
46ec57cbc6 little change when calling tag methods 2000-01-13 13:56:03 -02:00
Roberto Ierusalimschy
62787f1b1f `exp' is "reserved word" in Visual-C++ ;-) 2000-01-12 14:24:39 -02:00
Roberto Ierusalimschy
dcb7bb514e details (error messages) 2000-01-10 15:34:38 -02:00
Roberto Ierusalimschy
b3aaa048b0 bug: cannot reopen stdin (for binary mode) 1999-12-30 16:40:57 -02:00
Roberto Ierusalimschy
aee07c6599 details 1999-12-30 16:29:46 -02:00
Roberto Ierusalimschy
bcdbdaccc3 more debug information (still with bug for tag methods...) 1999-12-30 16:28:40 -02:00
Roberto Ierusalimschy
5cafe5af02 tag method must be a function 1999-12-30 16:27:03 -02:00
Roberto Ierusalimschy
607012ece1 tag method must be a function
+ error message must be a string
1999-12-30 16:27:03 -02:00
Roberto Ierusalimschy
0652906e7a details. 1999-12-30 10:40:29 -02:00
Roberto Ierusalimschy
4d1b815b60 return gives wrong line in debug information. 1999-12-29 16:07:10 -02:00
Roberto Ierusalimschy
4ebc183e56 bug: return gives wrong line in debug information. 1999-12-29 16:07:10 -02:00
Roberto Ierusalimschy
298d0abff7 first version of extra debug information (NAME) 1999-12-29 14:31:15 -02:00
Roberto Ierusalimschy
4fbe775154 details 1999-12-29 14:24:03 -02:00
Roberto Ierusalimschy
aabefe9d68 details. 1999-12-28 17:23:41 -02:00
Roberto Ierusalimschy
fb60283974 better error messages 1999-12-28 09:52:49 -02:00
Roberto Ierusalimschy
acdb0b741e comments. 1999-12-27 15:33:22 -02:00
Roberto Ierusalimschy
5b08fcd5a1 no more "lua" in error messages 1999-12-27 11:04:53 -02:00
Roberto Ierusalimschy
b1b0c219f5 new ttypes to distinguish between C closures and Lua closures. 1999-12-23 16:19:57 -02:00
Roberto Ierusalimschy
be3212de78 details 1999-12-22 14:58:36 -02:00
Roberto Ierusalimschy
2eaf9a00ae little bug: `1ea' got a wrong token at the error message 1999-12-22 14:58:36 -02:00
Roberto Ierusalimschy
6c79a0a80d new way to control hooks inside hooks (now the control is done inside Lua) 1999-12-21 16:04:41 -02:00
Roberto Ierusalimschy
3daeabb606 new way to pass arguments: with option `-f' 1999-12-21 15:34:23 -02:00
Roberto Ierusalimschy
cfdebfbc53 debug information for parameters use line 0 for them (as they are
always visible).
1999-12-21 15:31:28 -02:00
Roberto Ierusalimschy
d61d5bef9d details 1999-12-20 11:10:38 -02:00
Roberto Ierusalimschy
4450efc97e new chunkid for C functions (`luaL_chunkid') 1999-12-20 11:09:45 -02:00
Roberto Ierusalimschy
de65253f2d new way to handle _PROMPT 1999-12-20 11:03:20 -02:00
Roberto Ierusalimschy
12b45c2df2 luaS_newfixedstring renamed to luaS_newfixed 1999-12-14 16:42:57 -02:00
Roberto Ierusalimschy
1b15206cf9 many details + code redistribution 1999-12-14 16:33:29 -02:00
Roberto Ierusalimschy
e6d56cd2d8 module for internal use only, with functions for internal tests 1999-12-14 16:31:20 -02:00
Roberto Ierusalimschy
c16c63cc59 new module with the debug API functions 1999-12-14 16:31:20 -02:00
Roberto Ierusalimschy
dea54a7c71 comments 1999-12-09 18:01:48 -02:00
Roberto Ierusalimschy
544eeb1f9c details 1999-12-07 10:05:34 -02:00
Roberto Ierusalimschy
b3fe203c36 keep it simple 1999-12-07 10:05:34 -02:00
Roberto Ierusalimschy
9c142740c1 stack may not be empty after a correct run... 1999-12-07 09:42:54 -02:00
Roberto Ierusalimschy
7621cc2aa5 for the future... 1999-12-07 09:36:16 -02:00
Roberto Ierusalimschy
ba1f504970 `optimization' doesn't seem to make any difference... 1999-12-06 17:30:53 -02:00
Roberto Ierusalimschy
617be66015 better control (and error recovery) for begin/end blocks 1999-12-06 10:03:45 -02:00
Roberto Ierusalimschy
f356eb010b configurable stack size + some corrections in error recovery in
`protectedrun'
1999-12-06 09:43:58 -02:00
Roberto Ierusalimschy
3e38fd2463 `lua_setfallback' leaves things on the stack, so it is better to protect
it.
1999-12-06 09:43:09 -02:00
Roberto Ierusalimschy
533beedad2 new tests for begin/end blocks and multi-state 1999-12-06 09:42:18 -02:00
Roberto Ierusalimschy
968ad49da6 `lua_newstate' gets the inital stack size and other arguments 1999-12-06 09:41:28 -02:00
Roberto Ierusalimschy
1fdb445e7d details. 1999-12-06 09:40:55 -02:00
Roberto Ierusalimschy
c7119a93f0 new language for testC (debugging facility) 1999-12-03 16:02:54 -02:00
Roberto Ierusalimschy
3c9e29f56d details 1999-12-03 09:26:23 -02:00
Roberto Ierusalimschy
72afb6debb modifications by lhf 1999-12-02 17:11:51 -02:00
Roberto Ierusalimschy
b097076678 missing include 1999-12-02 14:41:29 -02:00
Roberto Ierusalimschy
8223ff473f lua_Object is a pointer to the stack (because now the stack doen't move) 1999-12-02 14:24:45 -02:00
Roberto Ierusalimschy
fe237ad808 fixed stack; first version. 1999-12-01 17:50:08 -02:00
Roberto Ierusalimschy
3181dfefee details 1999-11-30 11:06:50 -02:00
Roberto Ierusalimschy
764e095d7f object' and string' are very busy names... 1999-11-29 17:31:29 -02:00
Roberto Ierusalimschy
2b3ea61342 mistake in change for multi-state (gc threshold was not corrected) 1999-11-29 17:12:07 -02:00
Roberto Ierusalimschy
49af08e3e7 new name for lua_equal(obj); LUA_NOOBJECT is equal to LUA_NOOBJECT 1999-11-29 17:11:36 -02:00
Roberto Ierusalimschy
c5fa0895e9 table sizes don't need to be primes; power of 2 gives the same performance. 1999-11-29 14:38:48 -02:00
Roberto Ierusalimschy
d015f1fc02 table sizes don't need to be primes; power of 2 gives the same performance. 1999-11-26 16:59:20 -02:00
Roberto Ierusalimschy
790690a223 new way to keep function arguments (with StkId instead of copy) 1999-11-26 16:53:03 -02:00
Roberto Ierusalimschy
33b8a01032 new way to code CALLs + passing multiple arguments between function calls 1999-11-25 16:59:43 -02:00
Roberto Ierusalimschy
d29ce75737 new signature for function luaD_call (old luaD_calln) 1999-11-25 16:58:51 -02:00
Roberto Ierusalimschy
878ef96127 comment 1999-11-25 16:44:02 -02:00
Roberto Ierusalimschy
e5743adb21 macros key', val', and `node' don't need the state 1999-11-23 11:58:02 -02:00
Roberto Ierusalimschy
514783de9d simpler without `init_hash' 1999-11-22 16:24:50 -02:00
Roberto Ierusalimschy
7d1499ba88 new macro luaL_openl 1999-11-22 15:39:51 -02:00
Roberto Ierusalimschy
29ede6aa13 first implementation of multiple states (reentrant code). 1999-11-22 11:12:07 -02:00
Roberto Ierusalimschy
951897c093 last warnings in Visual C 1999-11-16 10:50:48 -02:00
Roberto Ierusalimschy
a34677e4f4 details 1999-11-12 11:54:44 -02:00
Roberto Ierusalimschy
573372665a new API function `lua_equalobj' 1999-11-11 15:02:40 -02:00
Roberto Ierusalimschy
a6755e2f1a BUG: `strfind' does not handle \0 in plain search. 1999-11-11 14:45:04 -02:00
Roberto Ierusalimschy
a4628a02cf better ways to test lock mechanism 1999-11-10 13:41:11 -02:00
Roberto Ierusalimschy
0c725b2492 buffer can shrink when too big 1999-11-10 13:40:46 -02:00
Roberto Ierusalimschy
d915cf4f9d ways to measure number of `blocks' for GC + details 1999-11-10 13:39:35 -02:00
Roberto Ierusalimschy
53fb65d394 better implementation of `lua_ref' (much better...) 1999-11-10 13:37:50 -02:00
Roberto Ierusalimschy
a7fa7bafc8 new warnings with option "-W" (gcc) 1999-11-09 15:59:35 -02:00
Roberto Ierusalimschy
cde179b369 new implementation for global variable values (separated from strings) 1999-11-04 15:23:12 -02:00
Roberto Ierusalimschy
80b39d83c3 default `success' for exit is more useful. 1999-10-26 09:00:12 -02:00
Roberto Ierusalimschy
5a48255c9f invariant tests over tables performed externally, through a built-in
function (when DEBUG is ion).
1999-10-26 08:53:40 -02:00
Roberto Ierusalimschy
bbab974717 details (comments) 1999-10-25 11:35:44 -02:00
Roberto Ierusalimschy
910836fb53 warnings from Visual C++ 1999-10-19 11:33:22 -02:00
Roberto Ierusalimschy
8e7451512f some more `const's 1999-10-14 17:46:57 -02:00
Roberto Ierusalimschy
4e9f2d13d5 new implementation of hash tables. 1999-10-14 17:13:31 -02:00
Roberto Ierusalimschy
b6ebbb2fee better assertions. 1999-10-14 15:53:35 -02:00
Roberto Ierusalimschy
c5fee7615e new implementation for string hashing, with chaining. 1999-10-11 14:13:42 -02:00
Roberto Ierusalimschy
cca78b5c71 Visual C++ warning 1999-10-11 14:06:01 -02:00
Roberto Ierusalimschy
d435b7acd8 read patterns are deprecated; new option `read(n)' to read n bytes. 1999-10-07 17:18:36 -02:00
Roberto Ierusalimschy
63ccf42397 new API function 'lua_type'. 1999-10-07 17:04:30 -02:00
Roberto Ierusalimschy
1942b58609 details 1999-10-05 16:33:43 -02:00
Roberto Ierusalimschy
4343420d4d simplified version of `gc' tag method (only for userdata now). 1999-10-04 15:51:04 -02:00
Roberto Ierusalimschy
1f7103e05d implementation of lua_ref (previously in module `lmem'). 1999-10-04 15:50:24 -02:00
Roberto Ierusalimschy
dcc10accea temporary version 1999-09-29 09:56:22 -03:00
Roberto Ierusalimschy
e2fc5aa684 checks table size only when element is a new one 1999-09-28 09:27:06 -03:00
Roberto Ierusalimschy
d53e2d2386 details 1999-09-27 15:00:25 -03:00
Roberto Ierusalimschy
cf9a22396c "luaH_set" only needs to check size when key is new 1999-09-22 11:38:45 -03:00
Roberto Ierusalimschy
17374d2daa `put_luaObjectonTop' must be public (to be used by lfback.c), and so
it must have a "public" name: `luaA_putObjectOnTop'
1999-09-21 13:10:13 -03:00
Roberto Ierusalimschy
04265655a8 compatibility with old fallback system now provided by external module 1999-09-20 11:57:29 -03:00
Roberto Ierusalimschy
e10788b2ff reorganization of `stat' function. 1999-09-20 11:15:18 -03:00
Roberto Ierusalimschy
7eb2f18621 remove of some useless #includes 1999-09-17 13:53:54 -03:00
Roberto Ierusalimschy
a8a75fb7ab details 1999-09-13 16:42:02 -03:00
Roberto Ierusalimschy
ae3ecc2d4a tonumber'e1' and tonumber(' ', x), for x!=10, gave 0 instead of nil. 1999-09-08 17:45:18 -03:00
Roberto Ierusalimschy
2e13cd77ab new interface for `luaO_strtod', which now checks signal, too. 1999-09-06 17:34:18 -03:00
Roberto Ierusalimschy
ff9c0da783 test first the most common case. 1999-09-06 17:19:22 -03:00
Roberto Ierusalimschy
f7fe04d4b7 details. 1999-09-06 12:24:46 -03:00
Roberto Ierusalimschy
82699d0c4f new interface for `luaO_strtod', which now checks signal, too. 1999-09-06 10:55:09 -03:00
Roberto Ierusalimschy
88866208f0 luaL_arg_check' always has an extramsg'. 1999-09-06 10:13:03 -03:00
Roberto Ierusalimschy
7d365a5c7a in the (old) expression << ls->fs->f->consts[checkname(ls)] >>, checkname
could realloc f->consts.
1999-09-02 10:13:22 -03:00
Roberto Ierusalimschy
52a206366d bug: in the (old) expression << ls->fs->f->consts[checkname(ls)] >>, checkname
could realloc f->consts.
1999-09-02 10:13:22 -03:00
Roberto Ierusalimschy
b2c89ed2d2 new mechanism to access argv from a script 1999-08-18 14:40:54 -03:00
Roberto Ierusalimschy
2a03170ebd random(0) and random(x,0) are wrong (0 is read as no argument!). 1999-08-18 11:40:51 -03:00
Roberto Ierusalimschy
05f55cc062 more warning checking (mainly related to const strings). 1999-08-17 17:21:52 -03:00
Roberto Ierusalimschy
c787dccd9b "const" !!! 1999-08-16 17:52:00 -03:00
Roberto Ierusalimschy
b44e35b773 new constants LUA_NOREF and LUA_REFNIL. 1999-08-11 14:00:59 -03:00
Roberto Ierusalimschy
21843f022a writeto, readfrom, and closefile must return an error code when
closing a file.
1999-08-10 10:05:16 -03:00
Roberto Ierusalimschy
900257e814 char-set may contain '%]' 1999-08-10 09:55:56 -03:00
Roberto Ierusalimschy
a82c8185bc details 1999-08-10 09:55:47 -03:00
Roberto Ierusalimschy
4bbe0679a8 variables _INPUT and _OUTPUT should be read as rawglobal. 1999-07-22 16:35:50 -03:00
Roberto Ierusalimschy
438598aeea details. 1999-07-22 16:35:41 -03:00
Roberto Ierusalimschy
e9a670695a details 1999-07-22 16:29:42 -03:00
Roberto Ierusalimschy
16024861bd new format for numbers in precompiled code (as strings) 1999-07-08 09:43:23 -03:00
Roberto Ierusalimschy
3f43aaa23f new RedHat defines PI :-( 1999-07-07 14:54:08 -03:00
Roberto Ierusalimschy
3b4c831ca9 some systems do not reset signal handlers when a signal happens 1999-07-02 15:22:38 -03:00
Roberto Ierusalimschy
3fdab3981b no more automatic setlocale. 1999-06-24 16:42:02 -03:00
Roberto Ierusalimschy
88b65da4d7 simplifications. 1999-06-23 10:48:39 -03:00
Roberto Ierusalimschy
521b38532a better interfaces for luaD_calln (x luaD_call) 1999-06-22 17:37:23 -03:00
Roberto Ierusalimschy
36b6fe8d17 better treatment for arbitrary limits 1999-06-17 14:04:03 -03:00
Roberto Ierusalimschy
d4dce57f5c cannot assign to unlimited variables, because it causes overflow in
the number of returns of a function.
1999-06-16 10:35:01 -03:00
Roberto Ierusalimschy
5c19ed2a13 bigger limit for number of local variables and upvalues 1999-06-16 10:22:04 -03:00
Roberto Ierusalimschy
5caf7f4a33 tremove erases its previous last element (to avoid locking potential
garbagge).
1999-05-27 17:21:03 -03:00
Roberto Ierusalimschy
3b533ea7c7 foreach, foreachi, foreachvar points to function in stack when stack
can be reallocated.
1999-05-24 14:53:49 -03:00
Roberto Ierusalimschy
995775e1cb tighter control on the stack when debugging 1999-05-24 14:53:03 -03:00
Roberto Ierusalimschy
abfc885079 when debugging, move and erase old blocks to realloc. 1999-05-24 14:51:05 -03:00
Roberto Ierusalimschy
613b60c156 detail 1999-05-21 16:54:06 -03:00
Roberto Ierusalimschy
cdd0fe9946 some C compilers cannot initialize a local struct 1999-05-21 16:41:49 -03:00
Roberto Ierusalimschy
bc8619342a better control of stack size (only for DEBUG). 1999-05-21 14:23:15 -03:00
Roberto Ierusalimschy
48326500d0 longer marks when controling memory leaks 1999-05-20 17:43:06 -03:00
Roberto Ierusalimschy
c8d219798a lhf 1999-05-17 11:12:01 -03:00
Roberto Ierusalimschy
34695d4f4a details (message text) 1999-05-14 09:24:20 -03:00
Roberto Ierusalimschy
924bbe020b bigger limits 1999-05-14 09:24:04 -03:00
Roberto Ierusalimschy
3aa500b524 new pattern item '+' 1999-05-11 17:46:28 -03:00
Roberto Ierusalimschy
f1861ee210 no more beta 1999-05-11 17:29:19 -03:00
Roberto Ierusalimschy
705eae9fe4 there is no need for a size for Cblocks 1999-05-11 17:08:20 -03:00
Roberto Ierusalimschy
6eb1399a1c array Cblocks should grow dynamically 1999-05-11 11:19:32 -03:00
Roberto Ierusalimschy
c390f73e3b block must always have a power-of-2 size (even at the limit) 1999-05-11 11:18:40 -03:00
Roberto Ierusalimschy
73308c7605 warnings by clinio 1999-05-10 10:54:01 -03:00
Roberto Ierusalimschy
288fa05602 opcodes with LONGARG do not use byte variants. 1999-05-06 11:41:41 -03:00
Roberto Ierusalimschy
7808ea3a5f new implementation for '*' in patterns + new option '+' 1999-05-05 16:23:11 -03:00
Roberto Ierusalimschy
732741b62f cannot use (i=i+1) 1999-05-05 16:21:57 -03:00
Roberto Ierusalimschy
cc0f635ef7 '$' at end of pattern was matching regular '$', too. 1999-04-30 11:12:05 -03:00
Roberto Ierusalimschy
e64dbc390a new version is beta. 1999-04-15 09:33:19 -03:00
Roberto Ierusalimschy
a0fd8d1787 manual for 3.2 beta should be the same one that for 3.2. 1999-04-14 17:47:12 -03:00
Roberto Ierusalimschy
d9d04a9274 "read_pattern" could lock when reading a lookahead from stdin. 1999-04-14 17:40:32 -03:00
Roberto Ierusalimschy
b4ad600b93 numbers are stored in ascii format for better portability and simplicity 1999-04-13 17:16:37 -03:00
Roberto Ierusalimschy
cb7f027380 IMtable must be initialized (and IMtable_size is not needed any more) due
to new way to handle growing vectors (previous modification).
1999-04-13 16:30:51 -03:00
Roberto Ierusalimschy
0bbd96bd5f details. 1999-04-13 16:28:49 -03:00
Roberto Ierusalimschy
4eb67aa710 changes from lhf. 1999-04-07 13:40:04 -03:00
Roberto Ierusalimschy
0133610315 format for function prototypes. 1999-04-07 12:37:02 -03:00
Roberto Ierusalimschy
de04533dc0 better the old way, using upvalues to keep iotag. 1999-04-05 16:47:05 -03:00
Roberto Ierusalimschy
7c9aee64c2 new version by lhf. 1999-03-30 17:29:34 -03:00
Roberto Ierusalimschy
e0ff4e5d22 first version about Lua debug library. 1999-03-29 11:21:37 -03:00
Roberto Ierusalimschy
bf7f85d609 GC of files is tricky when Lua is being closed... 1999-03-26 10:48:26 -03:00
Roberto Ierusalimschy
a775a2d81a check first whether function is global. 1999-03-26 10:14:00 -03:00
Roberto Ierusalimschy
e9aa98d594 do not generate SETLINE after main (it will be after last line) 1999-03-25 18:06:57 -03:00
Roberto Ierusalimschy
3e9c6a8a24 details 1999-03-25 18:05:05 -03:00
Roberto Ierusalimschy
1f4e2ba7b2 more precise debug information about local variables 1999-03-23 16:58:37 -03:00
Roberto Ierusalimschy
d6ff06751a new functions openfile and closefile;
new way to keep file handle tags.
1999-03-16 17:07:54 -03:00
Roberto Ierusalimschy
7a11c7f8e4 details 1999-03-16 13:43:27 -03:00
Roberto Ierusalimschy
c454dc7bdd no more if expressions. 1999-03-11 16:00:12 -03:00
Roberto Ierusalimschy
82ad0d5770 details 1999-03-11 15:59:19 -03:00
Roberto Ierusalimschy
256d1bea08 missing #include 1999-03-10 11:23:07 -03:00
Roberto Ierusalimschy
f2d35bdc78 format for file source is independent of "ldo". 1999-03-10 11:19:41 -03:00
Roberto Ierusalimschy
2679461637 no more assignment expressions (they don't fit in Lua...) 1999-03-10 11:09:45 -03:00
Roberto Ierusalimschy
0870a2d1d8 new opcode TAILCALL 1999-03-05 18:16:07 -03:00
Roberto Ierusalimschy
78edc241e9 details about debug info. 1999-03-05 17:45:01 -03:00
Roberto Ierusalimschy
e907c711c0 "feof" may be a macro. 1999-03-05 10:15:50 -03:00
Roberto Ierusalimschy
5a8bb00df4 storing chunk "sources" instead of "filenames". 1999-03-04 18:23:39 -03:00
Roberto Ierusalimschy
677188de8a details. 1999-03-04 18:15:50 -03:00
Roberto Ierusalimschy
6233d21c9d file stream cannot call fread after EOF. 1999-03-04 11:50:26 -03:00
Roberto Ierusalimschy
ab8ea5c38a warnings 1999-03-01 17:22:16 -03:00
Roberto Ierusalimschy
ae9fd122fa vector do not need to grow until MINSIZE 1999-03-01 14:49:13 -03:00
Roberto Ierusalimschy
da18ec5d54 warnings... 1999-03-01 14:49:04 -03:00
Roberto Ierusalimschy
038848eccd better control of vector when DEBUGing 1999-02-26 12:50:10 -03:00
Roberto Ierusalimschy
b678e465a1 warnings in Solaris 1999-02-26 12:49:53 -03:00
Roberto Ierusalimschy
72d675aba7 macros "growvector" and "reallocvector" more compact 1999-02-26 12:48:55 -03:00
Roberto Ierusalimschy
ba57f7d946 details 1999-02-26 12:48:30 -03:00
Roberto Ierusalimschy
e63b542c9b comments 1999-02-26 12:19:54 -03:00
Roberto Ierusalimschy
6a853fcb8b details (from lhf) 1999-02-25 18:07:26 -03:00
Roberto Ierusalimschy
31bea2190b small correction 1999-02-25 16:20:40 -03:00
Roberto Ierusalimschy
4b954e9b2e details (from lhf) 1999-02-25 16:13:56 -03:00
Roberto Ierusalimschy
055823c04d "L->Mbuffbase" is better kept as offset instead of pointer 1999-02-25 12:17:01 -03:00
Roberto Ierusalimschy
26d1e21c89 new way to handle "growing" vectors 1999-02-25 12:16:26 -03:00
Roberto Ierusalimschy
24a2c08145 details 1999-02-24 18:31:03 -03:00
Roberto Ierusalimschy
9d7bae0b6a better instrumentation for internal debugging 1999-02-24 14:55:51 -03:00
Roberto Ierusalimschy
082aded149 warnings 1999-02-24 12:37:19 -03:00
Roberto Ierusalimschy
aa9c75c06e no more EXTRALIBS (and new dependencies) 1999-02-23 12:01:29 -03:00
Roberto Ierusalimschy
f04c83e075 new function "lua_next" (+ new implementation for "next") 1999-02-23 11:57:28 -03:00
Roberto Ierusalimschy
c364e9f97e LONGARGW (for completeness). 1999-02-23 10:38:38 -03:00
Roberto Ierusalimschy
e3a02e6a9c comments 1999-02-22 16:23:36 -03:00
Roberto Ierusalimschy
d5feffdb60 new function lua_nextvar 1999-02-22 16:13:12 -03:00
Roberto Ierusalimschy
bb5627f3a4 better control over calls to _ALERT and _ERRORMESSAGE (to avoid error
loops)
1999-02-22 11:17:24 -03:00
Roberto Ierusalimschy
21107d7c2c debug state is restored after a dofile/dostring 1999-02-22 10:51:44 -03:00
Roberto Ierusalimschy
b5cd7d426f details 1999-02-19 15:33:35 -02:00
Roberto Ierusalimschy
bf6d2ccf92 details 1999-02-12 17:23:02 -02:00
Roberto Ierusalimschy
b82ff713e3 new name for opcode 1999-02-09 16:01:55 -02:00
Roberto Ierusalimschy
77113ee02f new year for Copyright. 1999-02-09 13:59:22 -02:00
Roberto Ierusalimschy
ad6c7b0dd4 small corrections in opcodes. 1999-02-09 13:59:10 -02:00
Roberto Ierusalimschy
8b2d97d187 assignment expression may be multiple 1999-02-08 16:54:19 -02:00
Roberto Ierusalimschy
fb1cf6ab2d clearer way to set tables. 1999-02-08 15:07:59 -02:00
Roberto Ierusalimschy
19ca2087de another (silly) debuging function. 1999-02-08 14:29:35 -02:00
Roberto Ierusalimschy
7bdbd833b5 userdata and strings are kept in separate stringtables 1999-02-08 14:28:48 -02:00
Roberto Ierusalimschy
b22baf386d Lua cannot have static variables. 1999-02-05 13:22:43 -02:00
Roberto Ierusalimschy
8fdd06ba3c lots of new stuff from 3.2 1999-02-05 10:15:07 -02:00
Roberto Ierusalimschy
028ec00ab9 details 1999-02-05 09:22:58 -02:00
Roberto Ierusalimschy
1dcf1c9cbd format "%s" may break limit of "sprintf" on some machines. 1999-02-04 17:29:51 -02:00
Roberto Ierusalimschy
76179a1014 compile option EXTRALIB for builtin functions that can be written in Lua. 1999-02-04 17:12:35 -02:00
Roberto Ierusalimschy
bdfab46c22 "errorim" now is _ERRORMESSAGE. 1999-02-04 16:59:31 -02:00
Roberto Ierusalimschy
5687949560 "lua_debug", "lua_callhook" and "lua_linehook" must be inside "lua_state". 1999-02-04 15:47:59 -02:00
Roberto Ierusalimschy
19de5b2205 new dependencies 1999-02-04 14:37:41 -02:00
Roberto Ierusalimschy
cbc58af260 new opcode for "long" arguments (3 bytes) 1999-02-04 14:36:16 -02:00
Roberto Ierusalimschy
80001ab0eb getlocal cannot return the local itself, since lua_isstring and
lua_isnumber can modify it.
1999-02-03 14:42:42 -02:00
Roberto Ierusalimschy
ae29ab9858 only parser uses MAX_WORD 1999-02-03 11:53:48 -02:00
Roberto Ierusalimschy
27407fc1f5 new syntax: assignment expressions + better order for opcodes 1999-02-02 17:41:17 -02:00
Roberto Ierusalimschy
1a17da2ff9 opcodes with builtin parameters are too complicated for very little extra
performance.
1999-02-02 15:57:49 -02:00
Roberto Ierusalimschy
50248e440a "if" expression leaves only one of its expressions on the stack 1999-02-02 11:47:31 -02:00
Roberto Ierusalimschy
0f0079f394 "if" expressions. 1999-02-01 16:52:05 -02:00
Roberto Ierusalimschy
68267ed878 negative numerals do not need a MINUSOPeration; go directly to contant
table.
1999-01-29 11:48:58 -02:00
Roberto Ierusalimschy
fd25d4ad85 no need to define functions for macros... 1999-01-26 13:38:01 -02:00
Roberto Ierusalimschy
2431534f10 details 1999-01-26 09:50:58 -02:00
Roberto Ierusalimschy
fd7d0774e5 luaH_set does the set and protect its value; luaH_move can then be a
macro.
New algorithm for double hashing (does not use "%").
1999-01-25 15:41:19 -02:00
Roberto Ierusalimschy
57ffc3f009 luaH_set does the set, and protects its value, so luaH_move can be a
macro.
1999-01-25 15:40:10 -02:00
Roberto Ierusalimschy
4a13f513f8 luaH_set does the set! 1999-01-25 15:39:28 -02:00
Roberto Ierusalimschy
13ad46b67d uses the same double hashing that is used for tables 1999-01-25 15:38:04 -02:00
Roberto Ierusalimschy
1b45e967b4 table entries with ref=null always have val=null too. 1999-01-25 10:30:11 -02:00
Roberto Ierusalimschy
933bead92e small optimizations(?) 1999-01-22 16:47:23 -02:00
Roberto Ierusalimschy
3314f49ec4 C cannot initialize a struct. 1999-01-22 16:46:11 -02:00
Roberto Ierusalimschy
bc930aa5ff "free" usually handles NULL; handle non ANSI case separately. 1999-01-22 16:08:57 -02:00
Roberto Ierusalimschy
67b44c9493 local names are all in the constant pool, so they do not need to be
marked in GC.
1999-01-22 16:08:03 -02:00
Roberto Ierusalimschy
758a381644 "realloc" usually implements "malloc"; handle non ANSI case separately. 1999-01-22 15:28:00 -02:00
Roberto Ierusalimschy
eec31aaca5 <string.h> is needed because of "memcpy". 1999-01-21 16:38:39 -02:00
Roberto Ierusalimschy
595738f6fe small optimizations 1999-01-20 18:22:06 -02:00
Roberto Ierusalimschy
b5eb4f3126 small optimization in getglobal 1999-01-15 11:14:24 -02:00
Roberto Ierusalimschy
3fecf187ff names... 1999-01-15 11:11:57 -02:00
Roberto Ierusalimschy
54840fb256 new functions to manipulate C global variables 1999-01-15 11:11:22 -02:00
Roberto Ierusalimschy
e87fddf1ad GC can be called during parsing, if needed. 1999-01-15 09:38:33 -02:00
Roberto Ierusalimschy
dea400bc1d "getstack" returns func, too. 1999-01-15 09:36:28 -02:00
Roberto Ierusalimschy
fb663f768d "%.16g" already formats integers as integers, so we do not need an
alternative "%ld" convertion in "tostring".
1999-01-13 17:09:04 -02:00
Roberto Ierusalimschy
e03767b3eb details (comments) 1999-01-13 17:08:37 -02:00
Roberto Ierusalimschy
8396027516 better precision when converting numbers to strings. 1999-01-12 16:38:35 -02:00
Roberto Ierusalimschy
e24f7fd2d2 details 1999-01-11 18:23:54 -02:00
Roberto Ierusalimschy
8081f39dab header missing. 1999-01-11 16:57:35 -02:00
Roberto Ierusalimschy
3cc4ca821e initialization module (to load libraries) 1999-01-08 14:49:32 -02:00
Roberto Ierusalimschy
01772cefa5 new library for debbuging 1999-01-08 14:47:44 -02:00
Roberto Ierusalimschy
dc90d4bce3 when handling signals (^C), deep old hook values. 1999-01-06 11:12:41 -02:00
Roberto Ierusalimschy
f5bc671030 "goto" for tail recursion changed to "while" 1999-01-04 15:34:49 -02:00
Roberto Ierusalimschy
d7294c6de8 double hashing for string tables. 1999-01-04 11:37:29 -02:00
Roberto Ierusalimschy
63a752f961 small improvements. 1999-01-04 11:37:07 -02:00
Roberto Ierusalimschy
03d38b66fd new sort algorithm. 1999-01-04 10:55:09 -02:00
Roberto Ierusalimschy
b9c9ccfbb4 function "move" for tables is better implemented with some "inside
information".
1999-01-04 10:54:33 -02:00
Roberto Ierusalimschy
b94110a68f bug: "format" does not check size of format item (such as "%00000...00000d"). 1999-01-04 10:53:24 -02:00
Roberto Ierusalimschy
8278468041 comments 1999-01-04 10:41:12 -02:00
Roberto Ierusalimschy
4fbb2531b3 don´t need the "+1", the "%" is enough to garantee r<1. 1998-12-30 19:23:26 -02:00
Roberto Ierusalimschy
59f8e6fb77 details ("settable") 1998-12-30 15:26:49 -02:00
Roberto Ierusalimschy
05d89b5c05 new option for function "random": random(a,b) returns a<=x<=b 1998-12-30 15:22:17 -02:00
Roberto Ierusalimschy
fe5c41fb8a new functions "tinsert" and "tremove" 1998-12-30 11:16:50 -02:00
Roberto Ierusalimschy
9a45543841 tables are better manipulated via "Hash *" instead of "TObject" or
"lua_Object".
1998-12-30 11:14:46 -02:00
Roberto Ierusalimschy
766e67ef3b to avoid warnings about "typecast" (Visual C++) 1998-12-28 11:44:54 -02:00
Roberto Ierusalimschy
4c94d8cc2c new function "luaO_str2d" to convert strings to numbers, because
old "lex" algorithm had aproximation errors, but strtod (and atof
and scanf) are too slow.
1998-12-27 18:25:20 -02:00
Roberto Ierusalimschy
d2de2d5eda format for double is always "%g", do not need #defines 1998-12-27 18:23:22 -02:00
Roberto Ierusalimschy
96a7695275 reorder and rename of most functions, for better documentation. 1998-12-27 18:22:36 -02:00
Roberto Ierusalimschy
63166c0ca0 new implementation of function "read", with predifined options. 1998-12-27 18:21:28 -02:00
Roberto Ierusalimschy
a881abfd1e "strtod" is cleaner than "scanf" for this job. 1998-12-24 12:57:23 -02:00
Roberto Ierusalimschy
d3ac7075a2 better error message 1998-12-23 12:06:57 -02:00
Roberto Ierusalimschy
0c9080c7a9 "tonumber" goes crazy with negative numbers in other bases (not 10),
because "strtol" returns long, not unsigned long.
1998-12-18 11:26:43 -02:00
Roberto Ierusalimschy
b8fcb7b151 details 1998-12-15 13:21:09 -02:00
Roberto Ierusalimschy
5d6de9075d "print" uses fputs instead of printf (easier to reimplement). 1998-12-15 12:59:59 -02:00
Roberto Ierusalimschy
21cff3015a details (for regularity) 1998-12-15 12:59:43 -02:00
Roberto Ierusalimschy
5ca2709ba0 small warnings 1998-12-03 13:45:15 -02:00
Roberto Ierusalimschy
bb1cb7b9f1 NUMBER_FMT also may be predefined in makefile 1998-12-01 17:09:47 -02:00
Roberto Ierusalimschy
c64f36ab2b better behavior for "strsub" when indices are out-of-range 1998-12-01 16:41:25 -02:00
Roberto Ierusalimschy
e4830ddce3 new option "mode" in "readfrom", "writeto" and "appendto" (for
binary files).
1998-11-20 13:41:43 -02:00
Roberto Ierusalimschy
758e330d6e new functions "getn" and "foreachi" 1998-11-13 14:48:48 -02:00
Roberto Ierusalimschy
8e3bd752bb small optimization in "sort" + new functions "getn" and "foreachi" 1998-11-13 14:39:18 -02:00
Roberto Ierusalimschy
a84bca67fc bug: gsub/strfind do not check whether captures are properly finished. 1998-11-10 17:38:12 -02:00
Roberto Ierusalimschy
4ccfb2f9bc "_TRIGMODE" was still being declared. 1998-09-08 16:25:35 -03:00
Roberto Ierusalimschy
ce9609296c function "luaL_argerror" prints wrong argument number (from a user's point
of view) when functions have upvalues.
1998-09-07 15:59:59 -03:00
Roberto Ierusalimschy
b1450721be new function "lua_nups" (number of upvalues). 1998-09-07 15:59:59 -03:00
Roberto Ierusalimschy
b04294d3d8 details. 1998-08-30 17:25:24 -03:00
Roberto Ierusalimschy
22c2704842 "lua_state" is already declared in lua.h, which is included here. 1998-08-30 15:28:58 -03:00
Roberto Ierusalimschy
ee22af5ced new functions "seek" and "flush". 1998-08-24 17:14:56 -03:00
Roberto Ierusalimschy
cc117253c8 new implementation for error handling: on error, function _ERRORMESSAGE
is called, which in turn calls _ALERT to write a message to stderr.
1998-08-21 14:43:44 -03:00
Roberto Ierusalimschy
8e226e6a09 small bug: nuse may change when table is rehashed;
3/2 is a good fraction for hash limit (instead of 0.7, using floats)
1998-08-11 13:38:34 -03:00
Roberto Ierusalimschy
1d420c2c11 better error message for code too long (old one was misleading when the
problem was SETLINE after 64k lines...)
1998-08-11 10:28:05 -03:00
Roberto Ierusalimschy
5378331f2d hash tables may shrink if use rate is too small. 1998-08-10 18:36:32 -03:00
Roberto Ierusalimschy
894a264671 new hash function. 1998-07-27 14:06:17 -03:00
Roberto Ierusalimschy
e1a127245d details ("luaX_token2str" doesn't need LexState) 1998-07-24 15:02:38 -03:00
Roberto Ierusalimschy
afb5ef72e1 new function "sort" + many small changes 1998-07-12 13:16:43 -03:00
Roberto Ierusalimschy
1d8edd347d small changes to use new auxiliar functions 1998-07-12 13:16:02 -03:00
Roberto Ierusalimschy
41d9ea948c auxiliar functions "luaH_setint" & "luaH_getint". 1998-07-12 13:15:19 -03:00
Roberto Ierusalimschy
ee912e5a7f auxiliar function "luaD_calln". 1998-07-12 13:14:34 -03:00
Roberto Ierusalimschy
ad446a0eb0 "%q" can handle strings with '\0'. 1998-07-12 13:13:45 -03:00
Roberto Ierusalimschy
176cb39feb macro encapsulates de "-". 1998-07-12 13:11:55 -03:00
Roberto Ierusalimschy
64ad009fb2 "fileName" cannot be NULL 1998-07-12 13:10:38 -03:00
56 changed files with 9202 additions and 6556 deletions

133
bugs
View File

@@ -1,9 +1,12 @@
** lua.stx / llex.c
Tue Dec 2 10:45:48 EDT 1997
>> BUG: "lastline" was not reset on function entry, so debug information
>> started only in the 2nd line of a function.
=================================================================
--- Version 3.1 alpha
** lua.c
@@ -13,7 +16,7 @@ Thu Jan 15 14:34:58 EDT 1998
** lbuiltin.c / lobject.h
Thu Jan 15 14:34:58 EDT 1998
>> MAX_WORD may be bigger than MAX_INT
(by lhf)
** llex.c
Mon Jan 19 18:17:18 EDT 1998
@@ -31,7 +34,7 @@ Tue Jan 27 17:12:36 EDT 1998
** lstring.c / ltable.c
Wed Jan 28 14:48:12 EDT 1998
>> tables can become full of "emptys" slots, and keep growing without limits.
>> tables can become full of "empty" slots, and keep growing without limits.
** lstrlib.c
Mon Mar 9 15:26:09 EST 1998
@@ -41,3 +44,129 @@ Mon Mar 9 15:26:09 EST 1998
Mon May 18 19:20:00 EST 1998
>> arguments for "format" 'x', 'X', 'o' and 'u' must be unsigned int.
=================================================================
--- Version 3.1
** liolib.c / lauxlib.c
Mon Sep 7 15:57:02 EST 1998
>> function "luaL_argerror" prints wrong argument number (from a user's point
of view) when functions have upvalues.
** lstrlib.c
Tue Nov 10 17:29:36 EDT 1998
>> gsub/strfind do not check whether captures are properly finished.
(by roberto/tomas)
** lbuiltin.c
Fri Dec 18 11:22:55 EDT 1998
>> "tonumber" goes crazy with negative numbers in other bases (not 10),
because "strtol" returns long, not unsigned long.
(by Visual C++)
** lstrlib.c
Mon Jan 4 10:41:40 EDT 1999
>> "format" does not check size of format item (such as "%00000...00000d").
** lapi.c
Wed Feb 3 14:40:21 EDT 1999
>> getlocal cannot return the local itself, since lua_isstring and
lua_isnumber can modify it.
** lstrlib.c
Thu Feb 4 17:08:50 EDT 1999
>> format "%s" may break limit of "sprintf" on some machines.
(by Marcelo Sales)
** lzio.c
Thu Mar 4 11:49:37 EST 1999
>> file stream cannot call fread after EOF.
(by lhf)
=================================================================
--- Version 3.2 (beta)
** lstrlib.c
Fri Apr 30 11:10:20 EST 1999
>> '$' at end of pattern was matching regular '$', too.
(by anna; since 2.5)
** lbuiltin.c
Fri May 21 17:15:11 EST 1999
>> foreach, foreachi, foreachvar points to function in stack when stack
can be reallocated.
(by tomas; since 3.2 beta)
** lparser.c
Wed Jun 16 10:32:46 EST 1999
>> cannot assign to unlimited variables, because it causes overflow in
the number of returns of a function.
(since 3.1)
=================================================================
--- Version 3.2
** lmathlib.c
Wed Aug 18 11:28:38 EST 1999
>> random(0) and random(x,0) are wrong (0 is read as no argument!).
(by Dave Bollinger; since 3.1)
** lparser.c
Thu Sep 2 10:07:20 EST 1999
>> in the (old) expression << ls->fs->f->consts[checkname(ls)] >>, checkname
could realloc f->consts.
(by Supratik Champati; since 3.2 beta)
** lobject.c / lbuiltin.c
Wed Sep 8 17:41:54 EST 1999
>> tonumber'e1' and tonumber(' ', x), for x!=10, gave 0 instead of nil.
(since 3.1)
** lstrlib.c
Thu Nov 11 14:36:30 EDT 1999
>> `strfind' does not handle \0 in plain search.
(by Jon Kleiser; since 3.1)
** lparser.c
Wed Dec 29 16:05:43 EDT 1999
>> return gives wrong line in debug information
(by lhf; since 3.2 [at least])
** ldo.c
Thu Dec 30 16:39:33 EDT 1999
>> cannot reopen stdin (for binary mode)
(by lhf & roberto; since 3.1)
** lapi.c
Thu Mar 2 09:41:53 EST 2000
>> lua_settable should check stack space (it could call a T.M.)
(by lhf & celes; since 3.2; it was already fixed by fixed stack)
** lparser.c
Mon Apr 3 09:59:06 EST 2000
>> '%' should be in expfollow
(by Edgar Toernig; since 3.1; it was already fixed)
** lbuiltin.c
Mon Apr 3 10:05:05 EST 2000
>> tostring() without arguments gives seg. fault.
(by Edgar Toernig; since 3.0)
=================================================================
--- Version 4.0 alpha
Tested with full test suites (as locked in Mon Apr 24 14:23:11 EST 2000)
in the following platforms:
* Linux - gcc, g++
* AIX - gcc
* Solaris - gcc, cc
* IRIX - cc, cc-purify
* Windows - Visual C++ (.c e .cpp, warning level=4)

678
lapi.c
View File

@@ -1,13 +1,14 @@
/*
** $Id: lapi.c,v 1.24 1998/03/09 21:49:52 roberto Exp roberto $
** $Id: lapi.c,v 1.77 2000/03/29 20:19:20 roberto Exp roberto $
** Lua API
** See Copyright Notice in lua.h
*/
#include <stdlib.h>
#include <string.h>
#define LUA_REENTRANT
#include "lapi.h"
#include "lauxlib.h"
#include "ldo.h"
@@ -15,617 +16,378 @@
#include "lgc.h"
#include "lmem.h"
#include "lobject.h"
#include "lref.h"
#include "lstate.h"
#include "lstring.h"
#include "ltable.h"
#include "ltm.h"
#include "lua.h"
#include "luadebug.h"
#include "lvm.h"
char lua_ident[] = "$Lua: " LUA_VERSION " " LUA_COPYRIGHT " $\n"
"$Autores: " LUA_AUTHORS " $";
const char lua_ident[] = "$Lua: " LUA_VERSION " " LUA_COPYRIGHT " $\n"
"$Authors: " LUA_AUTHORS " $";
TObject *luaA_Address (lua_Object o)
{
return Address(o);
void luaA_checkCargs (lua_State *L, int nargs) {
if (nargs > L->top-L->Cstack.base)
luaL_verror(L, "Lua API error - "
"expected at least %d arguments in C2lua stack", nargs);
}
static int normalized_type (TObject *o)
{
int t = ttype(o);
switch (t) {
case LUA_T_PMARK:
return LUA_T_PROTO;
case LUA_T_CMARK:
return LUA_T_CPROTO;
case LUA_T_CLMARK:
return LUA_T_CLOSURE;
default:
return t;
}
lua_Object luaA_putluaObject (lua_State *L, const TObject *o) {
luaD_openstack(L, L->Cstack.base);
*L->Cstack.base++ = *o;
return L->Cstack.base-1;
}
static void set_normalized (TObject *d, TObject *s)
{
d->value = s->value;
d->ttype = normalized_type(s);
lua_Object luaA_putObjectOnTop (lua_State *L) {
luaD_openstack(L, L->Cstack.base);
*L->Cstack.base++ = *(--L->top);
return L->Cstack.base-1;
}
static TObject *luaA_protovalue (TObject *o)
{
return (normalized_type(o) == LUA_T_CLOSURE) ? protovalue(o) : o;
static void top2LC (lua_State *L, int n) {
/* Put the `n' elements on the top as the Lua2C contents */
L->Cstack.base = L->top; /* new base */
L->Cstack.lua2C = L->Cstack.base-n; /* position of the new results */
L->Cstack.num = n; /* number of results */
}
void luaA_packresults (void)
{
luaV_pack(L->Cstack.lua2C, L->Cstack.num, L->stack.top);
incr_top;
}
int luaA_passresults (void)
{
luaD_checkstack(L->Cstack.num);
memcpy(L->stack.top, L->Cstack.lua2C+L->stack.stack,
L->Cstack.num*sizeof(TObject));
L->stack.top += L->Cstack.num;
return L->Cstack.num;
}
static void checkCparams (int nParams)
{
if (L->stack.top-L->stack.stack < L->Cstack.base+nParams)
lua_error("API error - wrong number of arguments in C2lua stack");
}
static lua_Object put_luaObject (TObject *o)
{
luaD_openstack((L->stack.top-L->stack.stack)-L->Cstack.base);
L->stack.stack[L->Cstack.base++] = *o;
return L->Cstack.base; /* this is +1 real position (see Ref) */
}
static lua_Object put_luaObjectonTop (void)
{
luaD_openstack((L->stack.top-L->stack.stack)-L->Cstack.base);
L->stack.stack[L->Cstack.base++] = *(--L->stack.top);
return L->Cstack.base; /* this is +1 real position (see Ref) */
}
lua_Object lua_pop (void)
{
checkCparams(1);
return put_luaObjectonTop();
lua_Object lua_pop (lua_State *L) {
luaA_checkCargs(L, 1);
return luaA_putObjectOnTop(L);
}
/*
** Get a parameter, returning the object handle or LUA_NOOBJECT on error.
** 'number' must be 1 to get the first parameter.
** `number' must be 1 to get the first parameter.
*/
lua_Object lua_lua2C (int number)
{
lua_Object lua_lua2C (lua_State *L, int number) {
if (number <= 0 || number > L->Cstack.num) return LUA_NOOBJECT;
/* Ref(L->stack.stack+(L->Cstack.lua2C+number-1)) ==
L->stack.stack+(L->Cstack.lua2C+number-1)-L->stack.stack+1 == */
return L->Cstack.lua2C+number;
return L->Cstack.lua2C+number-1;
}
int lua_callfunction (lua_Object function)
{
int lua_callfunction (lua_State *L, lua_Object function) {
if (function == LUA_NOOBJECT)
return 1;
else {
luaD_openstack((L->stack.top-L->stack.stack)-L->Cstack.base);
set_normalized(L->stack.stack+L->Cstack.base, Address(function));
return luaD_protectedrun(MULT_RET);
luaD_openstack(L, L->Cstack.base);
*L->Cstack.base = *function;
return luaD_protectedrun(L);
}
}
lua_Object lua_gettagmethod (int tag, char *event)
{
return put_luaObject(luaT_gettagmethod(tag, event));
lua_Object lua_gettagmethod (lua_State *L, int tag, const char *event) {
return luaA_putluaObject(L, luaT_gettagmethod(L, tag, event));
}
lua_Object lua_settagmethod (int tag, char *event)
{
checkCparams(1);
luaT_settagmethod(tag, event, L->stack.top-1);
return put_luaObjectonTop();
lua_Object lua_settagmethod (lua_State *L, int tag, const char *event) {
TObject *method;
luaA_checkCargs(L, 1);
method = L->top-1;
if ((ttype(method) != TAG_NIL) && (*lua_type(L, method) != 'f'))
lua_error(L, "Lua API error - tag method must be a function or nil");
luaT_settagmethod(L, tag, event, method);
return luaA_putObjectOnTop(L);
}
lua_Object lua_seterrormethod (void)
{
TObject temp = L->errorim;
checkCparams(1);
L->errorim = *(--L->stack.top);
return put_luaObject(&temp);
lua_Object lua_gettable (lua_State *L) {
luaA_checkCargs(L, 2);
luaV_gettable(L, L->top--);
return luaA_putObjectOnTop(L);
}
lua_Object lua_gettable (void)
{
checkCparams(2);
luaV_gettable();
return put_luaObjectonTop();
lua_Object lua_rawgettable (lua_State *L) {
lua_Object res;
luaA_checkCargs(L, 2);
if (ttype(L->top-2) != TAG_TABLE)
lua_error(L, "indexed expression not a table in rawgettable");
res = luaA_putluaObject(L, luaH_get(L, avalue(L->top-2), L->top-1));
L->top -= 2;
return res;
}
lua_Object lua_rawgettable (void)
{
checkCparams(2);
if (ttype(L->stack.top-2) != LUA_T_ARRAY)
lua_error("indexed expression not a table in rawgettable");
else {
TObject *h = luaH_get(avalue(L->stack.top-2), L->stack.top-1);
--L->stack.top;
if (h != NULL)
*(L->stack.top-1) = *h;
else
ttype(L->stack.top-1) = LUA_T_NIL;
}
return put_luaObjectonTop();
void lua_settable (lua_State *L) {
StkId top;
luaA_checkCargs(L, 3);
top = L->top;
luaV_settable(L, top-3, top);
L->top = top-3; /* pop table, index, and value */
}
void lua_settable (void)
{
checkCparams(3);
luaV_settable(L->stack.top-3, 1);
void lua_rawsettable (lua_State *L) {
luaA_checkCargs(L, 3);
luaV_rawsettable(L, L->top-3);
}
void lua_rawsettable (void)
{
checkCparams(3);
luaV_settable(L->stack.top-3, 0);
}
lua_Object lua_createtable (void)
{
lua_Object lua_createtable (lua_State *L) {
TObject o;
luaC_checkGC();
avalue(&o) = luaH_new(0);
ttype(&o) = LUA_T_ARRAY;
return put_luaObject(&o);
luaC_checkGC(L);
avalue(&o) = luaH_new(L, 0);
ttype(&o) = TAG_TABLE;
return luaA_putluaObject(L, &o);
}
lua_Object lua_getglobal (char *name)
{
luaD_checkstack(2); /* may need that to call T.M. */
luaV_getglobal(luaS_new(name));
return put_luaObjectonTop();
lua_Object lua_getglobal (lua_State *L, const char *name) {
luaV_getglobal(L, luaS_assertglobalbyname(L, name), L->top++);
return luaA_putObjectOnTop(L);
}
lua_Object lua_rawgetglobal (char *name)
{
TaggedString *ts = luaS_new(name);
return put_luaObject(&ts->u.s.globalval);
lua_Object lua_rawgetglobal (lua_State *L, const char *name) {
GlobalVar *gv = luaS_assertglobalbyname(L, name);
return luaA_putluaObject(L, &gv->value);
}
void lua_setglobal (char *name)
{
checkCparams(1);
luaD_checkstack(2); /* may need that to call T.M. */
luaV_setglobal(luaS_new(name));
void lua_setglobal (lua_State *L, const char *name) {
luaA_checkCargs(L, 1);
luaV_setglobal(L, luaS_assertglobalbyname(L, name), L->top--);
}
void lua_rawsetglobal (char *name)
{
TaggedString *ts = luaS_new(name);
checkCparams(1);
luaS_rawsetglobal(ts, --L->stack.top);
void lua_rawsetglobal (lua_State *L, const char *name) {
GlobalVar *gv = luaS_assertglobalbyname(L, name);
luaA_checkCargs(L, 1);
gv->value = *(--L->top);
}
int lua_isnil (lua_Object o)
{
return (o!= LUA_NOOBJECT) && (ttype(Address(o)) == LUA_T_NIL);
const char *lua_type (lua_State *L, lua_Object o) {
UNUSED(L);
return (o == LUA_NOOBJECT) ? "NOOBJECT" : luaO_typename(o);
}
int lua_istable (lua_Object o)
{
return (o!= LUA_NOOBJECT) && (ttype(Address(o)) == LUA_T_ARRAY);
int lua_isnil (lua_State *L, lua_Object o) {
UNUSED(L);
return (o != LUA_NOOBJECT) && (ttype(o) == TAG_NIL);
}
int lua_isuserdata (lua_Object o)
{
return (o!= LUA_NOOBJECT) && (ttype(Address(o)) == LUA_T_USERDATA);
int lua_istable (lua_State *L, lua_Object o) {
UNUSED(L);
return (o != LUA_NOOBJECT) && (ttype(o) == TAG_TABLE);
}
int lua_iscfunction (lua_Object o)
{
return (lua_tag(o) == LUA_T_CPROTO);
int lua_isuserdata (lua_State *L, lua_Object o) {
UNUSED(L);
return (o != LUA_NOOBJECT) && (ttype(o) == TAG_USERDATA);
}
int lua_isnumber (lua_Object o)
{
return (o!= LUA_NOOBJECT) && (tonumber(Address(o)) == 0);
int lua_iscfunction (lua_State *L, lua_Object o) {
UNUSED(L);
return (o != LUA_NOOBJECT) && (ttype(o) == TAG_CCLOSURE);
}
int lua_isstring (lua_Object o)
{
int t = lua_tag(o);
return (t == LUA_T_STRING) || (t == LUA_T_NUMBER);
int lua_isnumber (lua_State *L, lua_Object o) {
UNUSED(L);
return (o != LUA_NOOBJECT) && (tonumber(o) == 0);
}
int lua_isfunction (lua_Object o)
{
int t = lua_tag(o);
return (t == LUA_T_PROTO) || (t == LUA_T_CPROTO);
int lua_isstring (lua_State *L, lua_Object o) {
UNUSED(L);
return (o != LUA_NOOBJECT && (ttype(o) == TAG_STRING ||
ttype(o) == TAG_NUMBER));
}
int lua_isfunction (lua_State *L, lua_Object o) {
return *lua_type(L, o) == 'f';
}
int lua_equal(lua_State *L, lua_Object o1, lua_Object o2) {
UNUSED(L);
if (o1 == LUA_NOOBJECT || o2 == LUA_NOOBJECT)
return (o1 == o2);
else return luaO_equalObj(o1, o2);
}
double lua_getnumber (lua_Object object)
{
if (object == LUA_NOOBJECT) return 0.0;
if (tonumber(Address(object))) return 0.0;
else return (nvalue(Address(object)));
double lua_getnumber (lua_State *L, lua_Object obj) {
UNUSED(L);
if (obj == LUA_NOOBJECT || tonumber(obj))
return 0.0;
else return (nvalue(obj));
}
char *lua_getstring (lua_Object object)
{
luaC_checkGC(); /* "tostring" may create a new string */
if (object == LUA_NOOBJECT || tostring(Address(object)))
const char *lua_getstring (lua_State *L, lua_Object obj) {
luaC_checkGC(L); /* `tostring' may create a new string */
if (obj == LUA_NOOBJECT || tostring(L, obj))
return NULL;
else return (svalue(Address(object)));
else return (svalue(obj));
}
long lua_strlen (lua_Object object)
{
luaC_checkGC(); /* "tostring" may create a new string */
if (object == LUA_NOOBJECT || tostring(Address(object)))
long lua_strlen (lua_State *L, lua_Object obj) {
if (obj == LUA_NOOBJECT || tostring(L, obj))
return 0L;
else return (tsvalue(Address(object))->u.s.len);
else return (tsvalue(obj)->u.s.len);
}
void *lua_getuserdata (lua_Object object)
{
if (object == LUA_NOOBJECT || ttype(Address(object)) != LUA_T_USERDATA)
void *lua_getuserdata (lua_State *L, lua_Object obj) {
UNUSED(L);
if (obj == LUA_NOOBJECT || ttype(obj) != TAG_USERDATA)
return NULL;
else return tsvalue(Address(object))->u.d.v;
else return tsvalue(obj)->u.d.value;
}
lua_CFunction lua_getcfunction (lua_Object object)
{
if (!lua_iscfunction(object))
lua_CFunction lua_getcfunction (lua_State *L, lua_Object obj) {
if (!lua_iscfunction(L, obj))
return NULL;
else return fvalue(luaA_protovalue(Address(object)));
else return clvalue(obj)->f.c;
}
void lua_pushnil (void)
{
ttype(L->stack.top) = LUA_T_NIL;
void lua_pushnil (lua_State *L) {
ttype(L->top) = TAG_NIL;
incr_top;
}
void lua_pushnumber (double n)
{
ttype(L->stack.top) = LUA_T_NUMBER;
nvalue(L->stack.top) = n;
void lua_pushnumber (lua_State *L, double n) {
ttype(L->top) = TAG_NUMBER;
nvalue(L->top) = n;
incr_top;
}
void lua_pushlstring (char *s, long len)
{
tsvalue(L->stack.top) = luaS_newlstr(s, len);
ttype(L->stack.top) = LUA_T_STRING;
void lua_pushlstring (lua_State *L, const char *s, long len) {
tsvalue(L->top) = luaS_newlstr(L, s, len);
ttype(L->top) = TAG_STRING;
incr_top;
luaC_checkGC();
luaC_checkGC(L);
}
void lua_pushstring (char *s)
{
void lua_pushstring (lua_State *L, const char *s) {
if (s == NULL)
lua_pushnil();
lua_pushnil(L);
else
lua_pushlstring(s, strlen(s));
lua_pushlstring(L, s, strlen(s));
}
void lua_pushcclosure (lua_CFunction fn, int n)
{
void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n) {
if (fn == NULL)
lua_error("API error - attempt to push a NULL Cfunction");
checkCparams(n);
ttype(L->stack.top) = LUA_T_CPROTO;
fvalue(L->stack.top) = fn;
incr_top;
luaV_closure(n);
luaC_checkGC();
lua_error(L, "Lua API error - attempt to push a NULL Cfunction");
luaA_checkCargs(L, n);
luaV_Cclosure(L, fn, n);
luaC_checkGC(L);
}
void lua_pushusertag (void *u, int tag)
{
if (tag < 0 && tag != LUA_ANYTAG)
luaT_realtag(tag); /* error if tag is not valid */
tsvalue(L->stack.top) = luaS_createudata(u, tag);
ttype(L->stack.top) = LUA_T_USERDATA;
void lua_pushusertag (lua_State *L, void *u, int tag) { /* ORDER LUA_T */
if (tag != LUA_ANYTAG && tag != TAG_USERDATA && tag < NUM_TAGS)
luaL_verror(L, "invalid tag for a userdata (%d)", tag);
tsvalue(L->top) = luaS_createudata(L, u, tag);
ttype(L->top) = TAG_USERDATA;
incr_top;
luaC_checkGC();
luaC_checkGC(L);
}
void luaA_pushobject (TObject *o)
{
*L->stack.top = *o;
void luaA_pushobject (lua_State *L, const TObject *o) {
*L->top = *o;
incr_top;
}
void lua_pushobject (lua_Object o)
{
void lua_pushobject (lua_State *L, lua_Object o) {
if (o == LUA_NOOBJECT)
lua_error("API error - attempt to push a NOOBJECT");
else {
set_normalized(L->stack.top, Address(o));
incr_top;
}
lua_error(L, "Lua API error - attempt to push a NOOBJECT");
*L->top = *o;
incr_top;
}
int lua_tag (lua_Object lo)
{
if (lo == LUA_NOOBJECT)
return LUA_T_NIL;
else {
TObject *o = Address(lo);
int t;
switch (t = ttype(o)) {
case LUA_T_USERDATA:
return o->value.ts->u.d.tag;
case LUA_T_ARRAY:
return o->value.a->htag;
case LUA_T_PMARK:
return LUA_T_PROTO;
case LUA_T_CMARK:
return LUA_T_CPROTO;
case LUA_T_CLOSURE: case LUA_T_CLMARK:
return o->value.cl->consts[0].ttype;
#ifdef DEBUG
case LUA_T_LINE:
LUA_INTERNALERROR("invalid type");
#endif
default:
return t;
}
}
int lua_tag (lua_State *L, lua_Object o) {
if (o == LUA_NOOBJECT)
return TAG_NIL;
else if (ttype(o) == TAG_USERDATA) /* to allow `old' tags (deprecated) */
return o->value.ts->u.d.tag;
else
return luaT_effectivetag(L, o);
}
void lua_settag (int tag)
{
checkCparams(1);
luaT_realtag(tag);
switch (ttype(L->stack.top-1)) {
case LUA_T_ARRAY:
(L->stack.top-1)->value.a->htag = tag;
void lua_settag (lua_State *L, int tag) {
luaA_checkCargs(L, 1);
luaT_realtag(L, tag);
switch (ttype(L->top-1)) {
case TAG_TABLE:
(L->top-1)->value.a->htag = tag;
break;
case LUA_T_USERDATA:
(L->stack.top-1)->value.ts->u.d.tag = tag;
case TAG_USERDATA:
(L->top-1)->value.ts->u.d.tag = tag;
break;
default:
luaL_verror("cannot change the tag of a %.20s",
luaO_typenames[-ttype((L->stack.top-1))]);
luaL_verror(L, "cannot change the tag of a %.20s",
luaO_typename(L->top-1));
}
L->stack.top--;
L->top--;
}
/*
** =======================================================
** Debug interface
** =======================================================
*/
/* Hooks */
lua_CHFunction lua_callhook = NULL;
lua_LHFunction lua_linehook = NULL;
lua_Function lua_stackedfunction (int level)
{
StkId i;
for (i = (L->stack.top-1)-L->stack.stack; i>=0; i--) {
int t = L->stack.stack[i].ttype;
if (t == LUA_T_CLMARK || t == LUA_T_PMARK || t == LUA_T_CMARK)
if (level-- == 0)
return Ref(L->stack.stack+i);
}
return LUA_NOOBJECT;
}
int lua_currentline (lua_Function func)
{
TObject *f = Address(func);
return (f+1 < L->stack.top && (f+1)->ttype == LUA_T_LINE) ?
(f+1)->value.i : -1;
}
lua_Object lua_getlocal (lua_Function func, int local_number, char **name)
{
/* check whether func is a Lua function */
if (lua_tag(func) != LUA_T_PROTO)
return LUA_NOOBJECT;
GlobalVar *luaA_nextvar (lua_State *L, TString *ts) {
GlobalVar *gv;
if (ts == NULL)
gv = L->rootglobal; /* first variable */
else {
TObject *f = Address(func);
TProtoFunc *fp = luaA_protovalue(f)->value.tf;
*name = luaF_getlocalname(fp, local_number, lua_currentline(func));
if (*name) {
/* if "*name", there must be a LUA_T_LINE */
/* therefore, f+2 points to function base */
return Ref((f+2)+(local_number-1));
}
else
return LUA_NOOBJECT;
/* check whether name is in global var list */
luaL_arg_check(L, ts->u.s.gv, 1, "variable name expected");
gv = ts->u.s.gv->next; /* get next */
}
while (gv && gv->value.ttype == TAG_NIL) /* skip globals with nil */
gv = gv->next;
if (gv) {
ttype(L->top) = TAG_STRING; tsvalue(L->top) = gv->name;
incr_top;
luaA_pushobject(L, &gv->value);
}
return gv;
}
int lua_setlocal (lua_Function func, int local_number)
{
/* check whether func is a Lua function */
if (lua_tag(func) != LUA_T_PROTO)
return 0;
const char *lua_nextvar (lua_State *L, const char *varname) {
TString *ts = (varname == NULL) ? NULL : luaS_new(L, varname);
GlobalVar *gv = luaA_nextvar(L, ts);
if (gv) {
top2LC(L, 2);
return gv->name->str;
}
else {
TObject *f = Address(func);
TProtoFunc *fp = luaA_protovalue(f)->value.tf;
char *name = luaF_getlocalname(fp, local_number, lua_currentline(func));
checkCparams(1);
--L->stack.top;
if (name) {
/* if "name", there must be a LUA_T_LINE */
/* therefore, f+2 points to function base */
*((f+2)+(local_number-1)) = *L->stack.top;
return 1;
}
else
return 0;
top2LC(L, 0);
return NULL;
}
}
void lua_funcinfo (lua_Object func, char **filename, int *linedefined)
{
if (!lua_isfunction(func))
lua_error("API - `funcinfo' called with a non-function value");
else {
TObject *f = luaA_protovalue(Address(func));
if (normalized_type(f) == LUA_T_PROTO) {
*filename = tfvalue(f)->fileName->str;
*linedefined = tfvalue(f)->lineDefined;
}
else {
*filename = "(C)";
*linedefined = -1;
int luaA_next (lua_State *L, const Hash *t, int i) {
int tsize = t->size;
for (; i<tsize; i++) {
Node *n = node(t, i);
if (ttype(val(n)) != TAG_NIL) {
luaA_pushobject(L, key(n));
luaA_pushobject(L, val(n));
return i+1; /* index to be used next time */
}
}
return 0; /* no more elements */
}
static int checkfunc (TObject *o)
{
return luaO_equalObj(o, L->stack.top);
int lua_next (lua_State *L, lua_Object t, int i) {
if (ttype(t) != TAG_TABLE)
lua_error(L, "Lua API error - object is not a table in `lua_next'");
i = luaA_next(L, avalue(t), i);
top2LC(L, (i==0) ? 0 : 2);
return i;
}
char *lua_getobjname (lua_Object o, char **name)
{ /* try to find a name for given function */
set_normalized(L->stack.top, Address(o)); /* to be accessed by "checkfunc */
if ((*name = luaT_travtagmethods(checkfunc)) != NULL)
return "tag-method";
else if ((*name = luaS_travsymbol(checkfunc)) != NULL)
return "global";
else return "";
}
/*
** =======================================================
** BLOCK mechanism
** =======================================================
*/
void lua_beginblock (void)
{
if (L->numCblocks >= MAX_C_BLOCKS)
lua_error("too many nested blocks");
L->Cblocks[L->numCblocks] = L->Cstack;
L->numCblocks++;
}
void lua_endblock (void)
{
--L->numCblocks;
L->Cstack = L->Cblocks[L->numCblocks];
luaD_adjusttop(L->Cstack.base);
}
int lua_ref (int lock)
{
int ref;
checkCparams(1);
ref = luaC_ref(L->stack.top-1, lock);
L->stack.top--;
return ref;
}
lua_Object lua_getref (int ref)
{
TObject *o = luaC_getref(ref);
return (o ? put_luaObject(o) : LUA_NOOBJECT);
}
/*
** =======================================================
** Derived functions
** =======================================================
*/
int (lua_call) (char *name) { return lua_call(name); }
void (lua_pushref) (int ref) { lua_pushref(ref); }
int (lua_refobject) (lua_Object o, int l) { return lua_refobject(o, l); }
void (lua_register) (char *n, lua_CFunction f) { lua_register(n, f); }
void (lua_pushuserdata) (void *u) { lua_pushuserdata(u); }
void (lua_pushcfunction) (lua_CFunction f) { lua_pushcfunction(f); }
int (lua_clonetag) (int t) { return lua_clonetag(t); }
#ifdef LUA_COMPAT2_5
/*
** API: set a function as a fallback
*/
static void do_unprotectedrun (lua_CFunction f, int nParams, int nResults)
{
StkId base = (L->stack.top-L->stack.stack)-nParams;
luaD_openstack(nParams);
L->stack.stack[base].ttype = LUA_T_CPROTO;
L->stack.stack[base].value.f = f;
luaD_call(base+1, nResults);
}
lua_Object lua_setfallback (char *name, lua_CFunction fallback)
{
lua_pushstring(name);
lua_pushcfunction(fallback);
do_unprotectedrun(luaT_setfallback, 2, 1);
return put_luaObjectonTop();
}
#endif

13
lapi.h
View File

@@ -1,5 +1,5 @@
/*
** $Id: lapi.h,v 1.1 1997/09/16 19:25:59 roberto Exp roberto $
** $Id: lapi.h,v 1.15 2000/03/10 18:37:44 roberto Exp roberto $
** Auxiliary functions from Lua API
** See Copyright Notice in lua.h
*/
@@ -8,13 +8,14 @@
#define lapi_h
#include "lua.h"
#include "lobject.h"
TObject *luaA_Address (lua_Object o);
void luaA_pushobject (TObject *o);
void luaA_packresults (void);
int luaA_passresults (void);
void luaA_checkCargs (lua_State *L, int nargs);
void luaA_pushobject (lua_State *L, const TObject *o);
GlobalVar *luaA_nextvar (lua_State *L, TString *g);
int luaA_next (lua_State *L, const Hash *t, int i);
lua_Object luaA_putluaObject (lua_State *L, const TObject *o);
lua_Object luaA_putObjectOnTop (lua_State *L);
#endif

162
lauxlib.c
View File

@@ -1,5 +1,5 @@
/*
** $Id: lauxlib.c,v 1.11 1998/06/18 16:57:03 roberto Exp roberto $
** $Id: lauxlib.c,v 1.26 2000/02/08 16:34:31 roberto Exp roberto $
** Auxiliary functions for building Lua libraries
** See Copyright Notice in lua.h
*/
@@ -9,17 +9,20 @@
#include <stdio.h>
#include <string.h>
/* Please Notice: This file uses only the official API of Lua
** Any function declared here could be written as an application
** function. With care, these functions can be used by other libraries.
/* This file uses only the official API of Lua.
** Any function declared here could be written as an application function.
** With care, these functions can be used by other libraries.
*/
#define LUA_REENTRANT
#include "lauxlib.h"
#include "lua.h"
#include "luadebug.h"
int luaL_findstring (char *name, char *list[]) {
int luaL_findstring (const char *name, const char *const list[]) {
int i;
for (i=0; list[i]; i++)
if (strcmp(list[i], name) == 0)
@@ -27,85 +30,122 @@ int luaL_findstring (char *name, char *list[]) {
return -1; /* name not found */
}
void luaL_argerror (int numarg, char *extramsg)
{
char *funcname;
lua_getobjname(lua_stackedfunction(0), &funcname);
if (funcname == NULL)
funcname = "???";
if (extramsg == NULL)
luaL_verror("bad argument #%d to function `%.50s'", numarg, funcname);
else
luaL_verror("bad argument #%d to function `%.50s' (%.100s)",
numarg, funcname, extramsg);
}
char *luaL_check_lstr (int numArg, long *len)
{
lua_Object o = lua_getparam(numArg);
luaL_arg_check(lua_isstring(o), numArg, "string expected");
if (len) *len = lua_strlen(o);
return lua_getstring(o);
}
char *luaL_opt_lstr (int numArg, char *def, long *len)
{
return (lua_getparam(numArg) == LUA_NOOBJECT) ? def :
luaL_check_lstr(numArg, len);
}
double luaL_check_number (int numArg)
{
lua_Object o = lua_getparam(numArg);
luaL_arg_check(lua_isnumber(o), numArg, "number expected");
return lua_getnumber(o);
void luaL_argerror (lua_State *L, int narg, const char *extramsg) {
lua_Debug ar;
lua_getstack(L, 0, &ar);
lua_getinfo(L, "nu", &ar);
narg -= ar.nups;
if (ar.name == NULL)
ar.name = "?";
luaL_verror(L, "bad argument #%d to `%.50s' (%.100s)",
narg, ar.name, extramsg);
}
double luaL_opt_number (int numArg, double def)
{
return (lua_getparam(numArg) == LUA_NOOBJECT) ? def :
luaL_check_number(numArg);
}
static void type_error (lua_State *L, int narg, const char *type_name,
lua_Object o) {
char buff[100];
const char *otype = (o == LUA_NOOBJECT) ? "no value" : lua_type(L, o);
sprintf(buff, "%.10s expected, got %.10s", type_name, otype);
luaL_argerror(L, narg, buff);
}
lua_Object luaL_tablearg (int arg)
{
lua_Object o = lua_getparam(arg);
luaL_arg_check(lua_istable(o), arg, "table expected");
static const char *checkstr (lua_State *L, lua_Object o, int narg, long *len) {
const char *s = lua_getstring(L, o);
if (!s) type_error(L, narg, "string", o);
if (len) *len = lua_strlen(L, o);
return s;
}
const char *luaL_check_lstr (lua_State *L, int narg, long *len) {
return checkstr(L, lua_getparam(L, narg), narg, len);
}
const char *luaL_opt_lstr (lua_State *L, int narg, const char *def, long *len) {
lua_Object o = lua_getparam(L, narg);
if (o == LUA_NOOBJECT) {
if (len) *len = def ? strlen(def) : 0;
return def;
}
else return checkstr(L, o, narg, len);
}
double luaL_check_number (lua_State *L, int narg) {
lua_Object o = lua_getparam(L, narg);
if (!lua_isnumber(L, o)) type_error(L, narg, "number", o);
return lua_getnumber(L, o);
}
double luaL_opt_number (lua_State *L, int narg, double def) {
lua_Object o = lua_getparam(L, narg);
if (o == LUA_NOOBJECT) return def;
else {
if (!lua_isnumber(L, o)) type_error(L, narg, "number", o);
return lua_getnumber(L, o);
}
}
lua_Object luaL_tablearg (lua_State *L, int narg) {
lua_Object o = lua_getparam(L, narg);
if (!lua_istable(L, o)) type_error(L, narg, "table", o);
return o;
}
lua_Object luaL_functionarg (int arg)
{
lua_Object o = lua_getparam(arg);
luaL_arg_check(lua_isfunction(o), arg, "function expected");
lua_Object luaL_functionarg (lua_State *L, int narg) {
lua_Object o = lua_getparam(L, narg);
if (!lua_isfunction(L, o)) type_error(L, narg, "function", o);
return o;
}
lua_Object luaL_nonnullarg (int numArg)
{
lua_Object o = lua_getparam(numArg);
luaL_arg_check(o != LUA_NOOBJECT, numArg, "value expected");
lua_Object luaL_nonnullarg (lua_State *L, int narg) {
lua_Object o = lua_getparam(L, narg);
luaL_arg_check(L, o != LUA_NOOBJECT, narg, "value expected");
return o;
}
void luaL_openlib (struct luaL_reg *l, int n)
{
void luaL_openlib (lua_State *L, const struct luaL_reg *l, int n) {
int i;
lua_open(); /* make sure lua is already open */
for (i=0; i<n; i++)
lua_register(l[i].name, l[i].func);
lua_register(L, l[i].name, l[i].func);
}
void luaL_verror (char *fmt, ...)
{
void luaL_verror (lua_State *L, const char *fmt, ...) {
char buff[500];
va_list argp;
va_start(argp, fmt);
vsprintf(buff, fmt, argp);
va_end(argp);
lua_error(buff);
lua_error(L, buff);
}
#define EXTRALEN sizeof("string \"...\"0")
void luaL_chunkid (char *out, const char *source, int len) {
if (*source == '(') {
strncpy(out, source+1, len-1); /* remove first char */
out[len-1] = '\0'; /* make sure `out' has an end */
out[strlen(out)-1] = '\0'; /* remove last char */
}
else {
len -= EXTRALEN;
if (*source == '@')
sprintf(out, "file `%.*s'", len, source+1);
else {
const char *b = strchr(source , '\n'); /* stop at first new line */
int lim = (b && (b-source)<len) ? b-source : len;
sprintf(out, "string \"%.*s\"", lim, source);
strcpy(out+lim+(EXTRALEN-sizeof("...\"0")), "...\"");
}
}
}
void luaL_filesource (char *out, const char *filename, int len) {
if (filename == NULL) filename = "(stdin)";
sprintf(out, "@%.*s", len-2, filename); /* -2 for '@' and '\0' */
}

108
lauxlib.h
View File

@@ -1,47 +1,105 @@
/*
** $Id: lauxlib.h,v 1.8 1998/06/18 16:57:03 roberto Exp roberto $
** $Id: lauxlib.h,v 1.16 1999/12/03 11:26:23 roberto Exp roberto $
** Auxiliary functions for building Lua libraries
** See Copyright Notice in lua.h
*/
#ifndef auxlib_h
#define auxlib_h
#ifndef lauxlib_h
#define lauxlib_h
#include "lua.h"
struct luaL_reg {
char *name;
const char *name;
lua_CFunction func;
};
void luaL_openlib (lua_State *L, const struct luaL_reg *l, int n);
void luaL_argerror (lua_State *L, int numarg, const char *extramsg);
const char *luaL_check_lstr (lua_State *L, int numArg, long *len);
const char *luaL_opt_lstr (lua_State *L, int numArg, const char *def, long *len);
double luaL_check_number (lua_State *L, int numArg);
double luaL_opt_number (lua_State *L, int numArg, double def);
lua_Object luaL_functionarg (lua_State *L, int arg);
lua_Object luaL_tablearg (lua_State *L, int arg);
lua_Object luaL_nonnullarg (lua_State *L, int numArg);
void luaL_verror (lua_State *L, const char *fmt, ...);
char *luaL_openspace (lua_State *L, int size);
void luaL_resetbuffer (lua_State *L);
void luaL_addchar (lua_State *L, int c);
int luaL_getsize (lua_State *L);
void luaL_addsize (lua_State *L, int n);
int luaL_newbuffer (lua_State *L, int size);
void luaL_oldbuffer (lua_State *L, int old);
char *luaL_buffer (lua_State *L);
int luaL_findstring (const char *name, const char *const list[]);
void luaL_chunkid (char *out, const char *source, int len);
void luaL_filesource (char *out, const char *filename, int len);
#ifdef LUA_REENTRANT
/*
** ===============================================================
** some useful macros
** ===============================================================
*/
#define luaL_arg_check(L, cond,numarg,extramsg) if (!(cond)) \
luaL_argerror(L, numarg,extramsg)
#define luaL_check_string(L,n) (luaL_check_lstr(L, (n), NULL))
#define luaL_opt_string(L,n,d) (luaL_opt_lstr(L, (n), (d), NULL))
#define luaL_check_int(L,n) ((int)luaL_check_number(L, n))
#define luaL_check_long(L,n) ((long)luaL_check_number(L, n))
#define luaL_opt_int(L,n,d) ((int)luaL_opt_number(L, n,d))
#define luaL_opt_long(L,n,d) ((long)luaL_opt_number(L, n,d))
#define luaL_openl(L,a) luaL_openlib(L, a, (sizeof(a)/sizeof(a[0])))
#else
/*
** ===============================================================
** Macros for single-state use
** ===============================================================
*/
#define luaL_arg_check(cond,numarg,extramsg) if (!(cond)) \
luaL_argerror(numarg,extramsg)
#define luaL_check_string(n) (luaL_check_lstr((n), NULL))
#define luaL_opt_string(n, d) (luaL_opt_lstr((n), (d), NULL))
#define luaL_check_int(n) ((int)luaL_check_number(n))
#define luaL_check_long(n) ((long)luaL_check_number(n))
#define luaL_opt_int(n,d) ((int)luaL_opt_number(n,d))
#define luaL_opt_long(n,d) ((long)luaL_opt_number(n,d))
#define luaL_openl(a) luaL_openlib(a, (sizeof(a)/sizeof(a[0])))
void luaL_openlib (struct luaL_reg *l, int n);
void luaL_argerror (int numarg, char *extramsg);
#define luaL_check_string(n) (luaL_check_lstr((n), NULL))
char *luaL_check_lstr (int numArg, long *len);
#define luaL_opt_string(n, d) (luaL_opt_lstr((n), (d), NULL))
char *luaL_opt_lstr (int numArg, char *def, long *len);
double luaL_check_number (int numArg);
double luaL_opt_number (int numArg, double def);
lua_Object luaL_functionarg (int arg);
lua_Object luaL_tablearg (int arg);
lua_Object luaL_nonnullarg (int numArg);
void luaL_verror (char *fmt, ...);
char *luaL_openspace (int size);
void luaL_resetbuffer (void);
void luaL_addchar (int c);
int luaL_getsize (void);
void luaL_addsize (int n);
int luaL_newbuffer (int size);
void luaL_oldbuffer (int old);
char *luaL_buffer (void);
int luaL_findstring (char *name, char *list[]);
#define luaL_openlib(l,n) (luaL_openlib)(lua_state,l,n)
#define luaL_argerror(numarg,extramsg) \
(luaL_argerror)(lua_state,numarg,extramsg)
#define luaL_check_lstr(numArg,len) (luaL_check_lstr)(lua_state,numArg,len)
#define luaL_opt_lstr(numArg,def,len) \
(luaL_opt_lstr)(lua_state,numArg,def,len)
#define luaL_check_number(numArg) (luaL_check_number)(lua_state,numArg)
#define luaL_opt_number(numArg,def) (luaL_opt_number)(lua_state,numArg,def)
#define luaL_functionarg(arg) (luaL_functionarg)(lua_state,arg)
#define luaL_tablearg(arg) (luaL_tablearg)(lua_state,arg)
#define luaL_nonnullarg(numArg) (luaL_nonnullarg)(lua_state,numArg)
#define luaL_openspace(size) (luaL_openspace)(lua_state,size)
#define luaL_resetbuffer() (luaL_resetbuffer)(lua_state)
#define luaL_addchar(c) (luaL_addchar)(lua_state,c)
#define luaL_getsize() (luaL_getsize)(lua_state)
#define luaL_addsize(n) (luaL_addsize)(lua_state,n)
#define luaL_newbuffer(size) (luaL_newbuffer)(lua_state,size)
#define luaL_oldbuffer(old) (luaL_oldbuffer)(lua_state,old)
#define luaL_buffer() (luaL_buffer)(lua_state)
#endif
#endif

View File

@@ -1,5 +1,5 @@
/*
** $Id: lbuffer.c,v 1.3 1998/06/02 20:37:04 roberto Exp roberto $
** $Id: lbuffer.c,v 1.11 1999/11/22 13:12:07 roberto Exp roberto $
** Auxiliary functions for building Lua libraries
** See Copyright Notice in lua.h
*/
@@ -7,6 +7,8 @@
#include <stdio.h>
#define LUA_REENTRANT
#include "lauxlib.h"
#include "lmem.h"
#include "lstate.h"
@@ -16,70 +18,62 @@
** Auxiliary buffer
-------------------------------------------------------*/
#define BUFF_STEP 32
#define openspace(size) if (L->Mbuffnext+(size) > L->Mbuffsize) Openspace(size)
/*
** amount of extra space (pre)allocated when buffer is reallocated
*/
#define EXTRABUFF 32
static void Openspace (int size)
{
lua_State *l = L; /* to optimize */
int base = l->Mbuffbase-l->Mbuffer;
l->Mbuffsize *= 2;
if (l->Mbuffnext+size > l->Mbuffsize) /* still not big enough? */
l->Mbuffsize = l->Mbuffnext+size;
l->Mbuffer = luaM_realloc(l->Mbuffer, l->Mbuffsize);
l->Mbuffbase = l->Mbuffer+base;
#define openspace(L, size) if (L->Mbuffnext+(size) > L->Mbuffsize) \
Openspace(L, size)
static void Openspace (lua_State *L, int size) {
L->Mbuffsize = (L->Mbuffnext+size+EXTRABUFF)*2;
luaM_reallocvector(L, L->Mbuffer, L->Mbuffsize, char);
}
char *luaL_openspace (int size)
{
openspace(size);
char *luaL_openspace (lua_State *L, int size) {
openspace(L, size);
return L->Mbuffer+L->Mbuffnext;
}
void luaL_addchar (int c)
{
openspace(BUFF_STEP);
L->Mbuffer[L->Mbuffnext++] = c;
void luaL_addchar (lua_State *L, int c) {
openspace(L, 1);
L->Mbuffer[L->Mbuffnext++] = (char)c;
}
void luaL_resetbuffer (void)
{
L->Mbuffnext = L->Mbuffbase-L->Mbuffer;
void luaL_resetbuffer (lua_State *L) {
L->Mbuffnext = L->Mbuffbase;
}
void luaL_addsize (int n)
{
void luaL_addsize (lua_State *L, int n) {
L->Mbuffnext += n;
}
int luaL_getsize (void)
{
return L->Mbuffnext-(L->Mbuffbase-L->Mbuffer);
int luaL_getsize (lua_State *L) {
return L->Mbuffnext-L->Mbuffbase;
}
int luaL_newbuffer (int size)
{
int old = L->Mbuffbase-L->Mbuffer;
openspace(size);
L->Mbuffbase = L->Mbuffer+L->Mbuffnext;
int luaL_newbuffer (lua_State *L, int size) {
int old = L->Mbuffbase;
openspace(L, size);
L->Mbuffbase = L->Mbuffnext;
return old;
}
void luaL_oldbuffer (int old)
{
L->Mbuffnext = L->Mbuffbase-L->Mbuffer;
L->Mbuffbase = L->Mbuffer+old;
void luaL_oldbuffer (lua_State *L, int old) {
L->Mbuffnext = L->Mbuffbase;
L->Mbuffbase = old;
}
char *luaL_buffer (void)
{
return L->Mbuffbase;
char *luaL_buffer (lua_State *L) {
return L->Mbuffer+L->Mbuffbase;
}

1006
lbuiltin.c

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,5 @@
/*
** $Id: $
** $Id: lbuiltin.h,v 1.6 2000/03/03 14:58:26 roberto Exp roberto $
** Built-in functions
** See Copyright Notice in lua.h
*/
@@ -7,8 +7,43 @@
#ifndef lbuiltin_h
#define lbuiltin_h
#include "lua.h"
void luaB_predefine (void);
void luaB__ALERT (lua_State *L);
void luaB__ERRORMESSAGE (lua_State *L);
void luaB_assert (lua_State *L);
void luaB_call (lua_State *L);
void luaB_collectgarbage (lua_State *L);
void luaB_copytagmethods (lua_State *L);
void luaB_dofile (lua_State *L);
void luaB_dostring (lua_State *L);
void luaB_error (lua_State *L);
void luaB_foreach (lua_State *L);
void luaB_foreachi (lua_State *L);
void luaB_foreachvar (lua_State *L);
void luaB_getglobal (lua_State *L);
void luaB_getn (lua_State *L);
void luaB_gettagmethod (lua_State *L);
void luaB_newtag (lua_State *L);
void luaB_next (lua_State *L);
void luaB_nextvar (lua_State *L);
void luaB_print (lua_State *L);
void luaB_rawgetglobal (lua_State *L);
void luaB_rawgettable (lua_State *L);
void luaB_rawsetglobal (lua_State *L);
void luaB_rawsettable (lua_State *L);
void luaB_setglobal (lua_State *L);
void luaB_settag (lua_State *L);
void luaB_settagmethod (lua_State *L);
void luaB_sort (lua_State *L);
void luaB_tag (lua_State *L);
void luaB_tinsert (lua_State *L);
void luaB_tonumber (lua_State *L);
void luaB_tostring (lua_State *L);
void luaB_tremove (lua_State *L);
void luaB_type (lua_State *L);
void luaB_predefine (lua_State *L);
#endif

643
lcode.c Normal file
View File

@@ -0,0 +1,643 @@
/*
** $Id: lcode.c,v 1.27 2000/04/17 14:05:34 roberto Exp roberto $
** Code generator for Lua
** See Copyright Notice in lua.h
*/
#include "stdlib.h"
#define LUA_REENTRANT
#include "lcode.h"
#include "ldo.h"
#include "llex.h"
#include "lmem.h"
#include "lobject.h"
#include "lopcodes.h"
#include "lparser.h"
#include "lstring.h"
void luaK_error (LexState *ls, const char *msg) {
luaX_error(ls, msg, ls->token);
}
/*
** Returns the the previous instruction, for optimizations.
** If there is a jump target between this and the current instruction,
** returns a dummy instruction to avoid wrong optimizations.
*/
static Instruction previous_instruction (FuncState *fs) {
if (fs->pc > fs->lasttarget) /* no jumps to current position? */
return fs->f->code[fs->pc-1]; /* returns previous instruction */
else
return CREATE_0(OP_END); /* no optimizations after an `END' */
}
int luaK_jump (FuncState *fs) {
int j = luaK_code0(fs, OP_JMP);
if (j == fs->lasttarget) { /* possible jumps to this jump? */
luaK_concat(fs, &j, fs->jlt); /* keep them on hold */
fs->jlt = NO_JUMP;
}
return j;
}
static void luaK_fixjump (FuncState *fs, int pc, int dest) {
Instruction *jmp = &fs->f->code[pc];
if (dest == NO_JUMP)
SETARG_S(*jmp, NO_JUMP); /* point to itself to represent end of list */
else { /* jump is relative to position following jump instruction */
int offset = dest-(pc+1);
if (abs(offset) > MAXARG_S)
luaK_error(fs->ls, "control structure too long");
SETARG_S(*jmp, offset);
}
}
static int luaK_getjump (FuncState *fs, int pc) {
int offset = GETARG_S(fs->f->code[pc]);
if (offset == NO_JUMP) /* point to itself represents end of list */
return NO_JUMP; /* end of list */
else
return (pc+1)+offset; /* turn offset into absolute position */
}
/*
** discharge list of jumps to last target.
** returns current `pc' and marks it as a jump target (to avoid wrong
** optimizations with consecutive instructions not in the same basic block).
*/
int luaK_getlabel (FuncState *fs) {
if (fs->pc != fs->lasttarget) {
int lasttarget = fs->lasttarget;
fs->lasttarget = fs->pc;
luaK_patchlist(fs, fs->jlt, lasttarget); /* discharge old list `jlt' */
fs->jlt = NO_JUMP; /* nobody jumps to this new label (till now) */
}
return fs->pc;
}
void luaK_deltastack (FuncState *fs, int delta) {
fs->stacklevel += delta;
if (delta > 0 && fs->stacklevel > fs->f->maxstacksize) {
if (fs->stacklevel > MAXSTACK)
luaK_error(fs->ls, "function or expression too complex");
fs->f->maxstacksize = fs->stacklevel;
}
}
void luaK_kstr (LexState *ls, int c) {
luaK_code1(ls->fs, OP_PUSHSTRING, c);
}
static int real_constant (FuncState *fs, Number r) {
/* check whether `r' has appeared within the last LOOKBACKNUMS entries */
Proto *f = fs->f;
int c = f->nknum;
int lim = c < LOOKBACKNUMS ? 0 : c-LOOKBACKNUMS;
while (--c >= lim)
if (f->knum[c] == r) return c;
/* not found; create a new entry */
luaM_growvector(fs->L, f->knum, f->nknum, 1, Number, constantEM, MAXARG_U);
c = f->nknum++;
f->knum[c] = r;
return c;
}
void luaK_number (FuncState *fs, Number f) {
if (f <= (Number)MAXARG_S && (int)f == f)
luaK_code1(fs, OP_PUSHINT, (int)f); /* f has a short integer value */
else
luaK_code1(fs, OP_PUSHNUM, real_constant(fs, f));
}
void luaK_adjuststack (FuncState *fs, int n) {
if (n > 0)
luaK_code1(fs, OP_POP, n);
else if (n < 0)
luaK_code1(fs, OP_PUSHNIL, -n);
}
int luaK_lastisopen (FuncState *fs) {
/* check whether last instruction is an open function call */
Instruction i = previous_instruction(fs);
if (GET_OPCODE(i) == OP_CALL && GETARG_B(i) == MULT_RET)
return 1;
else return 0;
}
void luaK_setcallreturns (FuncState *fs, int nresults) {
if (luaK_lastisopen(fs)) { /* expression is an open function call? */
SETARG_B(fs->f->code[fs->pc-1], nresults); /* set number of results */
luaK_deltastack(fs, nresults); /* push results */
}
}
static void assertglobal (FuncState *fs, int index) {
luaS_assertglobal(fs->L, fs->f->kstr[index]);
}
static int discharge (FuncState *fs, expdesc *var) {
switch (var->k) {
case VLOCAL:
luaK_code1(fs, OP_GETLOCAL, var->u.index);
break;
case VGLOBAL:
luaK_code1(fs, OP_GETGLOBAL, var->u.index);
assertglobal(fs, var->u.index); /* make sure that there is a global */
break;
case VINDEXED:
luaK_code0(fs, OP_GETTABLE);
break;
case VEXP:
return 0; /* nothing to do */
}
var->k = VEXP;
var->u.l.t = var->u.l.f = NO_JUMP;
return 1;
}
static void discharge1 (FuncState *fs, expdesc *var) {
discharge(fs, var);
/* if it has jumps it is already discharged */
if (var->u.l.t == NO_JUMP && var->u.l.f == NO_JUMP)
luaK_setcallreturns(fs, 1); /* call must return 1 value */
}
void luaK_storevar (LexState *ls, const expdesc *var) {
FuncState *fs = ls->fs;
switch (var->k) {
case VLOCAL:
luaK_code1(fs, OP_SETLOCAL, var->u.index);
break;
case VGLOBAL:
luaK_code1(fs, OP_SETGLOBAL, var->u.index);
assertglobal(fs, var->u.index); /* make sure that there is a global */
break;
case VINDEXED: /* table is at top-3; pop 3 elements after operation */
luaK_code2(fs, OP_SETTABLE, 3, 3);
break;
default:
LUA_INTERNALERROR(ls->L, "invalid var kind to store");
}
}
static OpCode invertjump (OpCode op) {
switch (op) {
case OP_JMPNE: return OP_JMPEQ;
case OP_JMPEQ: return OP_JMPNE;
case OP_JMPLT: return OP_JMPGE;
case OP_JMPLE: return OP_JMPGT;
case OP_JMPGT: return OP_JMPLE;
case OP_JMPGE: return OP_JMPLT;
case OP_JMPT: case OP_JMPONT: return OP_JMPF;
case OP_JMPF: case OP_JMPONF: return OP_JMPT;
default:
LUA_INTERNALERROR(NULL, "invalid jump instruction");
return OP_END; /* to avoid warnings */
}
}
static void luaK_patchlistaux (FuncState *fs, int list, int target,
OpCode special, int special_target) {
Instruction *code = fs->f->code;
while (list != NO_JUMP) {
int next = luaK_getjump(fs, list);
Instruction *i = &code[list];
OpCode op = GET_OPCODE(*i);
if (op == special) /* this `op' already has a value */
luaK_fixjump(fs, list, special_target);
else {
luaK_fixjump(fs, list, target); /* do the patch */
if (op == OP_JMPONT) /* remove eventual values */
SET_OPCODE(*i, OP_JMPT);
else if (op == OP_JMPONF)
SET_OPCODE(*i, OP_JMPF);
}
list = next;
}
}
void luaK_patchlist (FuncState *fs, int list, int target) {
if (target == fs->lasttarget) /* same target that list `jlt'? */
luaK_concat(fs, &fs->jlt, list); /* delay fixing */
else
luaK_patchlistaux(fs, list, target, OP_END, 0);
}
static int need_value (FuncState *fs, int list, OpCode hasvalue) {
/* check whether list has a jump without a value */
for (; list != NO_JUMP; list = luaK_getjump(fs, list))
if (GET_OPCODE(fs->f->code[list]) != hasvalue) return 1;
return 0; /* not found */
}
void luaK_concat (FuncState *fs, int *l1, int l2) {
if (*l1 == NO_JUMP)
*l1 = l2;
else {
int list = *l1;
for (;;) { /* traverse `l1' */
int next = luaK_getjump(fs, list);
if (next == NO_JUMP) { /* end of list? */
luaK_fixjump(fs, list, l2);
return;
}
list = next;
}
}
}
static void luaK_testgo (FuncState *fs, expdesc *v, int invert, OpCode jump) {
Instruction *previous;
int *golist = &v->u.l.f;
int *exitlist = &v->u.l.t;
if (invert) { /* interchange `golist' and `exitlist' */
int *temp = golist; golist = exitlist; exitlist = temp;
}
discharge1(fs, v);
previous = &fs->f->code[fs->pc-1];
LUA_ASSERT(L, GET_OPCODE(*previous) != OP_SETLINE, "bad place to set line");
if (ISJUMP(GET_OPCODE(*previous))) {
if (invert)
SET_OPCODE(*previous, invertjump(GET_OPCODE(*previous)));
}
else
luaK_code0(fs, jump);
luaK_concat(fs, exitlist, fs->pc-1); /* insert last jump in `exitlist' */
luaK_patchlist(fs, *golist, luaK_getlabel(fs));
*golist = NO_JUMP;
}
void luaK_goiftrue (FuncState *fs, expdesc *v, int keepvalue) {
luaK_testgo(fs, v, 1, keepvalue ? OP_JMPONF : OP_JMPF);
}
void luaK_goiffalse (FuncState *fs, expdesc *v, int keepvalue) {
luaK_testgo(fs, v, 0, keepvalue ? OP_JMPONT : OP_JMPT);
}
static int code_label (FuncState *fs, OpCode op, int arg) {
int j = luaK_getlabel(fs);
luaK_code1(fs, op, arg);
return j;
}
void luaK_tostack (LexState *ls, expdesc *v, int onlyone) {
FuncState *fs = ls->fs;
if (!discharge(fs, v)) { /* `v' is an expression? */
OpCode previous = GET_OPCODE(fs->f->code[fs->pc-1]);
LUA_ASSERT(L, previous != OP_SETLINE, "bad place to set line");
if (!ISJUMP(previous) && v->u.l.f == NO_JUMP && v->u.l.t == NO_JUMP) {
/* expression has no jumps */
if (onlyone)
luaK_setcallreturns(fs, 1); /* call must return 1 value */
}
else { /* expression has jumps */
int final; /* position after whole expression */
int j = NO_JUMP; /* eventual jump over values */
int p_nil = NO_JUMP; /* position of an eventual PUSHNIL */
int p_1 = NO_JUMP; /* position of an eventual PUSHINT */
if (ISJUMP(previous) || need_value(fs, v->u.l.f, OP_JMPONF) ||
need_value(fs, v->u.l.t, OP_JMPONT)) {
/* expression needs values */
if (ISJUMP(previous))
luaK_concat(fs, &v->u.l.t, fs->pc-1); /* put `previous' in t. list */
else {
j = code_label(fs, OP_JMP, 0); /* to jump over both pushes */
luaK_deltastack(fs, -1); /* next PUSHes may be skipped */
}
p_nil = code_label(fs, OP_PUSHNILJMP, 0);
p_1 = code_label(fs, OP_PUSHINT, 1);
luaK_patchlist(fs, j, luaK_getlabel(fs));
}
final = luaK_getlabel(fs);
luaK_patchlistaux(fs, v->u.l.f, p_nil, OP_JMPONF, final);
luaK_patchlistaux(fs, v->u.l.t, p_1, OP_JMPONT, final);
v->u.l.f = v->u.l.t = NO_JUMP;
}
}
}
void luaK_prefix (LexState *ls, int op, expdesc *v) {
FuncState *fs = ls->fs;
if (op == '-') {
luaK_tostack(ls, v, 1);
luaK_code0(fs, OP_MINUS);
}
else { /* op == NOT */
Instruction *previous;
discharge1(fs, v);
previous = &fs->f->code[fs->pc-1];
if (ISJUMP(GET_OPCODE(*previous)))
SET_OPCODE(*previous, invertjump(GET_OPCODE(*previous)));
else
luaK_code0(fs, OP_NOT);
/* interchange true and false lists */
{ int temp = v->u.l.f; v->u.l.f = v->u.l.t; v->u.l.t = temp; }
}
}
void luaK_infix (LexState *ls, int op, expdesc *v) {
FuncState *fs = ls->fs;
if (op == TK_AND)
luaK_goiftrue(fs, v, 1);
else if (op == TK_OR)
luaK_goiffalse(fs, v, 1);
else
luaK_tostack(ls, v, 1); /* all other binary operators need a value */
}
void luaK_posfix (LexState *ls, int op, expdesc *v1, expdesc *v2) {
FuncState *fs = ls->fs;
if (op == TK_AND) {
LUA_ASSERT(ls->L, v1->u.l.t == NO_JUMP, "list must be closed");
discharge1(fs, v2);
v1->u.l.t = v2->u.l.t;
luaK_concat(fs, &v1->u.l.f, v2->u.l.f);
}
else if (op == TK_OR) {
LUA_ASSERT(ls->L, v1->u.l.f == NO_JUMP, "list must be closed");
discharge1(fs, v2);
v1->u.l.f = v2->u.l.f;
luaK_concat(fs, &v1->u.l.t, v2->u.l.t);
}
else {
luaK_tostack(ls, v2, 1); /* `v2' must be a value */
switch (op) {
case '+': luaK_code0(fs, OP_ADD); break;
case '-': luaK_code0(fs, OP_SUB); break;
case '*': luaK_code0(fs, OP_MULT); break;
case '/': luaK_code0(fs, OP_DIV); break;
case '^': luaK_code0(fs, OP_POW); break;
case TK_CONCAT: luaK_code1(fs, OP_CONCAT, 2); break;
case TK_EQ: luaK_code0(fs, OP_JMPEQ); break;
case TK_NE: luaK_code0(fs, OP_JMPNE); break;
case '>': luaK_code0(fs, OP_JMPGT); break;
case '<': luaK_code0(fs, OP_JMPLT); break;
case TK_GE: luaK_code0(fs, OP_JMPGE); break;
case TK_LE: luaK_code0(fs, OP_JMPLE); break;
}
}
}
int luaK_code0 (FuncState *fs, OpCode o) {
return luaK_code2(fs, o, 0, 0);
}
int luaK_code1 (FuncState *fs, OpCode o, int arg1) {
return luaK_code2(fs, o, arg1, 0);
}
int luaK_code2 (FuncState *fs, OpCode o, int arg1, int arg2) {
Instruction i = previous_instruction(fs);
int delta = 0;
enum {iO, iU, iS, iAB, iP} mode; /* instruction format (or iP to optimize) */
mode = iP;
switch (o) {
case OP_CLOSURE:
delta = -arg2+1;
mode = iAB;
break;
case OP_SETLINE:
mode = iU;
break;
case OP_CALL:
mode = iAB;
break;
case OP_PUSHINT:
delta = 1;
mode = iS;
break;
case OP_SETTABLE:
delta = -arg2;
mode = iAB;
break;
case OP_SETLIST:
delta = -(arg2+1);
mode = iAB;
break;
case OP_SETMAP:
delta = -2*(arg1+1);
mode = iU;
break;
case OP_FORLOOP:
delta = -3;
arg1 = NO_JUMP;
mode = iS;
break;
case OP_SETLOCAL:
case OP_SETGLOBAL:
delta = -1;
mode = iU;
break;
case OP_FORPREP:
case OP_JMP:
arg1 = NO_JUMP;
mode = iS;
break;
case OP_END:
case OP_PUSHNILJMP:
case OP_NOT:
mode = iO;
break;
case OP_PUSHSTRING:
case OP_PUSHNUM:
case OP_PUSHNEGNUM:
case OP_PUSHUPVALUE:
case OP_GETLOCAL:
case OP_GETGLOBAL:
case OP_PUSHSELF:
case OP_CREATETABLE:
delta = 1;
mode = iU;
break;
case OP_JMPLT:
case OP_JMPLE:
case OP_JMPGT:
case OP_JMPGE:
delta = -2;
arg1 = NO_JUMP;
mode = iS;
break;
case OP_MULT:
case OP_DIV:
case OP_POW:
delta = -1;
mode = iO;
break;
case OP_RETURN:
if (GET_OPCODE(i) == OP_CALL && GETARG_B(i) == MULT_RET) {
SET_OPCODE(i, OP_TAILCALL);
SETARG_B(i, arg1);
}
else mode = iU;
break;
case OP_PUSHNIL:
delta = arg1;
switch(GET_OPCODE(i)) {
case OP_PUSHNIL: SETARG_U(i, GETARG_U(i)+arg1); break;
default: mode = iU; break;
}
break;
case OP_POP:
delta = -arg1;
switch(GET_OPCODE(i)) {
case OP_SETTABLE: SETARG_B(i, GETARG_B(i)+arg1); break;
default: mode = iU; break;
}
break;
case OP_GETTABLE:
delta = -1;
switch(GET_OPCODE(i)) {
case OP_PUSHSTRING: SET_OPCODE(i, OP_GETDOTTED); break; /* `t.x' */
case OP_GETLOCAL: SET_OPCODE(i, OP_GETINDEXED); break; /* `t[i]' */
default: mode = iO; break;
}
break;
case OP_ADD:
delta = -1;
switch(GET_OPCODE(i)) {
case OP_PUSHINT: SET_OPCODE(i, OP_ADDI); break; /* `a+k' */
default: mode = iO; break;
}
break;
case OP_SUB:
delta = -1;
switch(GET_OPCODE(i)) {
case OP_PUSHINT: i = CREATE_S(OP_ADDI, -GETARG_S(i)); break; /* `a-k' */
default: mode = iO; break;
}
break;
case OP_CONCAT:
delta = -arg1+1;
switch(GET_OPCODE(i)) {
case OP_CONCAT: SETARG_U(i, GETARG_U(i)+1); break; /* `a..b..c' */
default: mode = iU; break;
}
break;
case OP_MINUS:
switch(GET_OPCODE(i)) {
case OP_PUSHINT: SETARG_S(i, -GETARG_S(i)); break; /* `-k' */
case OP_PUSHNUM: SET_OPCODE(i, OP_PUSHNEGNUM); break; /* `-k' */
default: mode = iO; break;
}
break;
case OP_JMPNE:
delta = -2;
if (i == CREATE_U(OP_PUSHNIL, 1)) /* `a~=nil' */
i = CREATE_S(OP_JMPT, NO_JUMP);
else {
arg1 = NO_JUMP;
mode = iS;
}
break;
case OP_JMPEQ:
delta = -2;
if (i == CREATE_U(OP_PUSHNIL, 1)) { /* `a==nil' */
i = CREATE_0(OP_NOT);
delta = -1; /* just undo effect of previous PUSHNIL */
}
else {
arg1 = NO_JUMP;
mode = iS;
}
break;
case OP_JMPT:
case OP_JMPF:
case OP_JMPONT:
case OP_JMPONF:
delta = -1;
arg1 = NO_JUMP;
switch (GET_OPCODE(i)) {
case OP_NOT: i = CREATE_S(invertjump(o), NO_JUMP); break;
default: mode = iS; break;
}
break;
case OP_GETDOTTED:
case OP_GETINDEXED:
case OP_TAILCALL:
case OP_ADDI:
LUA_INTERNALERROR(L, "instruction used only for optimizations");
return 0; /* to avoid warnings */
}
luaK_deltastack(fs, delta);
switch (mode) { /* handle instruction formats */
case iO: i = CREATE_0(o); break;
case iU: i = CREATE_U(o, arg1); break;
case iS: i = CREATE_S(o, arg1); break;
case iAB: i = CREATE_AB(o, arg1, arg2); break;
case iP: { /* optimize: put instruction in place of last one */
fs->f->code[fs->pc-1] = i; /* change previous instruction */
return fs->pc-1;
}
}
/* actually create the new instruction */
luaM_growvector(fs->L, fs->f->code, fs->pc, 1, Instruction, codeEM, MAX_INT);
fs->f->code[fs->pc] = i;
return fs->pc++;
}

46
lcode.h Normal file
View File

@@ -0,0 +1,46 @@
/*
** $Id: lcode.h,v 1.11 2000/04/07 19:35:20 roberto Exp roberto $
** Code generator for Lua
** See Copyright Notice in lua.h
*/
#ifndef lcode_h
#define lcode_h
#include "llex.h"
#include "lobject.h"
#include "lopcodes.h"
#include "lparser.h"
/*
** Marks the end of a patch list. It is an invalid value both as an absolute
** address, and as a list link (would link an element to itself).
*/
#define NO_JUMP (-1)
void luaK_error (LexState *ls, const char *msg);
int luaK_code0 (FuncState *fs, OpCode o);
int luaK_code1 (FuncState *fs, OpCode o, int arg1);
int luaK_code2 (FuncState *fs, OpCode o, int arg1, int arg2);
int luaK_jump (FuncState *fs);
void luaK_patchlist (FuncState *fs, int list, int target);
void luaK_concat (FuncState *fs, int *l1, int l2);
void luaK_goiftrue (FuncState *fs, expdesc *v, int keepvalue);
void luaK_goiffalse (FuncState *fs, expdesc *v, int keepvalue);
int luaK_getlabel (FuncState *fs);
void luaK_deltastack (FuncState *fs, int delta);
void luaK_kstr (LexState *ls, int c);
void luaK_number (FuncState *fs, Number f);
void luaK_adjuststack (FuncState *fs, int n);
int luaK_lastisopen (FuncState *fs);
void luaK_setcallreturns (FuncState *fs, int nresults);
void luaK_tostack (LexState *ls, expdesc *v, int onlyone);
void luaK_storevar (LexState *ls, const expdesc *var);
void luaK_prefix (LexState *ls, int op, expdesc *v);
void luaK_infix (LexState *ls, int op, expdesc *v);
void luaK_posfix (LexState *ls, int op, expdesc *v1, expdesc *v2);
#endif

176
ldblib.c Normal file
View File

@@ -0,0 +1,176 @@
/*
** $Id: ldblib.c,v 1.12 2000/03/30 17:19:48 roberto Exp roberto $
** Interface from Lua to its debug API
** See Copyright Notice in lua.h
*/
#include <stdlib.h>
#include <string.h>
#define LUA_REENTRANT
#include "lauxlib.h"
#include "lua.h"
#include "luadebug.h"
#include "lualib.h"
static void settabss (lua_State *L, lua_Object t, const char *i, const char *v) {
lua_pushobject(L, t);
lua_pushstring(L, i);
lua_pushstring(L, v);
lua_settable(L);
}
static void settabsi (lua_State *L, lua_Object t, const char *i, int v) {
lua_pushobject(L, t);
lua_pushstring(L, i);
lua_pushnumber(L, v);
lua_settable(L);
}
static void settabso (lua_State *L, lua_Object t, const char *i, lua_Object v) {
lua_pushobject(L, t);
lua_pushstring(L, i);
lua_pushobject(L, v);
lua_settable(L);
}
static void getstack (lua_State *L) {
lua_Debug ar;
if (!lua_getstack(L, luaL_check_int(L, 1), &ar)) /* level out of range? */
return;
else {
const char *options = luaL_check_string(L, 2);
lua_Object res = lua_createtable(L);
if (!lua_getinfo(L, options, &ar))
luaL_argerror(L, 2, "invalid option");
for (; *options; options++) {
switch (*options) {
case 'S':
settabss(L, res, "source", ar.source);
settabsi(L, res, "linedefined", ar.linedefined);
settabss(L, res, "what", ar.what);
break;
case 'l':
settabsi(L, res, "currentline", ar.currentline);
break;
case 'u':
settabsi(L, res, "nups", ar.nups);
break;
case 'n':
settabss(L, res, "name", ar.name);
settabss(L, res, "namewhat", ar.namewhat);
break;
case 'f':
settabso(L, res, "func", ar.func);
break;
}
}
lua_pushobject(L, res);
}
}
static void getlocal (lua_State *L) {
lua_Debug ar;
lua_Localvar lvar;
if (!lua_getstack(L, luaL_check_int(L, 1), &ar)) /* level out of range? */
luaL_argerror(L, 1, "level out of range");
lvar.index = luaL_check_int(L, 2);
if (lua_getlocal(L, &ar, &lvar)) {
lua_pushstring(L, lvar.name);
lua_pushobject(L, lvar.value);
}
else lua_pushnil(L);
}
static void setlocal (lua_State *L) {
lua_Debug ar;
lua_Localvar lvar;
if (!lua_getstack(L, luaL_check_int(L, 1), &ar)) /* level out of range? */
luaL_argerror(L, 1, "level out of range");
lvar.index = luaL_check_int(L, 2);
lvar.value = luaL_nonnullarg(L, 3);
if (lua_setlocal(L, &ar, &lvar))
lua_pushstring(L, lvar.name);
else lua_pushnil(L);
}
/*
** because of these variables, this module is not reentrant, and should
** not be used in multiple states
*/
static int linehook = LUA_NOREF; /* Lua reference to line hook function */
static int callhook = LUA_NOREF; /* Lua reference to call hook function */
static void linef (lua_State *L, lua_Debug *ar) {
if (linehook != LUA_NOREF) {
lua_pushnumber(L, ar->currentline);
lua_callfunction(L, lua_getref(L, linehook));
}
}
static void callf (lua_State *L, lua_Debug *ar) {
if (callhook != LUA_NOREF) {
lua_pushstring(L, ar->event);
lua_callfunction(L, lua_getref(L, callhook));
}
}
static void setcallhook (lua_State *L) {
lua_Object f = lua_getparam(L, 1);
lua_unref(L, callhook);
if (f == LUA_NOOBJECT) {
callhook = LUA_NOREF;
lua_setcallhook(L, NULL);
}
else {
lua_pushobject(L, f);
callhook = lua_ref(L, 1);
lua_setcallhook(L, callf);
}
}
static void setlinehook (lua_State *L) {
lua_Object f = lua_getparam(L, 1);
lua_unref(L, linehook);
if (f == LUA_NOOBJECT) {
linehook = LUA_NOREF;
lua_setlinehook(L, NULL);
}
else {
lua_pushobject(L, f);
linehook = lua_ref(L, 1);
lua_setlinehook(L, linef);
}
}
static const struct luaL_reg dblib[] = {
{"getlocal", getlocal},
{"getstack", getstack},
{"setcallhook", setcallhook},
{"setlinehook", setlinehook},
{"setlocal", setlocal}
};
void lua_dblibopen (lua_State *L) {
luaL_openl(L, dblib);
}

221
ldebug.c Normal file
View File

@@ -0,0 +1,221 @@
/*
** $Id: ldebug.c,v 1.15 2000/03/30 17:19:48 roberto Exp roberto $
** Debug Interface
** See Copyright Notice in lua.h
*/
#include <stdlib.h>
#define LUA_REENTRANT
#include "lapi.h"
#include "lauxlib.h"
#include "ldebug.h"
#include "ldo.h"
#include "lfunc.h"
#include "lobject.h"
#include "lstate.h"
#include "ltable.h"
#include "ltm.h"
#include "lua.h"
#include "luadebug.h"
static const lua_Type normtype[] = { /* ORDER LUA_T */
TAG_USERDATA, TAG_NUMBER, TAG_STRING, TAG_TABLE,
TAG_LCLOSURE, TAG_CCLOSURE, TAG_NIL,
TAG_LCLOSURE, TAG_CCLOSURE /* TAG_LMARK, TAG_CMARK */
};
static void setnormalized (TObject *d, const TObject *s) {
d->value = s->value;
d->ttype = normtype[ttype(s)];
}
static int hasdebuginfo (lua_State *L, StkId f) {
return (f+1 < L->top && (f+1)->ttype == TAG_LINE);
}
lua_Hook lua_setcallhook (lua_State *L, lua_Hook func) {
lua_Hook oldhook = L->callhook;
L->callhook = func;
return oldhook;
}
lua_Hook lua_setlinehook (lua_State *L, lua_Hook func) {
lua_Hook oldhook = L->linehook;
L->linehook = func;
return oldhook;
}
int lua_setdebug (lua_State *L, int debug) {
int old = L->debug;
L->debug = debug;
return old;
}
static StkId aux_stackedfunction (lua_State *L, int level, StkId top) {
int i;
for (i = (top-1)-L->stack; i>=0; i--) {
if (is_T_MARK(L->stack[i].ttype)) {
if (level == 0)
return L->stack+i;
level--;
}
}
return NULL;
}
int lua_getstack (lua_State *L, int level, lua_Debug *ar) {
StkId f = aux_stackedfunction(L, level, L->top);
if (f == NULL) return 0; /* there is no such level */
else {
ar->_func = f;
return 1;
}
}
static int lua_nups (StkId f) {
switch (ttype(f)) {
case TAG_LCLOSURE: case TAG_CCLOSURE:
case TAG_LMARK: case TAG_CMARK:
return f->value.cl->nelems;
default:
return 0;
}
}
static int lua_currentline (lua_State *L, StkId f) {
return hasdebuginfo(L, f) ? (f+1)->value.i : -1;
}
static Proto *getluaproto (StkId f) {
return (ttype(f) == TAG_LMARK) ? clvalue(f)->f.l : NULL;
}
int lua_getlocal (lua_State *L, const lua_Debug *ar, lua_Localvar *v) {
StkId f = ar->_func;
Proto *fp = getluaproto(f);
if (!fp) return 0; /* `f' is not a Lua function? */
v->name = luaF_getlocalname(fp, v->index, lua_currentline(L, f));
if (!v->name) return 0;
/* if `name', there must be a TAG_LINE */
/* therefore, f+2 points to function base */
LUA_ASSERT(L, ttype(f+1) == TAG_LINE, "");
v->value = luaA_putluaObject(L, (f+2)+(v->index-1));
return 1;
}
int lua_setlocal (lua_State *L, const lua_Debug *ar, lua_Localvar *v) {
StkId f = ar->_func;
Proto *fp = getluaproto(f);
if (!fp) return 0; /* `f' is not a Lua function? */
v->name = luaF_getlocalname(fp, v->index, lua_currentline(L, f));
if (!v->name) return 0;
LUA_ASSERT(L, ttype(f+1) == TAG_LINE, "");
*((f+2)+(v->index-1)) = *v->value;
return 1;
}
static void lua_funcinfo (lua_Debug *ar) {
StkId func = ar->_func;
switch (ttype(func)) {
case TAG_LCLOSURE: case TAG_LMARK:
ar->source = clvalue(func)->f.l->source->str;
ar->linedefined = clvalue(func)->f.l->lineDefined;
ar->what = "Lua";
break;
case TAG_CCLOSURE: case TAG_CMARK:
ar->source = "(C)";
ar->linedefined = -1;
ar->what = "C";
break;
default:
LUA_INTERNALERROR(L, "invalid `func' value");
}
if (ar->linedefined == 0)
ar->what = "main";
}
static int checkfunc (lua_State *L, TObject *o) {
return luaO_equalObj(o, L->top);
}
static void lua_getobjname (lua_State *L, StkId f, lua_Debug *ar) {
GlobalVar *g;
/* try to find a name for given function */
setnormalized(L->top, f); /* to be used by `checkfunc' */
for (g=L->rootglobal; g; g=g->next) {
if (checkfunc(L, &g->value)) {
ar->name = g->name->str;
ar->namewhat = "global";
return;
}
}
/* not found: try tag methods */
if ((ar->name = luaT_travtagmethods(L, checkfunc)) != NULL)
ar->namewhat = "tag-method";
else ar->namewhat = ""; /* not found at all */
}
int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) {
StkId func = ar->_func;
LUA_ASSERT(L, is_T_MARK(ttype(func)), "invalid activation record");
for (; *what; what++) {
switch (*what) {
case 'S':
lua_funcinfo(ar);
break;
case 'l':
ar->currentline = lua_currentline(L, func);
break;
case 'u':
ar->nups = lua_nups(func);
break;
case 'n':
lua_getobjname(L, func, ar);
break;
case 'f':
setnormalized(L->top, func);
incr_top;
ar->func = luaA_putObjectOnTop(L);
break;
default: return 0; /* invalid option */
}
}
return 1;
}
static void call_index_error (lua_State *L, TObject *o, const char *v) {
luaL_verror(L, "attempt to %.10s a %.10s value", v, lua_type(L, o));
}
void luaG_callerror (lua_State *L, TObject *func) {
call_index_error(L, func, "call");
}
void luaG_indexerror (lua_State *L, TObject *t) {
call_index_error(L, t, "index");
}

19
ldebug.h Normal file
View File

@@ -0,0 +1,19 @@
/*
** $Id: $
** Auxiliary functions from Debug Interface module
** See Copyright Notice in lua.h
*/
#ifndef ldebug_h
#define ldebug_h
#include "lobject.h"
#include "luadebug.h"
void luaG_callerror (lua_State *L, TObject *func);
void luaG_indexerror (lua_State *L, TObject *t);
#endif

491
ldo.c
View File

@@ -1,5 +1,5 @@
/*
** $Id: ldo.c,v 1.26 1998/06/15 21:34:14 roberto Exp roberto $
** $Id: ldo.c,v 1.72 2000/03/30 20:55:50 roberto Exp roberto $
** Stack and Call structure of Lua
** See Copyright Notice in lua.h
*/
@@ -10,13 +10,17 @@
#include <stdlib.h>
#include <string.h>
#define LUA_REENTRANT
#include "lauxlib.h"
#include "ldebug.h"
#include "ldo.h"
#include "lfunc.h"
#include "lgc.h"
#include "lmem.h"
#include "lobject.h"
#include "lparser.h"
#include "lstate.h"
#include "lstring.h"
#include "ltm.h"
#include "lua.h"
#include "luadebug.h"
@@ -25,279 +29,245 @@
#include "lzio.h"
#ifndef STACK_LIMIT
#define STACK_LIMIT 6000
#endif
#define EXTRA_STACK 32 /* space to handle stack overflow errors */
/*
** Error messages
** typical numer of stack slots used by a (big) function
** (this constant is used only for choosing error messages)
*/
#define SLOTS_PER_F 20
static void stderrorim (void)
{
fprintf(stderr, "lua error: %s\n", lua_getstring(lua_getparam(1)));
void luaD_init (lua_State *L, int stacksize) {
L->stack = luaM_newvector(L, stacksize+EXTRA_STACK, TObject);
L->stack_last = L->stack+(stacksize-1);
L->stacksize = stacksize;
L->Cstack.base = L->Cstack.lua2C = L->top = L->stack;
L->Cstack.num = 0;
}
#define STACK_UNIT 128
void luaD_init (void)
{
L->stack.stack = luaM_newvector(STACK_UNIT, TObject);
L->stack.top = L->stack.stack;
L->stack.last = L->stack.stack+(STACK_UNIT-1);
ttype(&L->errorim) = LUA_T_CPROTO;
fvalue(&L->errorim) = stderrorim;
}
void luaD_checkstack (int n)
{
struct Stack *S = &L->stack;
if (S->last-S->top <= n) {
StkId top = S->top-S->stack;
int stacksize = (S->last-S->stack)+1+STACK_UNIT+n;
S->stack = luaM_reallocvector(S->stack, stacksize, TObject);
S->last = S->stack+(stacksize-1);
S->top = S->stack + top;
if (stacksize >= STACK_LIMIT) { /* stack overflow? */
if (lua_stackedfunction(100) == LUA_NOOBJECT) /* 100 funcs on stack? */
lua_error("Lua2C - C2Lua overflow"); /* doesn't look like a rec. loop */
void luaD_checkstack (lua_State *L, int n) {
if (L->stack_last-L->top <= n) { /* stack overflow? */
if (L->stack_last-L->stack > (L->stacksize-1)) {
/* overflow while handling overflow: do what?? */
L->top -= EXTRA_STACK;
lua_error(L, "BAD STACK OVERFLOW! DATA CORRUPTED!");
}
else {
lua_Debug dummy;
L->stack_last += EXTRA_STACK; /* to be used by error message */
if (lua_getstack(L, L->stacksize/SLOTS_PER_F, &dummy) == 0) {
/* too few funcs on stack: doesn't look like a recursion loop */
lua_error(L, "Lua2C - C2Lua overflow");
}
else
lua_error("stack size overflow");
lua_error(L, "stack overflow; possible recursion loop");
}
}
}
static void restore_stack_limit (lua_State *L) {
if (L->top-L->stack < L->stacksize-1)
L->stack_last = L->stack+(L->stacksize-1);
}
/*
** Adjust stack. Set top to the given value, pushing NILs if needed.
** Adjust stack. Set top to base+extra, pushing NILs if needed.
** (we cannot add base+extra unless we are sure it fits in the stack;
** otherwise the result of such operation on pointers is undefined)
*/
void luaD_adjusttop (StkId newtop)
{
int diff = newtop-(L->stack.top-L->stack.stack);
void luaD_adjusttop (lua_State *L, StkId base, int extra) {
int diff = extra-(L->top-base);
if (diff <= 0)
L->stack.top += diff;
L->top = base+extra;
else {
luaD_checkstack(diff);
luaD_checkstack(L, diff);
while (diff--)
ttype(L->stack.top++) = LUA_T_NIL;
ttype(L->top++) = TAG_NIL;
}
}
/*
** Open a hole below "nelems" from the L->stack.top.
** Open a hole inside the stack at `pos'
*/
void luaD_openstack (int nelems)
{
luaO_memup(L->stack.top-nelems+1, L->stack.top-nelems,
nelems*sizeof(TObject));
void luaD_openstack (lua_State *L, StkId pos) {
int i = L->top-pos;
while (i--) pos[i+1] = pos[i];
incr_top;
}
void luaD_lineHook (int line)
{
struct C_Lua_Stack oldCLS = L->Cstack;
StkId old_top = L->Cstack.lua2C = L->Cstack.base = L->stack.top-L->stack.stack;
L->Cstack.num = 0;
(*lua_linehook)(line);
L->stack.top = L->stack.stack+old_top;
L->Cstack = oldCLS;
}
void luaD_callHook (StkId base, TProtoFunc *tf, int isreturn)
{
struct C_Lua_Stack oldCLS = L->Cstack;
StkId old_top = L->Cstack.lua2C = L->Cstack.base = L->stack.top-L->stack.stack;
L->Cstack.num = 0;
if (isreturn)
(*lua_callhook)(LUA_NOOBJECT, "(return)", 0);
else {
TObject *f = L->stack.stack+base-1;
if (tf)
(*lua_callhook)(Ref(f), tf->fileName->str, tf->lineDefined);
else
(*lua_callhook)(Ref(f), "(C)", -1);
void luaD_lineHook (lua_State *L, StkId func, int line) {
if (L->allowhooks) {
lua_Debug ar;
struct C_Lua_Stack oldCLS = L->Cstack;
StkId old_top = L->Cstack.lua2C = L->Cstack.base = L->top;
L->Cstack.num = 0;
ar._func = func;
ar.event = "line";
ar.currentline = line;
L->allowhooks = 0; /* cannot call hooks inside a hook */
(*L->linehook)(L, &ar);
L->allowhooks = 1;
L->top = old_top;
L->Cstack = oldCLS;
}
L->stack.top = L->stack.stack+old_top;
L->Cstack = oldCLS;
}
/*
** Call a C function.
** Cstack.num is the number of arguments; Cstack.lua2C points to the
** first argument. Returns an index to the first result from C.
*/
static StkId callC (lua_CFunction f, StkId base)
{
struct C_Lua_Stack *CS = &L->Cstack;
struct C_Lua_Stack oldCLS = *CS;
static void luaD_callHook (lua_State *L, StkId func, lua_Hook callhook,
const char *event) {
if (L->allowhooks) {
lua_Debug ar;
struct C_Lua_Stack oldCLS = L->Cstack;
StkId old_top = L->Cstack.lua2C = L->Cstack.base = L->top;
L->Cstack.num = 0;
ar._func = func;
ar.event = event;
L->allowhooks = 0; /* cannot call hooks inside a hook */
callhook(L, &ar);
L->allowhooks = 1;
L->top = old_top;
L->Cstack = oldCLS;
}
}
static StkId callCclosure (lua_State *L, const struct Closure *cl, StkId base) {
int nup = cl->nelems; /* number of upvalues */
int numarg = L->top-base;
struct C_Lua_Stack oldCLS = L->Cstack;
StkId firstResult;
int numarg = (L->stack.top-L->stack.stack) - base;
CS->num = numarg;
CS->lua2C = base;
CS->base = base+numarg; /* == top-stack */
if (lua_callhook)
luaD_callHook(base, NULL, 0);
(*f)(); /* do the actual call */
if (lua_callhook) /* func may have changed lua_callhook */
luaD_callHook(base, NULL, 1);
firstResult = CS->base;
*CS = oldCLS;
if (nup > 0) {
int n = numarg;
luaD_checkstack(L, nup);
/* open space for upvalues as extra arguments */
while (n--) *(base+nup+n) = *(base+n);
L->top += nup;
numarg += nup;
/* copy upvalues into stack */
while (nup--) *(base+nup) = cl->consts[nup];
}
L->Cstack.num = numarg;
L->Cstack.lua2C = base;
L->Cstack.base = L->top;
(*cl->f.c)(L); /* do the actual call */
firstResult = L->Cstack.base;
L->Cstack = oldCLS;
return firstResult;
}
static StkId callCclosure (struct Closure *cl, lua_CFunction f, StkId base)
{
TObject *pbase;
int nup = cl->nelems; /* number of upvalues */
luaD_checkstack(nup);
pbase = L->stack.stack+base; /* care: previous call may change this */
/* open space for upvalues as extra arguments */
luaO_memup(pbase+nup, pbase, (L->stack.top-pbase)*sizeof(TObject));
/* copy upvalues into stack */
memcpy(pbase, cl->consts+1, nup*sizeof(TObject));
L->stack.top += nup;
return callC(f, base);
}
void luaD_callTM (TObject *f, int nParams, int nResults)
{
luaD_openstack(nParams);
*(L->stack.top-nParams-1) = *f;
luaD_call((L->stack.top-L->stack.stack)-nParams, nResults);
void luaD_callTM (lua_State *L, const TObject *f, int nParams, int nResults) {
StkId base = L->top - nParams;
luaD_openstack(L, base);
*base = *f;
luaD_call(L, base, nResults);
}
/*
** Call a function (C or Lua). The parameters must be on the L->stack.stack,
** between [L->stack.stack+base,L->stack.top). The function to be called is at L->stack.stack+base-1.
** When returns, the results are on the L->stack.stack, between [L->stack.stack+base-1,L->stack.top).
** Call a function (C or Lua). The function to be called is at *func.
** The arguments are on the stack, right after the function.
** When returns, the results are on the stack, starting at the original
** function position.
** The number of results is nResults, unless nResults=MULT_RET.
*/
void luaD_call (StkId base, int nResults)
{
*/
void luaD_call (lua_State *L, StkId func, int nResults) {
StkId firstResult;
TObject *func = L->stack.stack+base-1;
int i;
lua_Hook callhook = L->callhook;
retry: /* for `function' tag method */
switch (ttype(func)) {
case LUA_T_CPROTO:
ttype(func) = LUA_T_CMARK;
firstResult = callC(fvalue(func), base);
break;
case LUA_T_PROTO:
ttype(func) = LUA_T_PMARK;
firstResult = luaV_execute(NULL, tfvalue(func), base);
break;
case LUA_T_CLOSURE: {
Closure *c = clvalue(func);
TObject *proto = &(c->consts[0]);
ttype(func) = LUA_T_CLMARK;
firstResult = (ttype(proto) == LUA_T_CPROTO) ?
callCclosure(c, fvalue(proto), base) :
luaV_execute(c, tfvalue(proto), base);
case TAG_LCLOSURE: {
ttype(func) = TAG_LMARK;
if (callhook)
luaD_callHook(L, func, callhook, "call");
firstResult = luaV_execute(L, clvalue(func), func+1);
break;
}
default: { /* func is not a function */
/* Check the tag method for invalid functions */
TObject *im = luaT_getimbyObj(func, IM_FUNCTION);
if (ttype(im) == LUA_T_NIL)
lua_error("call expression not a function");
luaD_callTM(im, (L->stack.top-L->stack.stack)-(base-1), nResults);
return;
case TAG_CCLOSURE: {
ttype(func) = TAG_CMARK;
if (callhook)
luaD_callHook(L, func, callhook, "call");
firstResult = callCclosure(L, clvalue(func), func+1);
break;
}
default: { /* `func' is not a function; check the `function' tag method */
const TObject *im = luaT_getimbyObj(L, func, IM_FUNCTION);
if (ttype(im) == TAG_NIL)
luaG_callerror(L, func);
luaD_openstack(L, func);
*func = *im; /* tag method is the new function to be called */
goto retry; /* retry the call */
}
}
if (callhook) /* same hook that was active at entry */
luaD_callHook(L, func, callhook, "return");
/* adjust the number of results */
if (nResults != MULT_RET)
luaD_adjusttop(firstResult+nResults);
/* move results to base-1 (to erase parameters and function) */
base--;
nResults = L->stack.top - (L->stack.stack+firstResult); /* actual number of results */
for (i=0; i<nResults; i++)
*(L->stack.stack+base+i) = *(L->stack.stack+firstResult+i);
L->stack.top -= firstResult-base;
if (nResults == MULT_RET)
nResults = L->top - firstResult;
else
luaD_adjusttop(L, firstResult, nResults);
/* move results to `func' (to erase parameters and function) */
while (nResults) {
*func++ = *(L->top - nResults);
nResults--;
}
L->top = func;
}
/*
** Traverse all objects on L->stack.stack
*/
void luaD_travstack (int (*fn)(TObject *))
{
StkId i;
for (i = (L->stack.top-1)-L->stack.stack; i>=0; i--)
fn(L->stack.stack+i);
}
static void message (char *s)
{
TObject im = L->errorim;
if (ttype(&im) != LUA_T_NIL) {
lua_pushstring(s);
luaD_callTM(&im, 1, 0);
static void message (lua_State *L, const char *s) {
const TObject *em = &(luaS_assertglobalbyname(L, "_ERRORMESSAGE")->value);
if (*luaO_typename(em) == 'f') {
*L->top = *em;
incr_top;
lua_pushstring(L, s);
luaD_call(L, L->top-2, 0);
}
}
/*
** Reports an error, and jumps up to the available recover label
** Reports an error, and jumps up to the available recovery label
*/
void lua_error (char *s)
{
if (s) message(s);
void lua_error (lua_State *L, const char *s) {
if (s) message(L, s);
if (L->errorJmp)
longjmp(*((jmp_buf *)L->errorJmp), 1);
longjmp(L->errorJmp->b, 1);
else {
fprintf (stderr, "lua: exit(1). Unable to recover\n");
message(L, "unable to recover; exiting\n");
exit(1);
}
}
/*
** Call the function at L->Cstack.base, and incorporate results on
** the Lua2C structure.
** Execute a protected call. Assumes that function is at Cstack.base and
** parameters are on top of it.
*/
static void do_callinc (int nResults)
{
int luaD_protectedrun (lua_State *L) {
struct lua_longjmp myErrorJmp;
StkId base = L->Cstack.base;
luaD_call(base+1, nResults);
L->Cstack.lua2C = base; /* position of the luaM_new results */
L->Cstack.num = (L->stack.top-L->stack.stack) - base; /* number of results */
L->Cstack.base = base + L->Cstack.num; /* incorporate results on L->stack.stack */
}
/*
** Execute a protected call. Assumes that function is at L->Cstack.base and
** parameters are on top of it. Leave nResults on the stack.
*/
int luaD_protectedrun (int nResults)
{
jmp_buf myErrorJmp;
int numCblocks = L->numCblocks;
int status;
volatile struct C_Lua_Stack oldCLS = L->Cstack;
jmp_buf *volatile oldErr = L->errorJmp;
struct lua_longjmp *volatile oldErr = L->errorJmp;
L->errorJmp = &myErrorJmp;
if (setjmp(myErrorJmp) == 0) {
do_callinc(nResults);
if (setjmp(myErrorJmp.b) == 0) {
luaD_call(L, base, MULT_RET);
L->Cstack.lua2C = base; /* position of the new results */
L->Cstack.num = L->top - base;
L->Cstack.base = base + L->Cstack.num; /* incorporate results on stack */
status = 0;
}
else { /* an error occurred: restore L->Cstack and L->stack.top */
L->Cstack = oldCLS;
L->stack.top = L->stack.stack+L->Cstack.base;
else { /* an error occurred: restore the stack */
L->Cstack.num = 0; /* no results */
L->top = L->Cstack.base = L->Cstack.lua2C = base;
L->numCblocks = numCblocks;
restore_stack_limit(L);
status = 1;
}
L->errorJmp = oldErr;
@@ -308,120 +278,89 @@ int luaD_protectedrun (int nResults)
/*
** returns 0 = chunk loaded; 1 = error; 2 = no more chunks to load
*/
static int protectedparser (ZIO *z, int bin)
{
volatile int status;
TProtoFunc *volatile tf;
jmp_buf myErrorJmp;
jmp_buf *volatile oldErr = L->errorJmp;
static int protectedparser (lua_State *L, ZIO *z, int bin) {
struct lua_longjmp myErrorJmp;
StkId base = L->Cstack.base;
int numCblocks = L->numCblocks;
int status;
Proto *volatile tf;
struct lua_longjmp *volatile oldErr = L->errorJmp;
L->errorJmp = &myErrorJmp;
if (setjmp(myErrorJmp) == 0) {
tf = bin ? luaU_undump1(z) : luaY_parser(z);
L->top = base; /* clear C2Lua */
if (setjmp(myErrorJmp.b) == 0) {
tf = bin ? luaU_undump1(L, z) : luaY_parser(L, z);
status = 0;
}
else {
else { /* an error occurred: restore Cstack and top */
L->Cstack.num = 0; /* no results */
L->top = L->Cstack.base = L->Cstack.lua2C = base;
L->numCblocks = numCblocks;
tf = NULL;
status = 1;
}
L->errorJmp = oldErr;
if (status) return 1; /* error code */
if (tf == NULL) return 2; /* 'natural' end */
luaD_adjusttop(L->Cstack.base+1); /* one slot for the pseudo-function */
L->stack.stack[L->Cstack.base].ttype = LUA_T_PROTO;
L->stack.stack[L->Cstack.base].value.tf = tf;
luaV_closure(0);
if (tf == NULL) return 2; /* `natural' end */
luaV_Lclosure(L, tf, 0);
return 0;
}
static int do_main (ZIO *z, int bin)
{
static int do_main (lua_State *L, ZIO *z, int bin) {
int status;
int debug = L->debug; /* save debug status */
do {
long old_blocks = (luaC_checkGC(), L->nblocks);
status = protectedparser(z, bin);
long old_blocks = (luaC_checkGC(L), L->nblocks);
status = protectedparser(L, z, bin);
if (status == 1) return 1; /* error */
else if (status == 2) return 0; /* 'natural' end */
else if (status == 2) return 0; /* `natural' end */
else {
unsigned long newelems2 = 2*(L->nblocks-old_blocks);
L->GCthreshold += newelems2;
status = luaD_protectedrun(MULT_RET);
status = luaD_protectedrun(L);
L->GCthreshold -= newelems2;
}
} while (bin && status == 0);
L->debug = debug; /* restore debug status */
return status;
}
void luaD_gcIM (TObject *o)
{
TObject *im = luaT_getimbyObj(o, IM_GC);
if (ttype(im) != LUA_T_NIL) {
*L->stack.top = *o;
incr_top;
luaD_callTM(im, 1, 0);
}
}
#define MAXFILENAME 260 /* maximum part of a file name kept */
int lua_dofile (char *filename)
{
int lua_dofile (lua_State *L, const char *filename) {
ZIO z;
int status;
int c;
int bin;
int bin; /* flag for file mode */
int c; /* look ahead char */
char source[MAXFILENAME];
FILE *f = (filename == NULL) ? stdin : fopen(filename, "r");
if (f == NULL)
return 2;
if (filename == NULL)
filename = "(stdin)";
if (f == NULL) return 2; /* unable to open file */
luaL_filesource(source, filename, sizeof(source));
c = fgetc(f);
ungetc(c, f);
bin = (c == ID_CHUNK);
if (bin)
if (bin && f != stdin) {
f = freopen(filename, "rb", f); /* set binary mode */
luaZ_Fopen(&z, f, filename);
status = do_main(&z, bin);
if (f == NULL) return 2; /* unable to reopen file */
}
luaZ_Fopen(&z, f, source);
status = do_main(L, &z, bin);
if (f != stdin)
fclose(f);
return status;
}
#define SIZE_PREF 20 /* size of string prefix to appear in error messages */
#define SSIZE_PREF "20"
static void build_name (char *str, char *name) {
if (str == NULL || *str == ID_CHUNK)
strcpy(name, "(buffer)");
else {
char *temp;
sprintf(name, "(dostring) >> \"%." SSIZE_PREF "s\"", str);
temp = strchr(name, '\n');
if (temp) { /* end string after first line */
*temp = '"';
*(temp+1) = 0;
}
}
int lua_dostring (lua_State *L, const char *str) {
return lua_dobuffer(L, str, strlen(str), str);
}
int lua_dostring (char *str) {
return lua_dobuffer(str, strlen(str), NULL);
}
int lua_dobuffer (char *buff, int size, char *name) {
char newname[SIZE_PREF+25];
int lua_dobuffer (lua_State *L, const char *buff, int size, const char *name) {
ZIO z;
int status;
if (name==NULL) {
build_name(buff, newname);
name = newname;
}
if (!name) name = "?";
luaZ_mopen(&z, buff, size, name);
status = do_main(&z, buff[0]==ID_CHUNK);
return status;
return do_main(L, &z, buff[0]==ID_CHUNK);
}

34
ldo.h
View File

@@ -1,5 +1,5 @@
/*
** $Id: ldo.h,v 1.3 1997/11/19 17:29:23 roberto Exp roberto $
** $Id: ldo.h,v 1.19 2000/03/29 20:19:20 roberto Exp roberto $
** Stack and Call structure of Lua
** See Copyright Notice in lua.h
*/
@@ -12,35 +12,21 @@
#include "lstate.h"
#define MULT_RET 255
/*
** macro to increment stack top.
** There must be always an empty slot at the L->stack.top
*/
#define incr_top { if (L->stack.top >= L->stack.last) luaD_checkstack(1); \
L->stack.top++; }
#define incr_top {if (L->top == L->stack_last) luaD_checkstack(L, 1); L->top++;}
/* macros to convert from lua_Object to (TObject *) and back */
#define Address(lo) ((lo)+L->stack.stack-1)
#define Ref(st) ((st)-L->stack.stack+1)
void luaD_init (void);
void luaD_adjusttop (StkId newtop);
void luaD_openstack (int nelems);
void luaD_lineHook (int line);
void luaD_callHook (StkId base, TProtoFunc *tf, int isreturn);
void luaD_call (StkId base, int nResults);
void luaD_callTM (TObject *f, int nParams, int nResults);
int luaD_protectedrun (int nResults);
void luaD_gcIM (TObject *o);
void luaD_travstack (int (*fn)(TObject *));
void luaD_checkstack (int n);
void luaD_init (lua_State *L, int stacksize);
void luaD_adjusttop (lua_State *L, StkId base, int extra);
void luaD_openstack (lua_State *L, StkId pos);
void luaD_lineHook (lua_State *L, StkId func, int line);
void luaD_call (lua_State *L, StkId func, int nResults);
void luaD_callTM (lua_State *L, const TObject *f, int nParams, int nResults);
int luaD_protectedrun (lua_State *L);
void luaD_checkstack (lua_State *L, int n);
#endif

86
lfunc.c
View File

@@ -1,5 +1,5 @@
/*
** $Id: lfunc.c,v 1.8 1997/12/15 16:17:20 roberto Exp roberto $
** $Id: lfunc.c,v 1.20 2000/03/10 18:37:44 roberto Exp roberto $
** Auxiliary functions to manipulate prototypes and closures
** See Copyright Notice in lua.h
*/
@@ -7,80 +7,74 @@
#include <stdlib.h>
#define LUA_REENTRANT
#include "lfunc.h"
#include "lmem.h"
#include "lstate.h"
#define gcsizeproto(p) 5 /* approximate "weight" for a prototype */
#define gcsizeclosure(c) 1 /* approximate "weight" for a closure */
#define gcsizeproto(L, p) numblocks(L, 0, sizeof(Proto))
#define gcsizeclosure(L, c) numblocks(L, c->nelems, sizeof(Closure))
Closure *luaF_newclosure (int nelems)
{
Closure *c = (Closure *)luaM_malloc(sizeof(Closure)+nelems*sizeof(TObject));
luaO_insertlist(&(L->rootcl), (GCnode *)c);
L->nblocks += gcsizeclosure(c);
Closure *luaF_newclosure (lua_State *L, int nelems) {
Closure *c = (Closure *)luaM_malloc(L, sizeof(Closure) +
sizeof(TObject)*(nelems-1));
c->next = L->rootcl;
L->rootcl = c;
c->marked = 0;
c->nelems = nelems;
L->nblocks += gcsizeclosure(L, c);
return c;
}
TProtoFunc *luaF_newproto (void)
{
TProtoFunc *f = luaM_new(TProtoFunc);
Proto *luaF_newproto (lua_State *L) {
Proto *f = luaM_new(L, Proto);
f->code = NULL;
f->lineDefined = 0;
f->fileName = NULL;
f->consts = NULL;
f->nconsts = 0;
f->source = NULL;
f->kstr = NULL;
f->nkstr = 0;
f->knum = NULL;
f->nknum = 0;
f->kproto = NULL;
f->nkproto = 0;
f->locvars = NULL;
luaO_insertlist(&(L->rootproto), (GCnode *)f);
L->nblocks += gcsizeproto(f);
f->next = L->rootproto;
L->rootproto = f;
f->marked = 0;
L->nblocks += gcsizeproto(L, f);
return f;
}
static void freefunc (TProtoFunc *f)
{
luaM_free(f->code);
luaM_free(f->locvars);
luaM_free(f->consts);
luaM_free(f);
void luaF_freeproto (lua_State *L, Proto *f) {
L->nblocks -= gcsizeproto(L, f);
luaM_free(L, f->code);
luaM_free(L, f->locvars);
luaM_free(L, f->kstr);
luaM_free(L, f->knum);
luaM_free(L, f->kproto);
luaM_free(L, f);
}
void luaF_freeproto (TProtoFunc *l)
{
while (l) {
TProtoFunc *next = (TProtoFunc *)l->head.next;
L->nblocks -= gcsizeproto(l);
freefunc(l);
l = next;
}
}
void luaF_freeclosure (Closure *l)
{
while (l) {
Closure *next = (Closure *)l->head.next;
L->nblocks -= gcsizeclosure(l);
luaM_free(l);
l = next;
}
void luaF_freeclosure (lua_State *L, Closure *c) {
L->nblocks -= gcsizeclosure(L, c);
luaM_free(L, c);
}
/*
** Look for n-th local variable at line "line" in function "func".
** Look for n-th local variable at line `line' in function `func'.
** Returns NULL if not found.
*/
char *luaF_getlocalname (TProtoFunc *func, int local_number, int line)
{
const char *luaF_getlocalname (const Proto *func,
int local_number, int line) {
int count = 0;
char *varname = NULL;
const char *varname = NULL;
LocVar *lv = func->locvars;
if (lv == NULL)
return NULL;

15
lfunc.h
View File

@@ -1,6 +1,6 @@
/*
** $Id: lfunc.h,v 1.4 1997/11/19 17:29:23 roberto Exp roberto $
** Lua Function structures
** $Id: lfunc.h,v 1.10 1999/12/27 17:33:22 roberto Exp roberto $
** Auxiliary functions to manipulate prototypes and closures
** See Copyright Notice in lua.h
*/
@@ -12,12 +12,13 @@
TProtoFunc *luaF_newproto (void);
Closure *luaF_newclosure (int nelems);
void luaF_freeproto (TProtoFunc *l);
void luaF_freeclosure (Closure *l);
Proto *luaF_newproto (lua_State *L);
Closure *luaF_newclosure (lua_State *L, int nelems);
void luaF_freeproto (lua_State *L, Proto *f);
void luaF_freeclosure (lua_State *L, Closure *c);
char *luaF_getlocalname (TProtoFunc *func, int local_number, int line);
const char *luaF_getlocalname (const Proto *func,
int local_number, int line);
#endif

419
lgc.c
View File

@@ -1,15 +1,17 @@
/*
** $Id: lgc.c,v 1.17 1998/03/06 16:54:42 roberto Exp roberto $
** $Id: lgc.c,v 1.46 2000/03/30 20:55:50 roberto Exp roberto $
** Garbage Collector
** See Copyright Notice in lua.h
*/
#define LUA_REENTRANT
#include "ldo.h"
#include "lfunc.h"
#include "lgc.h"
#include "lmem.h"
#include "lobject.h"
#include "lref.h"
#include "lstate.h"
#include "lstring.h"
#include "ltable.h"
@@ -18,271 +20,250 @@
static int markobject (TObject *o);
/*
** =======================================================
** REF mechanism
** =======================================================
*/
int luaC_ref (TObject *o, int lock)
{
int ref;
if (ttype(o) == LUA_T_NIL)
ref = -1; /* special ref for nil */
else {
for (ref=0; ref<L->refSize; ref++)
if (L->refArray[ref].status == FREE)
goto found;
/* no more empty spaces */ {
int oldSize = L->refSize;
L->refSize = luaM_growvector(&L->refArray, L->refSize, struct ref,
refEM, MAX_INT);
for (ref=oldSize; ref<L->refSize; ref++)
L->refArray[ref].status = FREE;
ref = oldSize;
} found:
L->refArray[ref].o = *o;
L->refArray[ref].status = lock ? LOCK : HOLD;
}
return ref;
}
void lua_unref (int ref)
{
if (ref >= 0 && ref < L->refSize)
L->refArray[ref].status = FREE;
}
TObject* luaC_getref (int ref)
{
if (ref == -1)
return &luaO_nilobject;
if (ref >= 0 && ref < L->refSize &&
(L->refArray[ref].status == LOCK || L->refArray[ref].status == HOLD))
return &L->refArray[ref].o;
else
return NULL;
}
static void travlock (void)
{
int i;
for (i=0; i<L->refSize; i++)
if (L->refArray[i].status == LOCK)
markobject(&L->refArray[i].o);
}
static int ismarked (TObject *o)
{
/* valid only for locked objects */
switch (o->ttype) {
case LUA_T_STRING: case LUA_T_USERDATA:
return o->value.ts->head.marked;
case LUA_T_ARRAY:
return o->value.a->head.marked;
case LUA_T_CLOSURE:
return o->value.cl->head.marked;
case LUA_T_PROTO:
return o->value.tf->head.marked;
#ifdef DEBUG
case LUA_T_LINE: case LUA_T_CLMARK:
case LUA_T_CMARK: case LUA_T_PMARK:
LUA_INTERNALERROR("invalid type");
#endif
default: /* nil, number or cproto */
return 1;
static void luaD_gcTM (lua_State *L, const TObject *o) {
const TObject *im = luaT_getimbyObj(L, o, IM_GC);
if (ttype(im) != TAG_NIL) {
luaD_checkstack(L, 2);
*(L->top++) = *im;
*(L->top++) = *o;
luaD_call(L, L->top-2, 0);
}
}
static void invalidaterefs (void)
{
int i;
for (i=0; i<L->refSize; i++)
if (L->refArray[i].status == HOLD && !ismarked(&L->refArray[i].o))
L->refArray[i].status = COLLECTED;
}
static int markobject (lua_State *L, TObject *o);
/* mark a string; marks larger than 1 cannot be changed */
#define strmark(L, s) {if ((s)->marked == 0) (s)->marked = 1;}
void luaC_hashcallIM (Hash *l)
{
TObject t;
ttype(&t) = LUA_T_ARRAY;
for (; l; l=(Hash *)l->head.next) {
avalue(&t) = l;
luaD_gcIM(&t);
}
}
void luaC_strcallIM (TaggedString *l)
{
TObject o;
ttype(&o) = LUA_T_USERDATA;
for (; l; l=(TaggedString *)l->head.next)
if (l->constindex == -1) { /* is userdata? */
tsvalue(&o) = l;
luaD_gcIM(&o);
}
}
static GCnode *listcollect (GCnode *l)
{
GCnode *frees = NULL;
while (l) {
GCnode *next = l->next;
l->marked = 0;
while (next && !next->marked) {
l->next = next->next;
next->next = frees;
frees = next;
next = l->next;
}
l = next;
}
return frees;
}
static void strmark (TaggedString *s)
{
if (!s->head.marked)
s->head.marked = 1;
}
static void protomark (TProtoFunc *f)
{
if (!f->head.marked) {
LocVar *v = f->locvars;
static void protomark (lua_State *L, Proto *f) {
if (!f->marked) {
int i;
f->head.marked = 1;
if (f->fileName)
strmark(f->fileName);
for (i=0; i<f->nconsts; i++)
markobject(&f->consts[i]);
if (v) {
for (; v->line != -1; v++)
if (v->varname)
strmark(v->varname);
}
f->marked = 1;
strmark(L, f->source);
for (i=f->nkstr-1; i>=0; i--)
strmark(L, f->kstr[i]);
for (i=f->nkproto-1; i>=0; i--)
protomark(L, f->kproto[i]);
}
}
static void closuremark (Closure *f)
{
if (!f->head.marked) {
int i;
f->head.marked = 1;
for (i=f->nelems; i>=0; i--)
markobject(&f->consts[i]);
static void closuremark (lua_State *L, Closure *f) {
if (!f->marked) {
int i = f->nelems;
f->marked = 1;
while (i--)
markobject(L, &f->consts[i]);
}
}
static void hashmark (Hash *h)
{
if (!h->head.marked) {
static void hashmark (lua_State *L, Hash *h) {
if (!h->marked) {
int i;
h->head.marked = 1;
for (i=0; i<nhash(h); i++) {
h->marked = 1;
for (i=h->size-1; i>=0; i--) {
Node *n = node(h,i);
if (ttype(ref(n)) != LUA_T_NIL) {
markobject(&n->ref);
markobject(&n->val);
if (ttype(key(n)) != TAG_NIL) {
markobject(L, &n->key);
markobject(L, &n->val);
}
}
}
}
static void globalmark (void)
{
TaggedString *g;
for (g=(TaggedString *)L->rootglobal.next; g; g=(TaggedString *)g->head.next){
LUA_ASSERT(g->constindex >= 0, "userdata in global list");
if (g->u.s.globalval.ttype != LUA_T_NIL) {
markobject(&g->u.s.globalval);
strmark(g); /* cannot collect non nil global variables */
static void travglobal (lua_State *L) {
GlobalVar *gv;
for (gv=L->rootglobal; gv; gv=gv->next) {
LUA_ASSERT(L, gv->name->u.s.gv == gv, "inconsistent global name");
if (gv->value.ttype != TAG_NIL) {
strmark(L, gv->name); /* cannot collect non nil global variables */
markobject(L, &gv->value);
}
}
}
static int markobject (TObject *o)
{
static void travstack (lua_State *L) {
int i;
for (i = (L->top-1)-L->stack; i>=0; i--)
markobject(L, L->stack+i);
}
static void travlock (lua_State *L) {
int i;
for (i=0; i<L->refSize; i++) {
if (L->refArray[i].st == LOCK)
markobject(L, &L->refArray[i].o);
}
}
static int markobject (lua_State *L, TObject *o) {
switch (ttype(o)) {
case LUA_T_USERDATA: case LUA_T_STRING:
strmark(tsvalue(o));
case TAG_USERDATA: case TAG_STRING:
strmark(L, tsvalue(o));
break;
case LUA_T_ARRAY:
hashmark(avalue(o));
case TAG_TABLE:
hashmark(L, avalue(o));
break;
case LUA_T_CLOSURE: case LUA_T_CLMARK:
closuremark(o->value.cl);
case TAG_LCLOSURE: case TAG_LMARK:
protomark(L, clvalue(o)->f.l);
/* go trhough */
case TAG_CCLOSURE: case TAG_CMARK:
closuremark(L, clvalue(o));
break;
case LUA_T_PROTO: case LUA_T_PMARK:
protomark(o->value.tf);
break;
default: break; /* numbers, cprotos, etc */
default: break; /* numbers, etc */
}
return 0;
}
static void markall (void)
{
luaD_travstack(markobject); /* mark stack objects */
globalmark(); /* mark global variable values and names */
travlock(); /* mark locked objects */
luaT_travtagmethods(markobject); /* mark fallbacks */
static void collectproto (lua_State *L) {
Proto **p = &L->rootproto;
Proto *next;
while ((next = *p) != NULL) {
if (next->marked) {
next->marked = 0;
p = &next->next;
}
else {
*p = next->next;
luaF_freeproto(L, next);
}
}
}
long lua_collectgarbage (long limit)
{
unsigned long recovered = L->nblocks; /* to subtract nblocks after gc */
Hash *freetable;
TaggedString *freestr;
TProtoFunc *freefunc;
Closure *freeclos;
markall();
invalidaterefs();
freestr = luaS_collector();
freetable = (Hash *)listcollect(&(L->roottable));
freefunc = (TProtoFunc *)listcollect(&(L->rootproto));
freeclos = (Closure *)listcollect(&(L->rootcl));
static void collectclosure (lua_State *L) {
Closure **p = &L->rootcl;
Closure *next;
while ((next = *p) != NULL) {
if (next->marked) {
next->marked = 0;
p = &next->next;
}
else {
*p = next->next;
luaF_freeclosure(L, next);
}
}
}
static void collecttable (lua_State *L) {
Hash **p = &L->roottable;
Hash *next;
while ((next = *p) != NULL) {
if (next->marked) {
next->marked = 0;
p = &next->next;
}
else {
*p = next->next;
luaH_free(L, next);
}
}
}
/*
** remove from the global list globals whose names will be collected
** (the global itself is freed when its name is freed)
*/
static void clear_global_list (lua_State *L, int limit) {
GlobalVar **p = &L->rootglobal;
GlobalVar *next;
while ((next = *p) != NULL) {
if (next->name->marked >= limit) p = &next->next;
else *p = next->next;
}
}
/*
** collect all elements with `marked' < `limit'.
** with limit=1, that means all unmarked elements;
** with limit=MAX_INT, that means all elements.
*/
static void collectstring (lua_State *L, int limit) {
TObject o; /* to call userdata `gc' tag method */
int i;
ttype(&o) = TAG_USERDATA;
clear_global_list(L, limit);
for (i=0; i<NUM_HASHS; i++) { /* for each hash table */
stringtable *tb = &L->string_root[i];
int j;
for (j=0; j<tb->size; j++) { /* for each list */
TString **p = &tb->hash[j];
TString *next;
while ((next = *p) != NULL) {
if (next->marked >= limit) {
if (next->marked < FIXMARK) /* does not change FIXMARKs */
next->marked = 0;
p = &next->nexthash;
}
else { /* collect */
if (next->constindex == -1) { /* is userdata? */
tsvalue(&o) = next;
luaD_gcTM(L, &o);
}
*p = next->nexthash;
luaS_free(L, next);
tb->nuse--;
}
}
}
if ((tb->nuse+1)*6 < tb->size)
luaS_resize(L, tb, tb->size/2); /* table is too big */
}
}
static void markall (lua_State *L) {
travstack(L); /* mark stack objects */
travglobal(L); /* mark global variable values and names */
travlock(L); /* mark locked objects */
luaT_travtagmethods(L, markobject); /* mark tag methods */
}
void luaC_collect (lua_State *L, int all) {
int oldah = L->allowhooks;
L->allowhooks = 0; /* stop debug hooks during GC */
L->GCthreshold *= 4; /* to avoid GC during GC */
luaC_hashcallIM(freetable); /* GC tag methods for tables */
luaC_strcallIM(freestr); /* GC tag methods for userdata */
luaD_gcIM(&luaO_nilobject); /* GC tag method for nil (signal end of GC) */
luaH_free(freetable);
luaS_free(freestr);
luaF_freeproto(freefunc);
luaF_freeclosure(freeclos);
recovered = recovered-L->nblocks;
collecttable(L);
collectstring(L, all?MAX_INT:1);
collectproto(L);
collectclosure(L);
L->allowhooks = oldah; /* restore hooks */
}
long lua_collectgarbage (lua_State *L, long limit) {
unsigned long recovered = L->nblocks; /* to subtract `nblocks' after gc */
markall(L);
luaR_invalidaterefs(L);
luaC_collect(L, 0);
recovered = recovered - L->nblocks;
L->GCthreshold = (limit == 0) ? 2*L->nblocks : L->nblocks+limit;
if (L->Mbuffsize > L->Mbuffnext*4) { /* is buffer too big? */
L->Mbuffsize /= 2; /* still larger than Mbuffnext*2 */
luaM_reallocvector(L, L->Mbuffer, L->Mbuffsize, char);
}
luaD_gcTM(L, &luaO_nilobject);
return recovered;
}
void luaC_checkGC (void)
{
void luaC_checkGC (lua_State *L) {
if (L->nblocks >= L->GCthreshold)
lua_collectgarbage(0);
lua_collectgarbage(L, 0);
}

9
lgc.h
View File

@@ -1,5 +1,5 @@
/*
** $Id: lgc.h,v 1.3 1997/11/19 17:29:23 roberto Exp roberto $
** $Id: lgc.h,v 1.6 1999/10/04 17:51:04 roberto Exp roberto $
** Garbage Collector
** See Copyright Notice in lua.h
*/
@@ -11,11 +11,8 @@
#include "lobject.h"
void luaC_checkGC (void);
TObject* luaC_getref (int ref);
int luaC_ref (TObject *o, int lock);
void luaC_hashcallIM (Hash *l);
void luaC_strcallIM (TaggedString *l);
void luaC_checkGC (lua_State *L);
void luaC_collect (lua_State *L, int all);
#endif

21
linit.c Normal file
View File

@@ -0,0 +1,21 @@
/*
** $Id: linit.c,v 1.2 1999/11/22 13:12:07 roberto Exp roberto $
** Initialization of libraries for lua.c
** See Copyright Notice in lua.h
*/
#define LUA_REENTRANT
#include "lua.h"
#include "lualib.h"
void lua_userinit (lua_State *L) {
lua_beginblock(L);
lua_iolibopen(L);
lua_strlibopen(L);
lua_mathlibopen(L);
lua_dblibopen(L);
lua_endblock(L);
}

879
liolib.c
View File

@@ -1,16 +1,19 @@
/*
** $Id: liolib.c,v 1.20 1998/06/05 22:17:44 roberto Exp roberto $
** $Id: liolib.c,v 1.61 2000/03/30 17:19:48 roberto Exp roberto $
** Standard I/O (and system) library
** See Copyright Notice in lua.h
*/
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define LUA_REENTRANT
#include "lauxlib.h"
#include "lua.h"
#include "luadebug.h"
@@ -20,7 +23,8 @@
#ifndef OLD_ANSI
#include <locale.h>
#else
#define setlocale(a,b) 0
/* no support for locale and for strerror: fake them */
#define setlocale(a,b) ((void)a, strcmp((b),"C")==0?"C":NULL)
#define LC_ALL 0
#define LC_COLLATE 0
#define LC_CTYPE 0
@@ -31,418 +35,615 @@
#endif
#define CLOSEDTAG 2
#define IOTAG 1
#define FIRSTARG 3 /* 1st and 2nd are upvalues */
#define FINPUT "_INPUT"
#define FOUTPUT "_OUTPUT"
#ifdef POPEN
FILE *popen();
int pclose();
/* FILE *popen();
int pclose(); */
#define CLOSEFILE(L, f) ((pclose(f) == -1) ? fclose(f) : 0)
#else
/* no support for popen */
#define popen(x,y) NULL /* that is, popen always fails */
#define pclose(x) (-1)
#define CLOSEFILE(L, f) (fclose(f))
#endif
static int gettag (int i)
{
return lua_getnumber(lua_getparam(i));
#define INFILE 0
#define OUTFILE 1
typedef struct IOCtrl {
FILE *file[2]; /* values of _INPUT and _OUTPUT */
int iotag; /* tag for file handles */
int closedtag; /* tag for closed handles */
} IOCtrl;
static const char *const filenames[] = {"_INPUT", "_OUTPUT", NULL};
static void atribTM (lua_State *L) {
IOCtrl *ctrl = (IOCtrl *)lua_getuserdata(L, lua_getparam(L, 1));
const char *varname = luaL_check_string(L, 2);
lua_Object newvalue = lua_getparam(L, 4);
int inout;
if ((inout = luaL_findstring(varname, filenames)) != -1) {
if (lua_tag(L, newvalue) != ctrl->iotag)
luaL_verror(L, "%.20s value must be a valid file handle",
filenames[inout]);
ctrl->file[inout] = (FILE *)lua_getuserdata(L, newvalue);
}
/* set the actual variable */
lua_pushobject(L, newvalue);
lua_rawsetglobal(L, varname);
}
static void pushresult (int i)
{
static void ctrl_collect (lua_State *L) {
IOCtrl *ctrl = (IOCtrl *)lua_getuserdata(L, lua_getparam(L, 1));
free(ctrl);
}
static void pushresult (lua_State *L, int i) {
if (i)
lua_pushuserdata(NULL);
lua_pushuserdata(L, NULL);
else {
lua_pushnil();
lua_pushstring(strerror(errno));
lua_pushnil(L);
lua_pushstring(L, strerror(errno));
lua_pushnumber(L, errno);
}
}
static int ishandler (lua_Object f)
{
if (lua_isuserdata(f)) {
if (lua_tag(f) == gettag(CLOSEDTAG))
lua_error("cannot access a closed file");
return lua_tag(f) == gettag(IOTAG);
/*
** {======================================================
** FILE Operations
** =======================================================
*/
static FILE *gethandle (lua_State *L, IOCtrl *ctrl, lua_Object f) {
if (lua_isuserdata(L, f)) {
int ftag = lua_tag(L, f);
if (ftag == ctrl->iotag)
return (FILE *)lua_getuserdata(L, f);
else if (ftag == ctrl->closedtag)
lua_error(L, "cannot access a closed file");
/* else go through */
}
else return 0;
}
static FILE *getfile (char *name)
{
lua_Object f = lua_getglobal(name);
if (!ishandler(f))
luaL_verror("global variable `%.50s' is not a file handle", name);
return lua_getuserdata(f);
return NULL;
}
static FILE *getfileparam (char *name, int *arg)
{
lua_Object f = lua_getparam(*arg);
if (ishandler(f)) {
static FILE *getnonullfile (lua_State *L, IOCtrl *ctrl, int arg) {
FILE *f = gethandle(L, ctrl, lua_getparam(L, arg));
luaL_arg_check(L, f, arg, "invalid file handle");
return f;
}
static FILE *getfileparam (lua_State *L, IOCtrl *ctrl, int *arg, int inout) {
FILE *f = gethandle(L, ctrl, lua_getparam(L, *arg));
if (f) {
(*arg)++;
return lua_getuserdata(f);
return f;
}
else
return getfile(name);
return ctrl->file[inout];
}
static void closefile (char *name)
{
FILE *f = getfile(name);
if (f == stdin || f == stdout) return;
if (pclose(f) == -1)
fclose(f);
lua_pushobject(lua_getglobal(name));
lua_settag(gettag(CLOSEDTAG));
static void setfilebyname (lua_State *L, IOCtrl *ctrl, FILE *f,
const char *name) {
lua_pushusertag(L, f, ctrl->iotag);
lua_setglobal(L, name);
}
static void setfile (FILE *f, char *name, int tag)
{
lua_pushusertag(f, tag);
lua_setglobal(name);
static void setfile (lua_State *L, IOCtrl *ctrl, FILE *f, int inout) {
ctrl->file[inout] = f;
lua_pushusertag(L, f, ctrl->iotag);
lua_setglobal(L, filenames[inout]);
}
static void setreturn (FILE *f, char *name)
{
int tag = gettag(IOTAG);
setfile(f, name, tag);
lua_pushusertag(f, tag);
}
static void io_readfrom (void)
{
FILE *current;
lua_Object f = lua_getparam(FIRSTARG);
if (f == LUA_NOOBJECT) {
closefile(FINPUT);
current = stdin;
}
else if (lua_tag(f) == gettag(IOTAG))
current = lua_getuserdata(f);
static void setreturn (lua_State *L, IOCtrl *ctrl, FILE *f, int inout) {
if (f == NULL)
pushresult(L, 0);
else {
char *s = luaL_check_string(FIRSTARG);
current = (*s == '|') ? popen(s+1, "r") : fopen(s, "r");
if (current == NULL) {
pushresult(0);
return;
}
setfile(L, ctrl, f, inout);
lua_pushusertag(L, f, ctrl->iotag);
}
setreturn(current, FINPUT);
}
static void io_writeto (void)
{
FILE *current;
lua_Object f = lua_getparam(FIRSTARG);
if (f == LUA_NOOBJECT) {
closefile(FOUTPUT);
current = stdout;
}
else if (lua_tag(f) == gettag(IOTAG))
current = lua_getuserdata(f);
static int closefile (lua_State *L, IOCtrl *ctrl, FILE *f) {
if (f == stdin || f == stdout)
return 1;
else {
char *s = luaL_check_string(FIRSTARG);
current = (*s == '|') ? popen(s+1,"w") : fopen(s,"w");
if (current == NULL) {
pushresult(0);
return;
}
if (f == ctrl->file[INFILE])
setfile(L, ctrl, stdin, INFILE);
else if (f == ctrl->file[OUTFILE])
setfile(L, ctrl, stdout, OUTFILE);
lua_pushusertag(L, f, ctrl->iotag);
lua_settag(L, ctrl->closedtag);
return (CLOSEFILE(L, f) == 0);
}
setreturn(current, FOUTPUT);
}
static void io_appendto (void)
{
char *s = luaL_check_string(FIRSTARG);
FILE *fp = fopen (s, "a");
if (fp != NULL)
setreturn(fp, FOUTPUT);
else
pushresult(0);
static void io_close (lua_State *L) {
IOCtrl *ctrl = (IOCtrl *)lua_getuserdata(L, lua_getparam(L, 1));
pushresult(L, closefile(L, ctrl, getnonullfile(L, ctrl, 2)));
}
static void io_open (lua_State *L) {
IOCtrl *ctrl = (IOCtrl *)lua_getuserdata(L, lua_getparam(L, 1));
FILE *f = fopen(luaL_check_string(L, 2), luaL_check_string(L, 3));
if (f) lua_pushusertag(L, f, ctrl->iotag);
else pushresult(L, 0);
}
static void io_fromto (lua_State *L, int inout, const char *mode) {
IOCtrl *ctrl = (IOCtrl *)lua_getuserdata(L, lua_getparam(L, 1));
lua_Object f = lua_getparam(L, 2);
FILE *current;
if (f == LUA_NOOBJECT) {
pushresult(L, closefile(L, ctrl, ctrl->file[inout]));
return;
}
else if (lua_tag(L, f) == ctrl->iotag) /* deprecated option */
current = (FILE *)lua_getuserdata(L, f);
else {
const char *s = luaL_check_string(L, 2);
current = (*s == '|') ? popen(s+1, mode) : fopen(s, mode);
}
setreturn(L, ctrl, current, inout);
}
static void io_readfrom (lua_State *L) {
io_fromto(L, INFILE, "r");
}
static void io_writeto (lua_State *L) {
io_fromto(L, OUTFILE, "w");
}
static void io_appendto (lua_State *L) {
IOCtrl *ctrl = (IOCtrl *)lua_getuserdata(L, lua_getparam(L, 1));
FILE *current = fopen(luaL_check_string(L, 2), "a");
setreturn(L, ctrl, current, OUTFILE);
}
/*
** {======================================================
** READ
** =======================================================
*/
#ifdef LUA_COMPAT_READPATTERN
/*
** We cannot lookahead without need, because this can lock stdin.
** This flag signals when we need to read a next char.
*/
#define NEED_OTHER (EOF-1) /* just some flag different from EOF */
static void read_until (FILE *f, int lim) {
int l = 0;
int c;
for (c = getc(f); c != EOF && c != lim; c = getc(f)) {
luaL_addchar(c);
l++;
}
if (l > 0 || c == lim) /* read anything? */
lua_pushlstring(luaL_buffer(), l);
}
static void io_read (void) {
int arg = FIRSTARG;
FILE *f = getfileparam(FINPUT, &arg);
char *p = luaL_opt_string(arg, NULL);
luaL_resetbuffer();
if (p == NULL) /* default: read a line */
read_until(f, '\n');
else if (p[0] == '.' && p[1] == '*' && p[2] == 0) /* p = ".*" */
read_until(f, EOF);
else {
int l = 0; /* number of chars read in buffer */
int inskip = 0; /* to control {skips} */
int c = NEED_OTHER;
while (*p) {
switch (*p) {
case '{':
inskip++;
p++;
continue;
case '}':
if (inskip == 0)
lua_error("unbalanced braces in read pattern");
inskip--;
p++;
continue;
default: {
char *ep; /* get what is next */
int m; /* match result */
if (c == NEED_OTHER) c = getc(f);
if (c == EOF) {
luaI_singlematch(0, p, &ep); /* to set "ep" */
m = 0;
}
else {
m = luaI_singlematch(c, p, &ep);
if (m) {
if (inskip == 0) {
luaL_addchar(c);
l++;
}
c = NEED_OTHER;
static int read_pattern (lua_State *L, FILE *f, const char *p) {
int inskip = 0; /* {skip} level */
int c = NEED_OTHER;
while (*p != '\0') {
switch (*p) {
case '{':
inskip++;
p++;
continue;
case '}':
if (!inskip) lua_error(L, "unbalanced braces in read pattern");
inskip--;
p++;
continue;
default: {
const char *ep = luaI_classend(L, p); /* get what is next */
int m; /* match result */
if (c == NEED_OTHER) c = getc(f);
m = (c==EOF) ? 0 : luaI_singlematch(c, p, ep);
if (m) {
if (!inskip) luaL_addchar(L, c);
c = NEED_OTHER;
}
switch (*ep) {
case '+': /* repetition (1 or more) */
if (!m) goto break_while; /* pattern fails? */
/* else go through */
case '*': /* repetition (0 or more) */
while (m) { /* reads the same item until it fails */
c = getc(f);
m = (c==EOF) ? 0 : luaI_singlematch(c, p, ep);
if (m && !inskip) luaL_addchar(L, c);
}
}
switch (*ep) {
case '*': /* repetition */
if (!m) p = ep+1; /* else stay in (repeat) the same item */
continue;
case '?': /* optional */
p = ep+1; /* continues reading the pattern */
continue;
default:
if (m) p = ep; /* continues reading the pattern */
else
goto break_while; /* pattern fails */
}
/* go through to continue reading the pattern */
case '?': /* optional */
p = ep+1; /* continues reading the pattern */
continue;
default:
if (!m) goto break_while; /* pattern fails? */
p = ep; /* else continues reading the pattern */
}
}
} break_while:
if (c >= 0) /* not EOF nor NEED_OTHER? */
ungetc(c, f);
if (l > 0 || *p == 0) /* read something or did not fail? */
lua_pushlstring(luaL_buffer(), l);
}
} break_while:
if (c != NEED_OTHER) ungetc(c, f);
return (*p == '\0');
}
#else
#define read_pattern(L, f, p) (lua_error(L, "read patterns are deprecated"), 0)
#endif
static int read_number (lua_State *L, FILE *f) {
double d;
if (fscanf(f, "%lf", &d) == 1) {
lua_pushnumber(L, d);
return 1;
}
else return 0; /* read fails */
}
static void io_write (void)
{
int arg = FIRSTARG;
FILE *f = getfileparam(FOUTPUT, &arg);
int status = 1;
char *s;
long l;
while ((s = luaL_opt_lstr(arg++, NULL, &l)) != NULL)
status = status && (fwrite(s, 1, l, f) == l);
pushresult(status);
}
static void io_execute (void)
{
lua_pushnumber(system(luaL_check_string(1)));
}
static void io_remove (void)
{
pushresult(remove(luaL_check_string(1)) == 0);
}
static void io_rename (void)
{
pushresult(rename(luaL_check_string(1),
luaL_check_string(2)) == 0);
}
static void io_tmpname (void)
{
lua_pushstring(tmpnam(NULL));
}
static void io_getenv (void)
{
lua_pushstring(getenv(luaL_check_string(1))); /* if NULL push nil */
}
static void io_clock (void) {
lua_pushnumber(((double)clock())/CLOCKS_PER_SEC);
}
static void io_date (void)
{
time_t t;
struct tm *tm;
char *s = luaL_opt_string(1, "%c");
char b[BUFSIZ];
time(&t); tm = localtime(&t);
if (strftime(b,sizeof(b),s,tm))
lua_pushstring(b);
else
lua_error("invalid `date' format");
}
static void setloc (void)
{
static int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY, LC_NUMERIC,
LC_TIME};
static char *catnames[] = {"all", "collate", "ctype", "monetary",
"numeric", "time", NULL};
int op = luaL_findstring(luaL_opt_string(2, "all"), catnames);
luaL_arg_check(op != -1, 2, "invalid option");
lua_pushstring(setlocale(cat[op], luaL_check_string(1)));
}
static void io_exit (void)
{
lua_Object o = lua_getparam(1);
exit(lua_isnumber(o) ? (int)lua_getnumber(o) : 1);
}
static void io_debug (void)
{
while (1) {
char buffer[250];
fprintf(stderr, "lua_debug> ");
if (fgets(buffer, sizeof(buffer), stdin) == 0) return;
if (strcmp(buffer, "cont\n") == 0) return;
lua_dostring(buffer);
static void read_word (lua_State *L, FILE *f) {
int c;
do { c = fgetc(f); } while (isspace(c)); /* skip spaces */
while (c != EOF && !isspace(c)) {
luaL_addchar(L, c);
c = fgetc(f);
}
ungetc(c, f);
}
static void lua_printstack (FILE *f)
{
int level = 1; /* skip level 0 (it's this function) */
lua_Object func;
while ((func = lua_stackedfunction(level++)) != LUA_NOOBJECT) {
char *name;
int currentline;
char *filename;
int linedefined;
lua_funcinfo(func, &filename, &linedefined);
fprintf(f, (level==2) ? "Active Stack:\n\t" : "\t");
switch (*lua_getobjname(func, &name)) {
case 'g':
fprintf(f, "function %s", name);
break;
case 't':
fprintf(f, "`%s' tag method", name);
break;
default: {
if (linedefined == 0)
fprintf(f, "main of %s", filename);
else if (linedefined < 0)
fprintf(f, "%s", filename);
else
fprintf(f, "function (%s:%d)", filename, linedefined);
filename = NULL;
#define HUNK_LINE 256
#define HUNK_FILE BUFSIZ
static int read_line (lua_State *L, FILE *f) {
int n;
char *b;
do {
b = luaL_openspace(L, HUNK_LINE);
if (!fgets(b, HUNK_LINE, f)) return 0; /* read fails */
n = strlen(b);
luaL_addsize(L, n);
} while (b[n-1] != '\n');
luaL_addsize(L, -1); /* remove '\n' */
return 1;
}
static void read_file (lua_State *L, FILE *f) {
int n;
do {
char *b = luaL_openspace(L, HUNK_FILE);
n = fread(b, sizeof(char), HUNK_FILE, f);
luaL_addsize(L, n);
} while (n==HUNK_FILE);
}
static int read_chars (lua_State *L, FILE *f, int n) {
char *b = luaL_openspace(L, n);
int n1 = fread(b, sizeof(char), n, f);
luaL_addsize(L, n1);
return (n == n1);
}
static void io_read (lua_State *L) {
IOCtrl *ctrl = (IOCtrl *)lua_getuserdata(L, lua_getparam(L, 1));
int arg = 2;
FILE *f = getfileparam(L, ctrl, &arg, INFILE);
lua_Object op = lua_getparam(L, arg);
do { /* repeat for each part */
long l;
int success;
luaL_resetbuffer(L);
if (lua_isnumber(L, op))
success = read_chars(L, f, (int)lua_getnumber(L, op));
else {
const char *p = luaL_opt_string(L, arg, "*l");
if (p[0] != '*')
success = read_pattern(L, f, p); /* deprecated! */
else {
switch (p[1]) {
case 'n': /* number */
if (!read_number(L, f)) return; /* read fails */
continue; /* number is already pushed; avoid the "pushstring" */
case 'l': /* line */
success = read_line(L, f);
break;
case 'a': /* file */
read_file(L, f);
success = 1; /* always success */
break;
case 'w': /* word */
read_word(L, f);
success = 0; /* must read something to succeed */
break;
default:
luaL_argerror(L, arg, "invalid format");
success = 0; /* to avoid warnings */
}
}
}
if ((currentline = lua_currentline(func)) > 0)
fprintf(f, " at line %d", currentline);
if (filename)
fprintf(f, " [in file %s]", filename);
fprintf(f, "\n");
l = luaL_getsize(L);
if (!success && l==0) return; /* read fails */
lua_pushlstring(L, luaL_buffer(L), l);
} while ((op = lua_getparam(L, ++arg)) != LUA_NOOBJECT);
}
/* }====================================================== */
static void io_write (lua_State *L) {
IOCtrl *ctrl = (IOCtrl *)lua_getuserdata(L, lua_getparam(L, 1));
int arg = 2;
FILE *f = getfileparam(L, ctrl, &arg, OUTFILE);
int status = 1;
lua_Object o;
while ((o = lua_getparam(L, arg)) != LUA_NOOBJECT) {
if (lua_type(L, o)[2] == 'm') { /* nuMber? */ /* LUA_NUMBER */
/* optimization: could be done exactly as for strings */
status = status && fprintf(f, "%.16g", lua_getnumber(L, o)) > 0;
}
else {
long l;
const char *s = luaL_check_lstr(L, arg, &l);
status = status && ((long)fwrite(s, sizeof(char), l, f) == l);
}
arg++;
}
pushresult(L, status);
}
static void io_seek (lua_State *L) {
static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
static const char *const modenames[] = {"set", "cur", "end", NULL};
IOCtrl *ctrl = (IOCtrl *)lua_getuserdata(L, lua_getparam(L, 1));
FILE *f = getnonullfile(L, ctrl, 2);
int op = luaL_findstring(luaL_opt_string(L, 3, "cur"), modenames);
long offset = luaL_opt_long(L, 4, 0);
luaL_arg_check(L, op != -1, 3, "invalid mode");
op = fseek(f, offset, mode[op]);
if (op)
pushresult(L, 0); /* error */
else
lua_pushnumber(L, ftell(f));
}
static void io_flush (lua_State *L) {
IOCtrl *ctrl = (IOCtrl *)lua_getuserdata(L, lua_getparam(L, 1));
lua_Object of = lua_getparam(L, 2);
FILE *f = gethandle(L, ctrl, of);
luaL_arg_check(L, f || of == LUA_NOOBJECT, 2, "invalid file handle");
pushresult(L, fflush(f) == 0);
}
/* }====================================================== */
/*
** {======================================================
** Other O.S. Operations
** =======================================================
*/
static void io_execute (lua_State *L) {
lua_pushnumber(L, system(luaL_check_string(L, 1)));
}
static void io_remove (lua_State *L) {
pushresult(L, remove(luaL_check_string(L, 1)) == 0);
}
static void io_rename (lua_State *L) {
pushresult(L, rename(luaL_check_string(L, 1),
luaL_check_string(L, 2)) == 0);
}
static void io_tmpname (lua_State *L) {
lua_pushstring(L, tmpnam(NULL));
}
static void io_getenv (lua_State *L) {
lua_pushstring(L, getenv(luaL_check_string(L, 1))); /* if NULL push nil */
}
static void io_clock (lua_State *L) {
lua_pushnumber(L, ((double)clock())/CLOCKS_PER_SEC);
}
static void io_date (lua_State *L) {
char b[256];
const char *s = luaL_opt_string(L, 1, "%c");
struct tm *stm;
time_t t;
time(&t); stm = localtime(&t);
if (strftime(b, sizeof(b), s, stm))
lua_pushstring(L, b);
else
lua_error(L, "invalid `date' format");
}
static void setloc (lua_State *L) {
static const int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY,
LC_NUMERIC, LC_TIME};
static const char *const catnames[] = {"all", "collate", "ctype", "monetary",
"numeric", "time", NULL};
int op = luaL_findstring(luaL_opt_string(L, 2, "all"), catnames);
luaL_arg_check(L, op != -1, 2, "invalid option");
lua_pushstring(L, setlocale(cat[op], luaL_check_string(L, 1)));
}
static void io_exit (lua_State *L) {
exit(luaL_opt_int(L, 1, EXIT_SUCCESS));
}
/* }====================================================== */
static void io_debug (lua_State *L) {
for (;;) {
char buffer[250];
fprintf(stderr, "lua_debug> ");
if (fgets(buffer, sizeof(buffer), stdin) == 0 ||
strcmp(buffer, "cont\n") == 0)
return;
lua_dostring(L, buffer);
}
}
static void errorfb (void)
{
fprintf(stderr, "lua: %s\n", lua_getstring(lua_getparam(1)));
lua_printstack(stderr);
#define MESSAGESIZE 150
#define MAXMESSAGE (MESSAGESIZE*10)
static void errorfb (lua_State *L) {
char buff[MAXMESSAGE];
int level = 1; /* skip level 0 (it's this function) */
lua_Debug ar;
lua_Object alertfunc = lua_rawgetglobal(L, "_ALERT");
sprintf(buff, "error: %.200s\n", lua_getstring(L, lua_getparam(L, 1)));
while (lua_getstack(L, level++, &ar)) {
char buffchunk[60];
lua_getinfo(L, "Snl", &ar);
luaL_chunkid(buffchunk, ar.source, sizeof(buffchunk));
if (level == 2) strcat(buff, "stack traceback:\n");
strcat(buff, " ");
if (strlen(buff) > MAXMESSAGE-MESSAGESIZE) {
strcat(buff, "...\n");
break; /* buffer is full */
}
switch (*ar.namewhat) {
case 'g': case 'l': /* global, local */
sprintf(buff+strlen(buff), "function `%.50s'", ar.name);
break;
case 'f': /* field */
sprintf(buff+strlen(buff), "method `%.50s'", ar.name);
break;
case 't': /* tag method */
sprintf(buff+strlen(buff), "`%.50s' tag method", ar.name);
break;
default: {
if (*ar.what == 'm') /* main? */
sprintf(buff+strlen(buff), "main of %.70s", buffchunk);
else if (*ar.what == 'C') /* C function? */
sprintf(buff+strlen(buff), "%.70s", buffchunk);
else
sprintf(buff+strlen(buff), "function <%d:%.70s>",
ar.linedefined, buffchunk);
ar.source = NULL;
}
}
if (ar.currentline > 0)
sprintf(buff+strlen(buff), " at line %d", ar.currentline);
if (ar.source)
sprintf(buff+strlen(buff), " [%.70s]", buffchunk);
strcat(buff, "\n");
}
if (lua_isfunction(L, alertfunc)) { /* avoid loop if _ALERT is not defined */
lua_pushstring(L, buff);
lua_callfunction(L, alertfunc);
}
}
static struct luaL_reg iolib[] = {
{"setlocale", setloc},
{"execute", io_execute},
{"remove", io_remove},
{"rename", io_rename},
{"tmpname", io_tmpname},
{"getenv", io_getenv},
{"date", io_date},
{"clock", io_clock},
{"exit", io_exit},
{"debug", io_debug},
{"print_stack", errorfb}
static const struct luaL_reg iolib[] = {
{"_ERRORMESSAGE", errorfb},
{"clock", io_clock},
{"date", io_date},
{"debug", io_debug},
{"execute", io_execute},
{"exit", io_exit},
{"getenv", io_getenv},
{"remove", io_remove},
{"rename", io_rename},
{"setlocale", setloc},
{"tmpname", io_tmpname}
};
static struct luaL_reg iolibtag[] = {
{"readfrom", io_readfrom},
{"writeto", io_writeto},
{"appendto", io_appendto},
{"read", io_read},
{"write", io_write}
static const struct luaL_reg iolibtag[] = {
{"appendto", io_appendto},
{"closefile", io_close},
{"flush", io_flush},
{"openfile", io_open},
{"read", io_read},
{"readfrom", io_readfrom},
{"seek", io_seek},
{"write", io_write},
{"writeto", io_writeto}
};
static void openwithtags (void)
{
int iotag = lua_newtag();
int closedtag = lua_newtag();
int i;
static void openwithcontrol (lua_State *L) {
IOCtrl *ctrl = (IOCtrl *)malloc(sizeof(IOCtrl));
unsigned int i;
int ctrltag = lua_newtag(L);
ctrl->iotag = lua_newtag(L);
ctrl->closedtag = lua_newtag(L);
for (i=0; i<sizeof(iolibtag)/sizeof(iolibtag[0]); i++) {
/* put both tags as upvalues for these functions */
lua_pushnumber(iotag);
lua_pushnumber(closedtag);
lua_pushcclosure(iolibtag[i].func, 2);
lua_setglobal(iolibtag[i].name);
/* put `ctrl' as upvalue for these functions */
lua_pushusertag(L, ctrl, ctrltag);
lua_pushcclosure(L, iolibtag[i].func, 1);
lua_setglobal(L, iolibtag[i].name);
}
setfile(stdin, FINPUT, iotag);
setfile(stdout, FOUTPUT, iotag);
setfile(stdin, "_STDIN", iotag);
setfile(stdout, "_STDOUT", iotag);
setfile(stderr, "_STDERR", iotag);
/* predefined file handles */
ctrl->file[INFILE] = stdin;
setfile(L, ctrl, stdin, INFILE);
ctrl->file[OUTFILE] = stdout;
setfile(L, ctrl, stdout, OUTFILE);
setfilebyname(L, ctrl, stdin, "_STDIN");
setfilebyname(L, ctrl, stdout, "_STDOUT");
setfilebyname(L, ctrl, stderr, "_STDERR");
/* change file when assigned */
lua_pushusertag(L, ctrl, ctrltag);
lua_pushcclosure(L, atribTM, 1);
lua_settagmethod(L, ctrl->iotag, "setglobal");
/* delete `ctrl' when collected */
lua_pushusertag(L, ctrl, ctrltag);
lua_pushcclosure(L, ctrl_collect, 1);
lua_settagmethod(L, ctrltag, "gc");
}
void lua_iolibopen (void)
{
luaL_openlib(iolib, (sizeof(iolib)/sizeof(iolib[0])));
openwithtags();
lua_pushcfunction(errorfb);
lua_seterrormethod();
void lua_iolibopen (lua_State *L) {
luaL_openl(L, iolib);
openwithcontrol(L);
}

405
llex.c
View File

@@ -1,13 +1,16 @@
/*
** $Id: llex.c,v 1.22 1998/06/19 18:47:06 roberto Exp roberto $
** Lexical Analizer
** $Id: llex.c,v 1.56 2000/04/07 13:11:49 roberto Exp roberto $
** Lexical Analyzer
** See Copyright Notice in lua.h
*/
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#define LUA_REENTRANT
#include "lauxlib.h"
#include "llex.h"
#include "lmem.h"
@@ -20,82 +23,88 @@
int lua_debug=0;
#define next(LS) (LS->current = zgetc(LS->z))
#define next(LS) (LS->current = zgetc(LS->lex_z))
#define save(L, c) luaL_addchar(L, c)
#define save_and_next(L, LS) (save(L, LS->current), next(LS))
#define save(c) luaL_addchar(c)
#define save_and_next(LS) (save(LS->current), next(LS))
/* ORDER RESERVED */
static const char *const token2string [] = {
"and", "break", "do", "else", "elseif", "end", "for",
"function", "if", "local", "nil", "not", "or", "repeat", "return", "then",
"until", "while", "", "..", "...", "==", ">=", "<=", "~=", "", "", "<eof>"};
char *reserved [] = {"and", "do", "else", "elseif", "end", "function",
"if", "local", "nil", "not", "or", "repeat", "return", "then",
"until", "while"};
void luaX_init (void)
{
void luaX_init (lua_State *L) {
int i;
for (i=0; i<(sizeof(reserved)/sizeof(reserved[0])); i++) {
TaggedString *ts = luaS_new(reserved[i]);
ts->head.marked = FIRST_RESERVED+i; /* reserved word (always > 255) */
for (i=0; i<NUM_RESERVED; i++) {
TString *ts = luaS_new(L, token2string[i]);
ts->marked = (unsigned char)(RESERVEDMARK+i); /* reserved word */
}
}
void luaX_syntaxerror (LexState *ls, char *s, char *token) {
if (token[0] == 0)
token = "<eof>";
luaL_verror("%.100s;\n last token read: `%.50s' at line %d in chunk `%.50s'",
s, token, ls->linenumber, zname(ls->lex_z));
#define MAXSRC 80
void luaX_syntaxerror (LexState *ls, const char *s, const char *token) {
char buff[MAXSRC];
luaL_chunkid(buff, zname(ls->z), sizeof(buff));
luaL_verror(ls->L, "%.100s;\n last token read: `%.50s' at line %d in %.80s",
s, token, ls->linenumber, buff);
}
void luaX_error (LexState *ls, char *s) {
save(0);
luaX_syntaxerror(ls, s, luaL_buffer());
}
void luaX_token2str (LexState *ls, int token, char *s) {
if (token < 255) {
s[0] = token;
s[1] = 0;
void luaX_error (LexState *ls, const char *s, int token) {
char buff[TOKEN_LEN];
luaX_token2str(token, buff);
if (buff[0] == '\0') {
save(ls->L, '\0');
luaX_syntaxerror(ls, s, luaL_buffer(ls->L));
}
else
strcpy(s, reserved[token-FIRST_RESERVED]);
luaX_syntaxerror(ls, s, buff);
}
void luaX_token2str (int token, char *s) {
if (token < 256) {
s[0] = (char)token;
s[1] = '\0';
}
else
strcpy(s, token2string[token-FIRST_RESERVED]);
}
static void luaX_invalidchar (LexState *ls, int c) {
char buff[10];
sprintf(buff, "0x%X", c);
char buff[8];
sprintf(buff, "0x%02X", c);
luaX_syntaxerror(ls, "invalid control char", buff);
}
static void firstline (LexState *LS)
{
int c = zgetc(LS->lex_z);
int c = zgetc(LS->z);
if (c == '#')
while ((c=zgetc(LS->lex_z)) != '\n' && c != EOZ) /* skip first line */;
zungetc(LS->lex_z);
while ((c=zgetc(LS->z)) != '\n' && c != EOZ) /* skip first line */;
zungetc(LS->z);
}
void luaX_setinput (LexState *LS, ZIO *z)
{
void luaX_setinput (lua_State *L, LexState *LS, ZIO *z) {
LS->L = L;
LS->current = '\n';
LS->linenumber = 0;
LS->iflevel = 0;
LS->ifstate[0].skip = 0;
LS->ifstate[0].elsepart = 1; /* to avoid a free $else */
LS->lex_z = z;
LS->z = z;
LS->fs = NULL;
firstline(LS);
luaL_resetbuffer();
luaL_resetbuffer(L);
}
@@ -106,22 +115,18 @@ void luaX_setinput (LexState *LS, ZIO *z)
** =======================================================
*/
#define PRAGMASIZE 20
static void skipspace (LexState *LS)
{
static void skipspace (LexState *LS) {
while (LS->current == ' ' || LS->current == '\t' || LS->current == '\r')
next(LS);
}
static int checkcond (LexState *LS, char *buff)
{
static char *opts[] = {"nil", "1", NULL};
static int checkcond (lua_State *L, LexState *LS, const char *buff) {
static const char *const opts[] = {"nil", "1", NULL};
int i = luaL_findstring(buff, opts);
if (i >= 0) return i;
else if (isalpha((unsigned char)buff[0]) || buff[0] == '_')
return luaS_globaldefined(buff);
return luaS_globaldefined(L, buff);
else {
luaX_syntaxerror(LS, "invalid $if condition", buff);
return 0; /* to avoid warnings */
@@ -129,8 +134,7 @@ static int checkcond (LexState *LS, char *buff)
}
static void readname (LexState *LS, char *buff)
{
static void readname (LexState *LS, char *buff) {
int i = 0;
skipspace(LS);
while (isalnum(LS->current) || LS->current == '_') {
@@ -138,31 +142,29 @@ static void readname (LexState *LS, char *buff)
buff[PRAGMASIZE] = 0;
luaX_syntaxerror(LS, "pragma too long", buff);
}
buff[i++] = LS->current;
buff[i++] = (char)LS->current;
next(LS);
}
buff[i] = 0;
}
static void inclinenumber (LexState *LS);
static void inclinenumber (lua_State *L, LexState *LS);
static void ifskip (LexState *LS)
{
static void ifskip (lua_State *L, LexState *LS) {
while (LS->ifstate[LS->iflevel].skip) {
if (LS->current == '\n')
inclinenumber(LS);
inclinenumber(L, LS);
else if (LS->current == EOZ)
luaX_error(LS, "input ends inside a $if");
luaX_error(LS, "input ends inside a $if", TK_EOS);
else next(LS);
}
}
static void inclinenumber (LexState *LS)
{
static char *pragmas [] =
static void inclinenumber (lua_State *L, LexState *LS) {
static const char *const pragmas [] =
{"debug", "nodebug", "endinput", "end", "ifnot", "if", "else", NULL};
next(LS); /* skip '\n' */
++LS->linenumber;
@@ -174,10 +176,10 @@ static void inclinenumber (LexState *LS)
readname(LS, buff);
switch (luaL_findstring(buff, pragmas)) {
case 0: /* debug */
if (!skip) lua_debug = 1;
if (!skip) L->debug = 1;
break;
case 1: /* nodebug */
if (!skip) lua_debug = 0;
if (!skip) L->debug = 0;
break;
case 2: /* endinput */
if (!skip) {
@@ -198,7 +200,7 @@ static void inclinenumber (LexState *LS)
readname(LS, buff);
LS->iflevel++;
LS->ifstate[LS->iflevel].elsepart = 0;
LS->ifstate[LS->iflevel].condition = checkcond(LS, buff) ? !ifnot : ifnot;
LS->ifstate[LS->iflevel].condition = checkcond(L, LS, buff) ? !ifnot : ifnot;
LS->ifstate[LS->iflevel].skip = skip || !LS->ifstate[LS->iflevel].condition;
break;
case 6: /* else */
@@ -213,249 +215,230 @@ static void inclinenumber (LexState *LS)
}
skipspace(LS);
if (LS->current == '\n') /* pragma must end with a '\n' ... */
inclinenumber(LS);
inclinenumber(L, LS);
else if (LS->current != EOZ) /* or eof */
luaX_syntaxerror(LS, "invalid pragma format", buff);
ifskip(LS);
ifskip(L, LS);
}
}
/*
** =======================================================
** LEXICAL ANALIZER
** LEXICAL ANALYZER
** =======================================================
*/
static int read_long_string (LexState *LS)
{
static void read_long_string (lua_State *L, LexState *LS) {
int cont = 0;
while (1) {
for (;;) {
switch (LS->current) {
case EOZ:
luaX_error(LS, "unfinished long string");
return EOS; /* to avoid warnings */
luaX_error(LS, "unfinished long string", TK_STRING);
break; /* to avoid warnings */
case '[':
save_and_next(LS);
save_and_next(L, LS);
if (LS->current == '[') {
cont++;
save_and_next(LS);
save_and_next(L, LS);
}
continue;
case ']':
save_and_next(LS);
save_and_next(L, LS);
if (LS->current == ']') {
if (cont == 0) goto endloop;
cont--;
save_and_next(LS);
save_and_next(L, LS);
}
continue;
case '\n':
save('\n');
inclinenumber(LS);
save(L, '\n');
inclinenumber(L, LS);
continue;
default:
save_and_next(LS);
save_and_next(L, LS);
}
} endloop:
save_and_next(LS); /* pass the second ']' */
LS->seminfo.ts = luaS_newlstr(L->Mbuffbase+2,
L->Mbuffnext-(L->Mbuffbase-L->Mbuffer)-4);
return STRING;
save_and_next(L, LS); /* skip the second ']' */
LS->seminfo.ts = luaS_newlstr(L, L->Mbuffer+(L->Mbuffbase+2),
L->Mbuffnext-L->Mbuffbase-4);
}
static void read_string (lua_State *L, LexState *LS, int del) {
save_and_next(L, LS);
while (LS->current != del) {
switch (LS->current) {
case EOZ: case '\n':
luaX_error(LS, "unfinished string", TK_STRING);
break; /* to avoid warnings */
case '\\':
next(LS); /* do not save the '\' */
switch (LS->current) {
case 'a': save(L, '\a'); next(LS); break;
case 'b': save(L, '\b'); next(LS); break;
case 'f': save(L, '\f'); next(LS); break;
case 'n': save(L, '\n'); next(LS); break;
case 'r': save(L, '\r'); next(LS); break;
case 't': save(L, '\t'); next(LS); break;
case 'v': save(L, '\v'); next(LS); break;
case '\n': save(L, '\n'); inclinenumber(L, LS); break;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9': {
int c = 0;
int i = 0;
do {
c = 10*c + (LS->current-'0');
next(LS);
} while (++i<3 && isdigit(LS->current));
if (c != (unsigned char)c)
luaX_error(LS, "escape sequence too large", TK_STRING);
save(L, c);
break;
}
default: /* handles \\, \", \', and \? */
save(L, LS->current);
next(LS);
}
break;
default:
save_and_next(L, LS);
}
}
save_and_next(L, LS); /* skip delimiter */
LS->seminfo.ts = luaS_newlstr(L, L->Mbuffer+(L->Mbuffbase+1),
L->Mbuffnext-L->Mbuffbase-2);
}
int luaX_lex (LexState *LS) {
double a;
luaL_resetbuffer();
while (1) {
lua_State *L = LS->L;
for (;;) {
switch (LS->current) {
case ' ': case '\t': case '\r': /* CR: to avoid problems with DOS */
case ' ': case '\t': case '\r': /* `\r' to avoid problems with DOS */
next(LS);
continue;
case '\n':
inclinenumber(LS);
inclinenumber(L, LS);
continue;
case '-':
save_and_next(LS);
next(LS);
if (LS->current != '-') return '-';
do { next(LS); } while (LS->current != '\n' && LS->current != EOZ);
luaL_resetbuffer();
continue;
case '[':
save_and_next(LS);
luaL_resetbuffer(L);
save_and_next(L, LS);
if (LS->current != '[') return '[';
else {
save_and_next(LS); /* pass the second '[' */
return read_long_string(LS);
save_and_next(L, LS); /* pass the second '[' */
read_long_string(L, LS);
return TK_STRING;
}
case '=':
save_and_next(LS);
next(LS);
if (LS->current != '=') return '=';
else { save_and_next(LS); return EQ; }
else { next(LS); return TK_EQ; }
case '<':
save_and_next(LS);
next(LS);
if (LS->current != '=') return '<';
else { save_and_next(LS); return LE; }
else { next(LS); return TK_LE; }
case '>':
save_and_next(LS);
next(LS);
if (LS->current != '=') return '>';
else { save_and_next(LS); return GE; }
else { next(LS); return TK_GE; }
case '~':
save_and_next(LS);
next(LS);
if (LS->current != '=') return '~';
else { save_and_next(LS); return NE; }
else { next(LS); return TK_NE; }
case '"':
case '\'': {
int del = LS->current;
save_and_next(LS);
while (LS->current != del) {
switch (LS->current) {
case EOZ:
case '\n':
luaX_error(LS, "unfinished string");
return EOS; /* to avoid warnings */
case '\\':
next(LS); /* do not save the '\' */
switch (LS->current) {
case 'a': save('\a'); next(LS); break;
case 'b': save('\b'); next(LS); break;
case 'f': save('\f'); next(LS); break;
case 'n': save('\n'); next(LS); break;
case 'r': save('\r'); next(LS); break;
case 't': save('\t'); next(LS); break;
case 'v': save('\v'); next(LS); break;
case '\n': save('\n'); inclinenumber(LS); break;
default : {
if (isdigit(LS->current)) {
int c = 0;
int i = 0;
do {
c = 10*c + (LS->current-'0');
next(LS);
} while (++i<3 && isdigit(LS->current));
if (c >= 256)
luaX_error(LS, "escape sequence too large");
save(c);
}
else { /* handles \, ", ', and ? */
save(LS->current);
next(LS);
}
break;
}
}
break;
default:
save_and_next(LS);
}
}
save_and_next(LS); /* skip delimiter */
LS->seminfo.ts = luaS_newlstr(L->Mbuffbase+1,
L->Mbuffnext-(L->Mbuffbase-L->Mbuffer)-2);
return STRING;
}
case '\'':
luaL_resetbuffer(L);
read_string(L, LS, LS->current);
return TK_STRING;
case '.':
save_and_next(LS);
if (LS->current == '.')
{
save_and_next(LS);
if (LS->current == '.')
{
save_and_next(LS);
return DOTS; /* ... */
luaL_resetbuffer(L);
save_and_next(L, LS);
if (LS->current == '.') {
next(LS);
if (LS->current == '.') {
next(LS);
return TK_DOTS; /* ... */
}
else return CONC; /* .. */
else return TK_CONCAT; /* .. */
}
else if (!isdigit(LS->current)) return '.';
/* LS->current is a digit: goes through to number */
a=0.0;
goto fraction;
else goto fraction; /* LS->current is a digit */
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
a=0.0;
luaL_resetbuffer(L);
do {
a = 10.0*a + (LS->current-'0');
save_and_next(LS);
save_and_next(L, LS);
} while (isdigit(LS->current));
if (LS->current == '.') {
save_and_next(LS);
save_and_next(L, LS);
if (LS->current == '.') {
save('.');
luaX_error(LS,
"ambiguous syntax (decimal point x string concatenation)");
save(L, '.');
luaX_error(LS, "ambiguous syntax"
" (decimal point x string concatenation)", TK_NUMBER);
}
}
fraction:
{ double da=0.1;
while (isdigit(LS->current))
{
a += (LS->current-'0')*da;
da /= 10.0;
save_and_next(LS);
}
if (toupper(LS->current) == 'E') {
int e = 0;
int neg;
double ea;
save_and_next(LS);
neg = (LS->current=='-');
if (LS->current == '+' || LS->current == '-') save_and_next(LS);
if (!isdigit(LS->current))
luaX_error(LS, "invalid numeral format");
do {
e = 10*e + (LS->current-'0');
save_and_next(LS);
} while (isdigit(LS->current));
for (ea=neg?0.1:10.0; e>0; e>>=1)
{
if (e & 1) a *= ea;
ea *= ea;
}
}
LS->seminfo.r = a;
return NUMBER;
fraction: /* LUA_NUMBER */
while (isdigit(LS->current))
save_and_next(L, LS);
if (LS->current == 'e' || LS->current == 'E') {
save_and_next(L, LS); /* read 'E' */
if (LS->current == '+' || LS->current == '-')
save_and_next(L, LS); /* optional exponent sign */
while (isdigit(LS->current))
save_and_next(L, LS);
}
save(L, '\0');
if (!luaO_str2d(L->Mbuffer+L->Mbuffbase, &LS->seminfo.r))
luaX_error(LS, "malformed number", TK_NUMBER);
return TK_NUMBER;
case EOZ:
if (LS->iflevel > 0)
luaX_error(LS, "input ends inside a $if");
return EOS;
luaX_error(LS, "input ends inside a $if", TK_EOS);
return TK_EOS;
case '_': goto tname;
default:
if (LS->current != '_' && !isalpha(LS->current)) {
if (!isalpha(LS->current)) {
int c = LS->current;
if (iscntrl(c))
luaX_invalidchar(LS, c);
save_and_next(LS);
next(LS);
return c;
}
else { /* identifier or reserved word */
TaggedString *ts;
tname: { /* identifier or reserved word */
TString *ts;
luaL_resetbuffer(L);
do {
save_and_next(LS);
save_and_next(L, LS);
} while (isalnum(LS->current) || LS->current == '_');
save(0);
ts = luaS_new(L->Mbuffbase);
if (ts->head.marked >= 'A')
return ts->head.marked; /* reserved word */
save(L, '\0');
ts = luaS_new(L, L->Mbuffer+L->Mbuffbase);
if (ts->marked >= RESERVEDMARK) /* reserved word? */
return ts->marked-RESERVEDMARK+FIRST_RESERVED;
LS->seminfo.ts = ts;
return NAME;
return TK_NAME;
}
}
}

51
llex.h
View File

@@ -1,6 +1,6 @@
/*
** $Id: llex.h,v 1.8 1998/05/27 13:03:40 roberto Exp roberto $
** Lexical Analizer
** $Id: llex.h,v 1.23 2000/04/07 13:11:49 roberto Exp roberto $
** Lexical Analyzer
** See Copyright Notice in lua.h
*/
@@ -11,26 +11,34 @@
#include "lzio.h"
#define FIRST_RESERVED 260
#define FIRST_RESERVED 257
/* maximum length of a reserved word (+1 for terminal 0) */
/* maximum length of a reserved word (+1 for final 0) */
#define TOKEN_LEN 15
/*
* WARNING: if you change the order of this enumeration,
* grep "ORDER RESERVED"
*/
enum RESERVED {
/* terminal symbols denoted by reserved words */
AND = FIRST_RESERVED,
DO, ELSE, ELSEIF, END, FUNCTION, IF, LOCAL, NIL, NOT, OR,
REPEAT, RETURN, THEN, UNTIL, WHILE,
TK_AND = FIRST_RESERVED, TK_BREAK,
TK_DO, TK_ELSE, TK_ELSEIF, TK_END, TK_FOR, TK_FUNCTION, TK_IF, TK_LOCAL,
TK_NIL, TK_NOT, TK_OR, TK_REPEAT, TK_RETURN, TK_THEN, TK_UNTIL, TK_WHILE,
/* other terminal symbols */
NAME, CONC, DOTS, EQ, GE, LE, NE, NUMBER, STRING, EOS};
TK_NAME, TK_CONCAT, TK_DOTS, TK_EQ, TK_GE, TK_LE, TK_NE, TK_NUMBER,
TK_STRING, TK_EOS
};
/* number of reserved words */
#define NUM_RESERVED ((int)(TK_WHILE-FIRST_RESERVED+1))
#define MAX_IFS 5
/* "ifstate" keeps the state of each nested $if the lexical is dealing with. */
/* `ifState' keeps the state of each nested $if the lexical is dealing with. */
struct ifState {
int elsepart; /* true if its in the $else part */
int elsepart; /* true if it's in the $else part */
int condition; /* true if $if condition is true */
int skip; /* true if part must be skipped */
};
@@ -39,24 +47,25 @@ struct ifState {
typedef struct LexState {
int current; /* look ahead character */
int token; /* look ahead token */
struct FuncState *fs; /* 'FuncState' is private for the parser */
struct FuncState *fs; /* `FuncState' is private to the parser */
struct lua_State *L;
union {
real r;
TaggedString *ts;
Number r;
TString *ts;
} seminfo; /* semantics information */
struct zio *lex_z; /* input stream */
struct zio *z; /* input stream */
int linenumber; /* input line counter */
int iflevel; /* level of nested $if's (for lexical analysis) */
struct ifState ifstate[MAX_IFS];
} LexState;
void luaX_init (void);
void luaX_setinput (LexState *LS, ZIO *z);
void luaX_init (lua_State *L);
void luaX_setinput (lua_State *L, LexState *LS, ZIO *z);
int luaX_lex (LexState *LS);
void luaX_syntaxerror (LexState *ls, char *s, char *token);
void luaX_error (LexState *ls, char *s);
void luaX_token2str (LexState *ls, int token, char *s);
void luaX_syntaxerror (LexState *ls, const char *s, const char *token);
void luaX_error (LexState *ls, const char *s, int token);
void luaX_token2str (int token, char *s);
#endif

194
llimits.h Normal file
View File

@@ -0,0 +1,194 @@
/*
** $Id: llimits.h,v 1.4 2000/03/31 16:28:45 roberto Exp roberto $
** Limits, basic types, and some other "instalation-dependent" definitions
** See Copyright Notice in lua.h
*/
#ifndef llimits_h
#define llimits_h
#include <limits.h>
/*
** Define the type `number' of Lua
** GREP LUA_NUMBER to change that
*/
#ifndef LUA_NUM_TYPE
#define LUA_NUM_TYPE double
#endif
typedef LUA_NUM_TYPE Number;
#define MAX_INT (INT_MAX-2) /* maximum value of an int (-2 for safety) */
/*
** conversion of pointer to int (for hashing only)
** (the shift removes bits that are usually 0 because of alignment)
*/
#define IntPoint(L, p) (((unsigned long)(p)) >> 3)
/*
** number of `blocks' for garbage collection: each reference to other
** objects count 1, and each 32 bytes of `raw' memory count 1; we add
** 2 to the total as a minimum (and also to count the overhead of malloc)
*/
#define numblocks(L, o,b) ((o)+((b)>>5)+2)
#define MINPOWER2 4 /* minimum size for "growing" vectors */
#ifndef DEFAULT_STACK_SIZE
#define DEFAULT_STACK_SIZE 1024
#endif
/*
** type for virtual-machine instructions
** must be an unsigned with 4 bytes (see details in lopcodes.h)
** For a very small machine, you may change that to 2 bytes (and adjust
** the following limits accordingly)
*/
typedef unsigned long Instruction;
/*
** limits for opcode arguments.
** For an instruction with 2 bytes, size is 16, and size_b can be 5
*/
#define SIZE_INSTRUCTION 32
#define SIZE_OP 6
#define SIZE_B 9
#define SIZE_U (SIZE_INSTRUCTION-SIZE_OP)
#define POS_U SIZE_OP
#define POS_B SIZE_OP
#define SIZE_A (SIZE_INSTRUCTION-(SIZE_OP+SIZE_B))
#define POS_A (SIZE_OP+SIZE_B)
#define MAXARG_U ((1<<SIZE_U)-1)
#define MAXARG_S (MAXARG_U>>1) /* `S' is signed */
#define MAXARG_A ((1<<SIZE_A)-1)
#define MAXARG_B ((1<<SIZE_B)-1)
/*
** we use int to manipulate most arguments, so they must fit
*/
#if MAXARG_U > MAX_INT
#undef MAXARG_U
#define MAXARG_U MAX_INT
#endif
#if MAXARG_S > MAX_INT
#undef MAXARG_S
#define MAXARG_S MAX_INT
#endif
#if MAXARG_A > MAX_INT
#undef MAXARG_A
#define MAXARG_A MAX_INT
#endif
#if MAXARG_B > MAX_INT
#undef MAXARG_B
#define MAXARG_B MAX_INT
#endif
/* maximum stack size in a function */
#define MAXSTACK MAXARG_B
/* maximum number of local variables */
#ifndef MAXLOCALS
#define MAXLOCALS 200 /* arbitrary limit (<MAXSTACK) */
#endif
#if MAXLOCALS>=MAXSTACK
#undef MAXLOCALS
#define MAXLOCALS (MAXSTACK-1)
#endif
/* maximum number of upvalues */
#ifndef MAXUPVALUES
#define MAXUPVALUES 32 /* arbitrary limit (<=MAXARG_B) */
#endif
#if MAXUPVALUES>MAXARG_B
#undef MAXUPVALUES
#define MAXUPVALUES MAXARG_B
#endif
/* special code for multiple returns */
#define MULT_RET 255 /* (<=MAXARG_B) */
#if MULT_RET>MAXARG_B
#undef MULT_RET
#define MULT_RET MAXARG_B
#endif
/* maximum number of variables in the left side of an assignment */
#ifndef MAXVARSLH
#define MAXVARSLH 100 /* arbitrary limit (<MULT_RET) */
#endif
#if MAXVARSLH>=MULT_RET
#undef MAXVARSLH
#define MAXVARSLH (MULT_RET-1)
#endif
/* maximum number of parameters in a function */
#ifndef MAXPARAMS
#define MAXPARAMS 100 /* arbitrary limit (<MAXLOCALS) */
#endif
#if MAXPARAMS>=MAXLOCALS
#undef MAXPARAMS
#define MAXPARAMS (MAXLOCALS-1)
#endif
/* number of list items to accumulate before a SETLIST instruction */
#define LFIELDS_PER_FLUSH 64
#if LFIELDS_PER_FLUSH>(MAXSTACK/4)
#undef LFIELDS_PER_FLUSH
#define LFIELDS_PER_FLUSH (MAXSTACK/4)
#endif
/* number of record items to accumulate before a SETMAP instruction */
/* (each item counts 2 elements on the stack: an index and a value) */
#define RFIELDS_PER_FLUSH (LFIELDS_PER_FLUSH/2)
/* maximum number of values printed in one call to `print' */
#ifndef MAXPRINT
#define MAXPRINT 40 /* arbitrary limit */
#endif
/* maximum depth of nested $ifs */
#ifndef MAX_IFS
#define MAX_IFS 5 /* arbitrary limit */
#endif
/* maximum size of a pragma line */
#ifndef PRAGMASIZE
#define PRAGMASIZE 80 /* arbitrary limit */
#endif
/* maximum lookback to find a real constant (for code generation) */
#ifndef LOOKBACKNUMS
#define LOOKBACKNUMS 20 /* arbitrary constant */
#endif
#endif

View File

@@ -1,6 +1,6 @@
/*
** $Id: lmathlib.c,v 1.9 1998/05/27 19:09:39 roberto Exp roberto $
** Lua standard mathematical library
** $Id: lmathlib.c,v 1.23 1999/12/27 17:33:22 roberto Exp roberto $
** Standard mathematical library
** See Copyright Notice in lua.h
*/
@@ -8,171 +8,168 @@
#include <stdlib.h>
#include <math.h>
#define LUA_REENTRANT
#include "lauxlib.h"
#include "lua.h"
#include "lualib.h"
#ifdef M_PI
#define PI M_PI
#undef PI
#define PI (3.14159265358979323846)
#define RADIANS_PER_DEGREE (PI/180.0)
/*
** If you want Lua to operate in radians (instead of degrees),
** define RADIANS
*/
#ifdef RADIANS
#define FROMRAD(a) (a)
#define TORAD(a) (a)
#else
#define PI ((double)3.14159265358979323846)
#define FROMRAD(a) ((a)/RADIANS_PER_DEGREE)
#define TORAD(a) ((a)*RADIANS_PER_DEGREE)
#endif
#define FROMRAD(a) ((a)*(180.0/PI))
#define TORAD(a) ((a)*(PI/180.0))
static void math_abs (void)
{
double d = luaL_check_number(1);
if (d < 0) d = -d;
lua_pushnumber(d);
static void math_abs (lua_State *L) {
lua_pushnumber(L, fabs(luaL_check_number(L, 1)));
}
static void math_sin (void)
{
lua_pushnumber(sin(TORAD(luaL_check_number(1))));
static void math_sin (lua_State *L) {
lua_pushnumber(L, sin(TORAD(luaL_check_number(L, 1))));
}
static void math_cos (void)
{
lua_pushnumber(cos(TORAD(luaL_check_number(1))));
static void math_cos (lua_State *L) {
lua_pushnumber(L, cos(TORAD(luaL_check_number(L, 1))));
}
static void math_tan (void)
{
lua_pushnumber(tan(TORAD(luaL_check_number(1))));
static void math_tan (lua_State *L) {
lua_pushnumber(L, tan(TORAD(luaL_check_number(L, 1))));
}
static void math_asin (void)
{
lua_pushnumber(FROMRAD(asin(luaL_check_number(1))));
static void math_asin (lua_State *L) {
lua_pushnumber(L, FROMRAD(asin(luaL_check_number(L, 1))));
}
static void math_acos (void)
{
lua_pushnumber(FROMRAD(acos(luaL_check_number(1))));
static void math_acos (lua_State *L) {
lua_pushnumber(L, FROMRAD(acos(luaL_check_number(L, 1))));
}
static void math_atan (void)
{
lua_pushnumber(FROMRAD(atan(luaL_check_number(1))));
static void math_atan (lua_State *L) {
lua_pushnumber(L, FROMRAD(atan(luaL_check_number(L, 1))));
}
static void math_atan2 (void)
{
lua_pushnumber(FROMRAD(atan2(luaL_check_number(1), luaL_check_number(2))));
static void math_atan2 (lua_State *L) {
lua_pushnumber(L, FROMRAD(atan2(luaL_check_number(L, 1), luaL_check_number(L, 2))));
}
static void math_ceil (void)
{
lua_pushnumber(ceil(luaL_check_number(1)));
static void math_ceil (lua_State *L) {
lua_pushnumber(L, ceil(luaL_check_number(L, 1)));
}
static void math_floor (void)
{
lua_pushnumber(floor(luaL_check_number(1)));
static void math_floor (lua_State *L) {
lua_pushnumber(L, floor(luaL_check_number(L, 1)));
}
static void math_mod (void)
{
lua_pushnumber(fmod(luaL_check_number(1), luaL_check_number(2)));
static void math_mod (lua_State *L) {
lua_pushnumber(L, fmod(luaL_check_number(L, 1), luaL_check_number(L, 2)));
}
static void math_sqrt (void)
{
lua_pushnumber(sqrt(luaL_check_number(1)));
static void math_sqrt (lua_State *L) {
lua_pushnumber(L, sqrt(luaL_check_number(L, 1)));
}
static void math_pow (void)
{
lua_pushnumber(pow(luaL_check_number(1), luaL_check_number(2)));
static void math_pow (lua_State *L) {
lua_pushnumber(L, pow(luaL_check_number(L, 1), luaL_check_number(L, 2)));
}
static void math_log (void)
{
lua_pushnumber(log(luaL_check_number(1)));
static void math_log (lua_State *L) {
lua_pushnumber(L, log(luaL_check_number(L, 1)));
}
static void math_log10 (void)
{
lua_pushnumber(log10(luaL_check_number(1)));
static void math_log10 (lua_State *L) {
lua_pushnumber(L, log10(luaL_check_number(L, 1)));
}
static void math_exp (void)
{
lua_pushnumber(exp(luaL_check_number(1)));
static void math_exp (lua_State *L) {
lua_pushnumber(L, exp(luaL_check_number(L, 1)));
}
static void math_deg (void)
{
lua_pushnumber(luaL_check_number(1)*(180.0/PI));
static void math_deg (lua_State *L) {
lua_pushnumber(L, luaL_check_number(L, 1)/RADIANS_PER_DEGREE);
}
static void math_rad (void)
{
lua_pushnumber(luaL_check_number(1)*(PI/180.0));
static void math_rad (lua_State *L) {
lua_pushnumber(L, luaL_check_number(L, 1)*RADIANS_PER_DEGREE);
}
static void math_frexp (void) {
static void math_frexp (lua_State *L) {
int e;
lua_pushnumber(frexp(luaL_check_number(1), &e));
lua_pushnumber(e);
lua_pushnumber(L, frexp(luaL_check_number(L, 1), &e));
lua_pushnumber(L, e);
}
static void math_ldexp (void) {
lua_pushnumber(ldexp(luaL_check_number(1), luaL_check_number(2)));
static void math_ldexp (lua_State *L) {
lua_pushnumber(L, ldexp(luaL_check_number(L, 1), luaL_check_int(L, 2)));
}
static void math_min (void)
{
static void math_min (lua_State *L) {
int i = 1;
double dmin = luaL_check_number(i);
while (lua_getparam(++i) != LUA_NOOBJECT) {
double d = luaL_check_number(i);
double dmin = luaL_check_number(L, i);
while (lua_getparam(L, ++i) != LUA_NOOBJECT) {
double d = luaL_check_number(L, i);
if (d < dmin)
dmin = d;
}
lua_pushnumber(dmin);
lua_pushnumber(L, dmin);
}
static void math_max (void)
{
static void math_max (lua_State *L) {
int i = 1;
double dmax = luaL_check_number(i);
while (lua_getparam(++i) != LUA_NOOBJECT) {
double d = luaL_check_number(i);
double dmax = luaL_check_number(L, i);
while (lua_getparam(L, ++i) != LUA_NOOBJECT) {
double d = luaL_check_number(L, i);
if (d > dmax)
dmax = d;
}
lua_pushnumber(dmax);
lua_pushnumber(L, dmax);
}
static void math_random (void)
{
/* the '%' is needed because on some systems (SunOS!) "rand()" may */
/* return a value bigger than RAND_MAX... */
static void math_random (lua_State *L) {
/* the '%' avoids the (rare) case of r==1, and is needed also because on
some systems (SunOS!) "rand()" may return a value larger than RAND_MAX */
double r = (double)(rand()%RAND_MAX) / (double)RAND_MAX;
double l = luaL_opt_number(1, 0);
if (l == 0)
lua_pushnumber(r);
else
lua_pushnumber((int)(r*l)+1);
if (lua_getparam(L, 1) == LUA_NOOBJECT) /* no arguments? */
lua_pushnumber(L, r); /* Number between 0 and 1 */
else {
int l, u; /* lower & upper limits */
if (lua_getparam(L, 2) == LUA_NOOBJECT) { /* only one argument? */
l = 1;
u = luaL_check_int(L, 1);
}
else { /* two arguments */
l = luaL_check_int(L, 1);
u = luaL_check_int(L, 2);
}
luaL_arg_check(L, l<=u, 1, "interval is empty");
lua_pushnumber(L, (int)(r*(u-l+1))+l); /* integer between `l' and `u' */
}
}
static void math_randomseed (void)
{
srand(luaL_check_number(1));
static void math_randomseed (lua_State *L) {
srand(luaL_check_int(L, 1));
}
static struct luaL_reg mathlib[] = {
static const struct luaL_reg mathlib[] = {
{"abs", math_abs},
{"sin", math_sin},
{"cos", math_cos},
@@ -201,13 +198,11 @@ static struct luaL_reg mathlib[] = {
/*
** Open math library
*/
void lua_mathlibopen (void)
{
luaL_openlib(mathlib, (sizeof(mathlib)/sizeof(mathlib[0])));
lua_pushstring("deg"); lua_setglobal("_TRIGMODE");
lua_pushcfunction(math_pow);
lua_pushnumber(0); /* to get its tag */
lua_settagmethod(lua_tag(lua_pop()), "pow");
lua_pushnumber(PI); lua_setglobal("PI");
void lua_mathlibopen (lua_State *L) {
luaL_openl(L, mathlib);
lua_pushcfunction(L, math_pow);
lua_pushnumber(L, 0); /* to get its tag */
lua_settagmethod(L, lua_tag(L, lua_pop(L)), "pow");
lua_pushnumber(L, PI); lua_setglobal(L, "PI");
}

183
lmem.c
View File

@@ -1,5 +1,5 @@
/*
** $Id: lmem.c,v 1.6 1998/06/19 16:14:09 roberto Exp roberto $
** $Id: lmem.c,v 1.28 2000/03/10 18:37:44 roberto Exp roberto $
** Interface to Memory Manager
** See Copyright Notice in lua.h
*/
@@ -7,107 +7,136 @@
#include <stdlib.h>
#define LUA_REENTRANT
#include "lmem.h"
#include "lobject.h"
#include "lstate.h"
#include "lua.h"
int luaM_growaux (void **block, unsigned long nelems, int size,
char *errormsg, unsigned long limit)
{
if (nelems >= limit)
lua_error(errormsg);
nelems = (nelems == 0) ? 32 : nelems*2;
if (nelems > limit)
nelems = limit;
*block = luaM_realloc(*block, nelems*size);
return (int)nelems;
}
#ifndef DEBUG
/*
** generic allocation routine.
** real ANSI systems do not need some of these tests,
** since realloc(NULL, s)==malloc(s) and realloc(b, 0)==free(b).
** But some systems (e.g. Sun OS) are not that ANSI...
** Number ANSI systems do not need these tests;
** but some systems (Sun OS) are not that ANSI...
*/
void *luaM_realloc (void *block, unsigned long size)
{
size_t s = (size_t)size;
if (s != size)
lua_error("Allocation Error: Block too big");
if (size == 0) {
if (block) {
free(block);
}
return NULL;
}
block = block ? realloc(block, s) : malloc(s);
if (block == NULL)
lua_error(memEM);
return block;
}
#ifdef OLD_ANSI
#define realloc(b,s) ((b) == NULL ? malloc(s) : (realloc)(b, s))
#define free(b) if (b) (free)(b)
#endif
#else
/* DEBUG */
#ifdef DEBUG
/*
** {======================================================================
** Controlled version for realloc.
** =======================================================================
*/
#include <assert.h>
#include <string.h>
#define HEADER (sizeof(double))
#define MARK 55
unsigned long numblocks = 0;
unsigned long totalmem = 0;
#define realloc(b, s) debug_realloc(b, s)
#define malloc(b) debug_realloc(NULL, 0)
#define free(b) debug_realloc(b, 0)
static void *checkblock (void *block)
{
unsigned long *b = (unsigned long *)((char *)block - HEADER);
/* ensures maximum alignment for HEADER */
#define HEADER (sizeof(double)>sizeof(long) ? sizeof(double) : sizeof(long))
#define MARKSIZE 16
#define MARK 0x55 /* 01010101 (a nice pattern) */
#define blocksize(b) ((unsigned long *)((char *)(b) - HEADER))
unsigned long memdebug_numblocks = 0;
unsigned long memdebug_total = 0;
unsigned long memdebug_maxmem = 0;
static void *checkblock (void *block) {
unsigned long *b = blocksize(block);
unsigned long size = *b;
LUA_ASSERT(*(((char *)b)+size+HEADER) == MARK,
"corrupted block");
numblocks--;
totalmem -= size;
int i;
for (i=0;i<MARKSIZE;i++)
assert(*(((char *)b)+HEADER+size+i) == MARK+i); /* corrupted block? */
memdebug_numblocks--;
memdebug_total -= size;
return b;
}
void *luaM_realloc (void *block, unsigned long size)
{
unsigned long realsize = HEADER+size+1;
if (realsize != (size_t)realsize)
lua_error("Allocation Error: Block too big");
if (size == 0) { /* ANSI dosen't need this, but some machines... */
if (block) {
unsigned long *b = (unsigned long *)((char *)block - HEADER);
memset(block, -1, *b); /* erase block */
block = checkblock(block);
free(block);
}
return NULL;
}
static void freeblock (void *block) {
if (block) {
size_t size = *blocksize(block);
block = checkblock(block);
block = (unsigned long *)realloc(block, realsize);
memset(block, -1, size+HEADER+MARKSIZE); /* erase block */
(free)(block); /* free original block */
}
else
block = (unsigned long *)malloc(realsize);
if (block == NULL)
lua_error(memEM);
totalmem += size;
numblocks++;
*(unsigned long *)block = size;
*(((char *)block)+size+HEADER) = MARK;
return (unsigned long *)((char *)block+HEADER);
}
static void *debug_realloc (void *block, size_t size) {
if (size == 0) {
freeblock(block);
return NULL;
}
else {
size_t realsize = HEADER+size+MARKSIZE;
char *newblock = (char *)(malloc)(realsize); /* alloc a new block */
int i;
if (newblock == NULL) return NULL;
if (block) {
size_t oldsize = *blocksize(block);
if (oldsize > size) oldsize = size;
memcpy(newblock+HEADER, block, oldsize);
freeblock(block); /* erase (and check) old copy */
}
memdebug_total += size;
if (memdebug_total > memdebug_maxmem) memdebug_maxmem = memdebug_total;
memdebug_numblocks++;
*(unsigned long *)newblock = size;
for (i=0;i<MARKSIZE;i++)
*(newblock+HEADER+size+i) = (char)(MARK+i);
return newblock+HEADER;
}
}
/* }====================================================================== */
#endif
void *luaM_growaux (lua_State *L, void *block, unsigned long nelems,
int inc, int size, const char *errormsg, unsigned long limit) {
unsigned long newn = nelems+inc;
if (newn >= limit) lua_error(L, errormsg);
if ((newn ^ nelems) <= nelems || /* still the same power-of-2 limit? */
(nelems > 0 && newn < MINPOWER2)) /* or block already is MINPOWER2? */
return block; /* do not need to reallocate */
else /* it crossed a power-of-2 boundary; grow to next power */
return luaM_realloc(L, block, luaO_power2(newn)*size);
}
/*
** generic allocation routine.
*/
void *luaM_realloc (lua_State *L, void *block, unsigned long size) {
if (size == 0) {
free(block); /* block may be NULL; that is OK for free */
return NULL;
}
else if ((size_t)size != size)
lua_error(L, "memory allocation error: block too big");
block = realloc(block, size);
if (block == NULL)
lua_error(L, memEM);
return block;
}

33
lmem.h
View File

@@ -1,5 +1,5 @@
/*
** $Id: lmem.h,v 1.4 1997/12/01 20:30:44 roberto Exp roberto $
** $Id: lmem.h,v 1.12 2000/01/13 16:30:47 roberto Exp roberto $
** Interface to Memory Manager
** See Copyright Notice in lua.h
*/
@@ -8,10 +8,9 @@
#define lmem_h
#ifndef NULL
#define NULL 0
#endif
#include <stdlib.h>
#include "lua.h"
/* memory error messages */
#define codeEM "code size overflow"
@@ -19,23 +18,25 @@
#define refEM "reference table overflow"
#define tableEM "table overflow"
#define memEM "not enough memory"
#define arrEM "internal array larger than `int' limit"
void *luaM_realloc (void *oldblock, unsigned long size);
int luaM_growaux (void **block, unsigned long nelems, int size,
char *errormsg, unsigned long limit);
void *luaM_realloc (lua_State *L, void *oldblock, unsigned long size);
void *luaM_growaux (lua_State *L, void *block, unsigned long nelems, int inc, int size,
const char *errormsg, unsigned long limit);
#define luaM_free(b) luaM_realloc((b), 0)
#define luaM_malloc(t) luaM_realloc(NULL, (t))
#define luaM_new(t) ((t *)luaM_malloc(sizeof(t)))
#define luaM_newvector(n,t) ((t *)luaM_malloc((n)*sizeof(t)))
#define luaM_growvector(old,n,t,e,l) \
(luaM_growaux((void**)old,n,sizeof(t),e,l))
#define luaM_reallocvector(v,n,t) ((t *)luaM_realloc(v,(n)*sizeof(t)))
#define luaM_free(L, b) luaM_realloc(L, (b), 0)
#define luaM_malloc(L, t) luaM_realloc(L, NULL, (t))
#define luaM_new(L, t) ((t *)luaM_malloc(L, sizeof(t)))
#define luaM_newvector(L, n,t) ((t *)luaM_malloc(L, (n)*sizeof(t)))
#define luaM_growvector(L, v,nelems,inc,t,e,l) \
((v)=(t *)luaM_growaux(L, v,nelems,inc,sizeof(t),e,l))
#define luaM_reallocvector(L, v,n,t) ((v)=(t *)luaM_realloc(L, v,(n)*sizeof(t)))
#ifdef DEBUG
extern unsigned long numblocks;
extern unsigned long totalmem;
extern unsigned long memdebug_numblocks;
extern unsigned long memdebug_total;
extern unsigned long memdebug_maxmem;
#endif

135
lobject.c
View File

@@ -1,83 +1,110 @@
/*
** $Id: lobject.c,v 1.12 1998/06/18 16:57:03 roberto Exp roberto $
** $Id: lobject.c,v 1.35 2000/03/29 20:19:20 roberto Exp roberto $
** Some generic functions over Lua objects
** See Copyright Notice in lua.h
*/
#include <ctype.h>
#include <stdlib.h>
#define LUA_REENTRANT
#include "lobject.h"
#include "lua.h"
char *luaO_typenames[] = { /* ORDER LUA_T */
"userdata", "number", "string", "table", "function", "function",
"nil", "function", "mark", "mark", "mark", "line", NULL
const char *const luaO_typenames[] = { /* ORDER LUA_T */
"userdata", "number", "string", "table", "function", "function", "nil",
"function", "function", "line"
};
TObject luaO_nilobject = {LUA_T_NIL, {NULL}};
const TObject luaO_nilobject = {TAG_NIL, {NULL}};
/* hash dimensions values */
static long dimensions[] =
{5L, 11L, 23L, 47L, 97L, 197L, 397L, 797L, 1597L, 3203L, 6421L,
12853L, 25717L, 51437L, 102811L, 205619L, 411233L, 822433L,
1644817L, 3289613L, 6579211L, 13158023L, MAX_INT};
int luaO_redimension (int oldsize)
{
int i;
for (i=0; dimensions[i]<MAX_INT; i++) {
if (dimensions[i] > oldsize)
return dimensions[i];
}
lua_error("table overflow");
return 0; /* to avoid warnings */
/*
** returns smaller power of 2 larger than `n' (minimum is MINPOWER2)
*/
unsigned long luaO_power2 (unsigned long n) {
unsigned long p = MINPOWER2;
while (p<=n) p<<=1;
return p;
}
int luaO_equalObj (TObject *t1, TObject *t2)
{
if (ttype(t1) != ttype(t2)) return 0;
int luaO_equalval (const TObject *t1, const TObject *t2) {
switch (ttype(t1)) {
case LUA_T_NIL: return 1;
case LUA_T_NUMBER: return nvalue(t1) == nvalue(t2);
case LUA_T_STRING: case LUA_T_USERDATA: return svalue(t1) == svalue(t2);
case LUA_T_ARRAY: return avalue(t1) == avalue(t2);
case LUA_T_PROTO: return tfvalue(t1) == tfvalue(t2);
case LUA_T_CPROTO: return fvalue(t1) == fvalue(t2);
case LUA_T_CLOSURE: return t1->value.cl == t2->value.cl;
case TAG_NUMBER:
return nvalue(t1) == nvalue(t2);
case TAG_STRING: case TAG_USERDATA:
return svalue(t1) == svalue(t2);
case TAG_TABLE:
return avalue(t1) == avalue(t2);
case TAG_CCLOSURE: case TAG_LCLOSURE:
return clvalue(t1) == clvalue(t2);
default:
LUA_INTERNALERROR("invalid type");
return 0; /* UNREACHABLE */
LUA_ASSERT(L, ttype(t1) == TAG_NIL, "invalid type");
return 1; /* TAG_NIL */
}
}
void luaO_insertlist (GCnode *root, GCnode *node)
{
node->next = root->next;
root->next = node;
node->marked = 0;
static double expten (unsigned int e) {
double exp = 10.0;
double res = 1.0;
for (; e; e>>=1) {
if (e & 1) res *= exp;
exp *= exp;
}
return res;
}
#ifdef OLD_ANSI
void luaO_memup (void *dest, void *src, int size)
{
char *d = dest;
char *s = src;
while (size--) d[size]=s[size];
int luaO_str2d (const char *s, Number *result) { /* LUA_NUMBER */
double a = 0.0;
int point = 0; /* number of decimal digits */
int sig;
while (isspace((unsigned char)*s)) s++;
sig = 0;
switch (*s) {
case '-': sig = 1; /* go through */
case '+': s++;
}
if (! (isdigit((unsigned char)*s) ||
(*s == '.' && isdigit((unsigned char)*(s+1)))))
return 0; /* not (at least one digit before or after the point) */
while (isdigit((unsigned char)*s))
a = 10.0*a + (*(s++)-'0');
if (*s == '.') {
s++;
while (isdigit((unsigned char)*s)) {
a = 10.0*a + (*(s++)-'0');
point++;
}
}
if (sig) a = -a;
if (*s == 'e' || *s == 'E') {
int e = 0;
s++;
sig = 0;
switch (*s) {
case '-': sig = 1; /* go through */
case '+': s++;
}
if (!isdigit((unsigned char)*s)) return 0; /* no digit in the exponent? */
do {
e = 10*e + (*(s++)-'0');
} while (isdigit((unsigned char)*s));
if (sig) e = -e;
point -= e;
}
while (isspace((unsigned char)*s)) s++;
if (*s != '\0') return 0; /* invalid trailing characters? */
if (point != 0) {
if (point > 0) a /= expten(point);
else a *= expten(-point);
}
*result = a;
return 1;
}
void luaO_memdown (void *dest, void *src, int size)
{
char *d = dest;
char *s = src;
int i;
for (i=0; i<size; i++) d[i]=s[i];
}
#endif

231
lobject.h
View File

@@ -1,5 +1,5 @@
/*
** $Id: lobject.h,v 1.20 1998/06/11 18:21:37 roberto Exp roberto $
** $Id: lobject.h,v 1.59 2000/03/31 16:28:45 roberto Exp roberto $
** Type definitions for Lua objects
** See Copyright Notice in lua.h
*/
@@ -8,52 +8,28 @@
#define lobject_h
#include <limits.h>
#include "llimits.h"
#include "lua.h"
#ifdef DEBUG
#include "lauxlib.h"
#define LUA_INTERNALERROR(s) \
luaL_verror("INTERNAL ERROR - %s [%s:%d]",(s),__FILE__,__LINE__)
#define LUA_ASSERT(c,s) { if (!(c)) LUA_INTERNALERROR(s); }
#undef NDEBUG
#include <assert.h>
#define LUA_INTERNALERROR(L,s) assert(((void)s,0))
#define LUA_ASSERT(L,c,s) assert(((void)s,(c)))
#else
#define LUA_INTERNALERROR(s) /* empty */
#define LUA_ASSERT(c,s) /* empty */
#define LUA_INTERNALERROR(L,s) /* empty */
#define LUA_ASSERT(L,c,s) /* empty */
#endif
/*
** "real" is the type "number" of Lua
** GREP LUA_NUMBER to change that
*/
#ifndef LUA_NUM_TYPE
#define LUA_NUM_TYPE double
#endif
/*
** format to convert number to strings
*/
#define NUMBER_FMT "%g"
typedef LUA_NUM_TYPE real;
#define Byte lua_Byte /* some systems have Byte as a predefined type */
typedef unsigned char Byte; /* unsigned 8 bits */
#define MAX_INT (INT_MAX-2) /* maximum value of an int (-2 for safety) */
/* maximum value of a word of 2 bytes (-2 for safety); must fit in an "int" */
#if MAX_INT < 65534
#define MAX_WORD MAX_INT
#ifdef DEBUG
/* to avoid warnings, and make sure value is really unused */
#define UNUSED(x) (x=0, (void)(x))
#else
#define MAX_WORD 65534
#define UNUSED(x) ((void)(x)) /* to avoid warnings */
#endif
typedef unsigned int IntPoint; /* unsigned with same size as a pointer (for hashing) */
/*
** Lua TYPES
@@ -61,150 +37,153 @@ typedef unsigned int IntPoint; /* unsigned with same size as a pointer (for hash
** grep "ORDER LUA_T"
*/
typedef enum {
LUA_T_USERDATA = 0, /* tag default for userdata */
LUA_T_NUMBER = -1, /* fixed tag for numbers */
LUA_T_STRING = -2, /* fixed tag for strings */
LUA_T_ARRAY = -3, /* tag default for tables (or arrays) */
LUA_T_PROTO = -4, /* fixed tag for functions */
LUA_T_CPROTO = -5, /* fixed tag for Cfunctions */
LUA_T_NIL = -6, /* last "pre-defined" tag */
LUA_T_CLOSURE = -7,
LUA_T_CLMARK = -8, /* mark for closures */
LUA_T_PMARK = -9, /* mark for Lua prototypes */
LUA_T_CMARK = -10, /* mark for C prototypes */
LUA_T_LINE = -11
TAG_USERDATA = 0, /* default tag for userdata */
TAG_NUMBER, /* fixed tag for numbers */
TAG_STRING, /* fixed tag for strings */
TAG_TABLE, /* default tag for tables */
TAG_LCLOSURE, /* fixed tag for Lua closures */
TAG_CCLOSURE, /* fixed tag for C closures */
TAG_NIL, /* last "pre-defined" tag */
TAG_LMARK, /* mark for Lua closures */
TAG_CMARK, /* mark for C closures */
TAG_LINE
} lua_Type;
#define NUM_TYPES 11
#define NUM_TAGS 7
/* tags for values visible from Lua == first user-created tag */
#define NUM_TAGS 7
/*
** check whether `t' is a mark
*/
#define is_T_MARK(t) ((t) == TAG_LMARK || (t) == TAG_CMARK)
typedef union {
lua_CFunction f; /* LUA_T_CPROTO, LUA_T_CMARK */
real n; /* LUA_T_NUMBER */
struct TaggedString *ts; /* LUA_T_STRING, LUA_T_USERDATA */
struct TProtoFunc *tf; /* LUA_T_PROTO, LUA_T_PMARK */
struct Closure *cl; /* LUA_T_CLOSURE, LUA_T_CLMARK */
struct Hash *a; /* LUA_T_ARRAY */
int i; /* LUA_T_LINE */
struct TString *ts; /* TAG_STRING, TAG_USERDATA */
struct Closure *cl; /* TAG_[CL]CLOSURE, TAG_[CL]MARK */
struct Hash *a; /* TAG_TABLE */
Number n; /* TAG_NUMBER */
int i; /* TAG_LINE */
} Value;
/* Macros to access values */
#define ttype(o) ((o)->ttype)
#define nvalue(o) ((o)->value.n)
#define svalue(o) ((o)->value.ts->str)
#define tsvalue(o) ((o)->value.ts)
#define clvalue(o) ((o)->value.cl)
#define avalue(o) ((o)->value.a)
typedef struct TObject {
lua_Type ttype;
Value value;
} TObject;
/*
** generic header for garbage collector lists
*/
typedef struct GCnode {
struct GCnode *next;
int marked;
} GCnode;
typedef struct GlobalVar {
TObject value;
struct GlobalVar *next;
struct TString *name;
} GlobalVar;
/*
** String headers for string table
*/
typedef struct TaggedString {
GCnode head;
unsigned long hash;
int constindex; /* hint to reuse constants (= -1 if this is a userdata) */
typedef struct TString {
union {
struct {
TObject globalval;
long len; /* if this is a string, here is its length */
struct { /* for strings */
GlobalVar *gv; /* eventual global value with this name */
long len;
} s;
struct {
struct { /* for userdata */
int tag;
void *v; /* if this is a userdata, here is its value */
void *value;
} d;
} u;
char str[1]; /* \0 byte already reserved */
} TaggedString;
struct TString *nexthash; /* chain for hash table */
unsigned long hash;
int constindex; /* hint to reuse constants (= -1 if this is a userdata) */
unsigned char marked;
char str[1]; /* variable length string!! must be the last field! */
} TString;
/*
** Function Prototypes
*/
typedef struct TProtoFunc {
GCnode head;
struct TObject *consts;
int nconsts;
Byte *code; /* ends with opcode ENDCODE */
typedef struct Proto {
struct Proto *next;
int marked;
struct TString **kstr; /* strings used by the function */
int nkstr; /* size of `kstr' */
Number *knum; /* Number numbers used by the function */
int nknum; /* size of `knum' */
struct Proto **kproto; /* functions defined inside the function */
int nkproto; /* size of `kproto' */
Instruction *code; /* ends with opcode ENDCODE */
int lineDefined;
TaggedString *fileName;
TString *source;
int numparams;
int is_vararg;
int maxstacksize;
struct LocVar *locvars; /* ends with line = -1 */
} TProtoFunc;
} Proto;
typedef struct LocVar {
TaggedString *varname; /* NULL signals end of scope */
TString *varname; /* NULL signals end of scope */
int line;
} LocVar;
/* Macros to access structure members */
#define ttype(o) ((o)->ttype)
#define nvalue(o) ((o)->value.n)
#define svalue(o) ((o)->value.ts->str)
#define tsvalue(o) ((o)->value.ts)
#define clvalue(o) ((o)->value.cl)
#define avalue(o) ((o)->value.a)
#define fvalue(o) ((o)->value.f)
#define tfvalue(o) ((o)->value.tf)
#define protovalue(o) ((o)->value.cl->consts)
/*
** Closures
*/
typedef struct Closure {
GCnode head;
int nelems; /* not included the first one (always the prototype) */
TObject consts[1]; /* at least one for prototype */
struct Closure *next;
int marked;
union {
lua_CFunction c; /* C functions */
struct Proto *l; /* Lua functions */
} f;
int nelems;
TObject consts[1];
} Closure;
typedef struct node {
TObject ref;
typedef struct Node {
TObject key;
TObject val;
struct Node *next; /* for chaining */
} Node;
typedef struct Hash {
GCnode head;
Node *node;
int nhash;
int nuse;
int htag;
Node *node;
int size;
Node *firstfree; /* this position is free; all positions after it are full */
struct Hash *next;
int marked;
} Hash;
extern char *luaO_typenames[];
extern const char *const luaO_typenames[];
extern const TObject luaO_nilobject;
extern TObject luaO_nilobject;
#define luaO_typename(o) luaO_typenames[ttype(o)]
int luaO_equalObj (TObject *t1, TObject *t2);
int luaO_redimension (int oldsize);
void luaO_insertlist (GCnode *root, GCnode *node);
unsigned long luaO_power2 (unsigned long n);
#define luaO_equalObj(t1,t2) (ttype(t1) == ttype(t2) && luaO_equalval(t1,t2))
int luaO_equalval (const TObject *t1, const TObject *t2);
int luaO_redimension (lua_State *L, int oldsize);
int luaO_str2d (const char *s, Number *result);
#ifdef OLD_ANSI
void luaO_memup (void *dest, void *src, int size);
void luaO_memdown (void *dest, void *src, int size);
#else
#include <string.h>
#define luaO_memup(d,s,n) memmove(d,s,n)
#define luaO_memdown(d,s,n) memmove(d,s,n)
#endif
#endif

View File

@@ -1,5 +1,5 @@
/*
** $Id: lopcodes.h,v 1.17 1998/03/25 18:52:29 roberto Exp roberto $
** $Id: lopcodes.h,v 1.58 2000/04/13 16:51:01 roberto Exp roberto $
** Opcodes for Lua virtual machine
** See Copyright Notice in lua.h
*/
@@ -7,175 +7,151 @@
#ifndef lopcodes_h
#define lopcodes_h
#include "llimits.h"
/*===========================================================================
We assume that instructions are unsigned numbers.
All instructions have an opcode in the first 6 bits. Moreover,
an instruction can have 0, 1, or 2 arguments. Instructions can
have the following types:
type 0: no arguments
type 1: 1 unsigned argument in the higher bits (called `U')
type 2: 1 signed argument in the higher bits (`S')
type 3: 1st unsigned argument in the higher bits (`A')
2nd unsigned argument in the middle bits (`B')
A signed argument is represented in excess K; that is, the number
value is the unsigned value minus K. K is exactly the maximum value
for that argument (so that -max is represented by 0, and +max is
represented by 2*max), which is half the maximum for the corresponding
unsigned argument.
The size of each argument is defined in `llimits.h'. The usual is an
instruction with 32 bits, U arguments with 26 bits (32-6), B arguments
with 9 bits, and A arguments with 17 bits (32-6-9). For small
instalations, the instruction size can be 16, so U has 10 bits,
and A and B have 5 bits each.
===========================================================================*/
/* creates a mask with `n' 1 bits at position `p' */
#define MASK1(n,p) ((~((~(Instruction)0)<<n))<<p)
/* creates a mask with `n' 0 bits at position `p' */
#define MASK0(n,p) (~MASK1(n,p))
/*
** NOTICE: variants of the same opcode must be consecutive: First, those
** with byte parameter, then with built-in parameters, and last with
** word parameter.
** the following macros help to manipulate instructions
*/
#define CREATE_0(o) ((Instruction)(o))
#define GET_OPCODE(i) ((OpCode)((i)&MASK1(SIZE_OP,0)))
#define SET_OPCODE(i,o) ((i) = (((i)&MASK0(SIZE_OP,0)) | (Instruction)(o)))
#define CREATE_U(o,u) ((Instruction)(o) | (Instruction)(u)<<POS_U)
#define GETARG_U(i) ((int)((i)>>POS_U))
#define SETARG_U(i,u) ((i) = (((i)&MASK0(SIZE_U,POS_U)) | \
((Instruction)(u)<<POS_U)))
#define CREATE_S(o,s) CREATE_U((o),(s)+MAXARG_S)
#define GETARG_S(i) (GETARG_U(i)-MAXARG_S)
#define SETARG_S(i,s) SETARG_U((i),(s)+MAXARG_S)
#define CREATE_AB(o,a,b) ((Instruction)(o) | ((Instruction)(a)<<POS_A) \
| ((Instruction)(b)<<POS_B))
#define GETARG_A(i) ((int)((i)>>POS_A))
#define SETARG_A(i,a) ((i) = (((i)&MASK0(SIZE_A,POS_A)) | \
((Instruction)(a)<<POS_A)))
#define GETARG_B(i) ((int)(((i)>>POS_B) & MASK1(SIZE_B,0)))
#define SETARG_B(i,b) ((i) = (((i)&MASK0(SIZE_B,POS_B)) | \
((Instruction)(b)<<POS_B)))
/*
** K = U argument used as index to `kstr'
** J = S argument used as jump offset (relative to pc of next instruction)
** L = unsigned argument used as index of local variable
** N = U argument used as index to `knum'
*/
typedef enum {
/* name parm before after side effect
-----------------------------------------------------------------------------*/
ENDCODE,/* - - - */
/*----------------------------------------------------------------------
name args stack before stack after side effects
------------------------------------------------------------------------*/
OP_END,/* - - (return) no results */
OP_RETURN,/* U v_n-v_x(at u) (return) returns v_x-v_n */
PUSHNIL,/* b - nil_0...nil_b */
PUSHNIL0,/* - - nil */
OP_CALL,/* A B v_n-v_1 f(at a) r_b-r_1 f(v1,...,v_n) */
OP_TAILCALL,/* A B v_n-v_1 f(at a) (return) f(v1,...,v_n) */
PUSHNUMBER,/* b - (float)b */
PUSHNUMBER0,/* - - 0.0 */
PUSHNUMBER1,/* - - 1.0 */
PUSHNUMBER2,/* - - 2.0 */
PUSHNUMBERW,/* w - (float)w */
OP_PUSHNIL,/* U - nil_1-nil_u */
OP_POP,/* U a_u-a_1 - */
PUSHCONSTANT,/* b - CNST[b] */
PUSHCONSTANT0,/*- - CNST[0] */
PUSHCONSTANT1,/*- - CNST[1] */
PUSHCONSTANT2,/*- - CNST[2] */
PUSHCONSTANT3,/*- - CNST[3] */
PUSHCONSTANT4,/*- - CNST[4] */
PUSHCONSTANT5,/*- - CNST[5] */
PUSHCONSTANT6,/*- - CNST[6] */
PUSHCONSTANT7,/*- - CNST[7] */
PUSHCONSTANTW,/*w - CNST[w] */
OP_PUSHINT,/* S - (Number)s */
OP_PUSHSTRING,/* K - KSTR[k] */
OP_PUSHNUM,/* N - KNUM[n] */
OP_PUSHNEGNUM,/* N - -KNUM[n] */
PUSHUPVALUE,/* b - Closure[b] */
PUSHUPVALUE0,/* - - Closure[0] */
PUSHUPVALUE1,/* - - Closure[1] */
OP_PUSHUPVALUE,/* U - Closure[u] */
PUSHLOCAL,/* b - LOC[b] */
PUSHLOCAL0,/* - - LOC[0] */
PUSHLOCAL1,/* - - LOC[1] */
PUSHLOCAL2,/* - - LOC[2] */
PUSHLOCAL3,/* - - LOC[3] */
PUSHLOCAL4,/* - - LOC[4] */
PUSHLOCAL5,/* - - LOC[5] */
PUSHLOCAL6,/* - - LOC[6] */
PUSHLOCAL7,/* - - LOC[7] */
OP_GETLOCAL,/* L - LOC[l] */
OP_GETGLOBAL,/* K - VAR[KSTR[k]] */
GETGLOBAL,/* b - VAR[CNST[b]] */
GETGLOBAL0,/* - - VAR[CNST[0]] */
GETGLOBAL1,/* - - VAR[CNST[1]] */
GETGLOBAL2,/* - - VAR[CNST[2]] */
GETGLOBAL3,/* - - VAR[CNST[3]] */
GETGLOBAL4,/* - - VAR[CNST[4]] */
GETGLOBAL5,/* - - VAR[CNST[5]] */
GETGLOBAL6,/* - - VAR[CNST[6]] */
GETGLOBAL7,/* - - VAR[CNST[7]] */
GETGLOBALW,/* w - VAR[CNST[w]] */
OP_GETTABLE,/* - i t t[i] */
OP_GETDOTTED,/* K t t[KSTR[k]] */
OP_GETINDEXED,/* L t t[LOC[l]] */
OP_PUSHSELF,/* K t t t[KSTR[k]] */
GETTABLE,/* - i t t[i] */
OP_CREATETABLE,/* U - newarray(size = u) */
GETDOTTED,/* b t t[CNST[b]] */
GETDOTTED0,/* - t t[CNST[0]] */
GETDOTTED1,/* - t t[CNST[1]] */
GETDOTTED2,/* - t t[CNST[2]] */
GETDOTTED3,/* - t t[CNST[3]] */
GETDOTTED4,/* - t t[CNST[4]] */
GETDOTTED5,/* - t t[CNST[5]] */
GETDOTTED6,/* - t t[CNST[6]] */
GETDOTTED7,/* - t t[CNST[7]] */
GETDOTTEDW,/* w t t[CNST[w]] */
OP_SETLOCAL,/* L x - LOC[l]=x */
OP_SETGLOBAL,/* K x - VAR[KSTR[k]]=x */
OP_SETTABLE,/* A B v a_a-a_1 i t (pops b values) t[i]=v */
PUSHSELF,/* b t t t[CNST[b]] */
PUSHSELF0,/* - t t t[CNST[0]] */
PUSHSELF1,/* - t t t[CNST[1]] */
PUSHSELF2,/* - t t t[CNST[2]] */
PUSHSELF3,/* - t t t[CNST[3]] */
PUSHSELF4,/* - t t t[CNST[4]] */
PUSHSELF5,/* - t t t[CNST[5]] */
PUSHSELF6,/* - t t t[CNST[6]] */
PUSHSELF7,/* - t t t[CNST[7]] */
PUSHSELFW,/* w t t t[CNST[w]] */
OP_SETLIST,/* A B v_b-v_0 t t t[i+a*FPF]=v_i */
OP_SETMAP,/* U v_u k_u - v_0 k_0 t t t[k_i]=v_i */
CREATEARRAY,/* b - newarray(size = b) */
CREATEARRAY0,/* - - newarray(size = 0) */
CREATEARRAY1,/* - - newarray(size = 1) */
CREATEARRAYW,/* w - newarray(size = w) */
OP_ADD,/* - y x x+y */
OP_ADDI,/* S x x+s */
OP_SUB,/* - y x x-y */
OP_MULT,/* - y x x*y */
OP_DIV,/* - y x x/y */
OP_POW,/* - y x x^y */
OP_CONCAT,/* U v_u-v_1 v1..-..v_u */
OP_MINUS,/* - x -x */
OP_NOT,/* - x (x==nil)? 1 : nil */
SETLOCAL,/* b x - LOC[b]=x */
SETLOCAL0,/* - x - LOC[0]=x */
SETLOCAL1,/* - x - LOC[1]=x */
SETLOCAL2,/* - x - LOC[2]=x */
SETLOCAL3,/* - x - LOC[3]=x */
SETLOCAL4,/* - x - LOC[4]=x */
SETLOCAL5,/* - x - LOC[5]=x */
SETLOCAL6,/* - x - LOC[6]=x */
SETLOCAL7,/* - x - LOC[7]=x */
OP_JMPNE,/* J y x - (x~=y)? PC+=s */
OP_JMPEQ,/* J y x - (x==y)? PC+=s */
OP_JMPLT,/* J y x - (x<y)? PC+=s */
OP_JMPLE,/* J y x - (x<y)? PC+=s */
OP_JMPGT,/* J y x - (x>y)? PC+=s */
OP_JMPGE,/* J y x - (x>=y)? PC+=s */
SETGLOBAL,/* b x - VAR[CNST[b]]=x */
SETGLOBAL0,/* - x - VAR[CNST[0]]=x */
SETGLOBAL1,/* - x - VAR[CNST[1]]=x */
SETGLOBAL2,/* - x - VAR[CNST[2]]=x */
SETGLOBAL3,/* - x - VAR[CNST[3]]=x */
SETGLOBAL4,/* - x - VAR[CNST[4]]=x */
SETGLOBAL5,/* - x - VAR[CNST[5]]=x */
SETGLOBAL6,/* - x - VAR[CNST[6]]=x */
SETGLOBAL7,/* - x - VAR[CNST[7]]=x */
SETGLOBALW,/* w x - VAR[CNST[w]]=x */
OP_JMPT,/* J x - (x~=nil)? PC+=s */
OP_JMPF,/* J x - (x==nil)? PC+=s */
OP_JMPONT,/* J x (x~=nil)? x : - (x~=nil)? PC+=s */
OP_JMPONF,/* J x (x==nil)? x : - (x==nil)? PC+=s */
OP_JMP,/* J - - PC+=s */
SETTABLE0,/* - v i t - t[i]=v */
OP_PUSHNILJMP,/* - - nil PC++; */
SETTABLE,/* b v a_b...a_1 i t a_b...a_1 i t t[i]=v */
OP_FORPREP,/* J */
OP_FORLOOP,/* J */
SETLIST,/* b c v_c...v_1 t - t[i+b*FPF]=v_i */
SETLIST0,/* b v_b...v_1 t - t[i]=v_i */
SETLISTW,/* w c v_c...v_1 t - t[i+w*FPF]=v_i */
OP_CLOSURE,/* A B v_b-v_1 closure(KPROTO[a], v_1-v_b) */
SETMAP,/* b v_b k_b ...v_0 k_0 t t t[k_i]=v_i */
SETMAP0,/* - v_0 k_0 t t t[k_0]=v_0 */
EQOP,/* - y x (x==y)? 1 : nil */
NEQOP,/* - y x (x~=y)? 1 : nil */
LTOP,/* - y x (x<y)? 1 : nil */
LEOP,/* - y x (x<y)? 1 : nil */
GTOP,/* - y x (x>y)? 1 : nil */
GEOP,/* - y x (x>=y)? 1 : nil */
ADDOP,/* - y x x+y */
SUBOP,/* - y x x-y */
MULTOP,/* - y x x*y */
DIVOP,/* - y x x/y */
POWOP,/* - y x x^y */
CONCOP,/* - y x x..y */
MINUSOP,/* - x -x */
NOTOP,/* - x (x==nil)? 1 : nil */
ONTJMP,/* b x (x!=nil)? x : - (x!=nil)? PC+=b */
ONTJMPW,/* w x (x!=nil)? x : - (x!=nil)? PC+=w */
ONFJMP,/* b x (x==nil)? x : - (x==nil)? PC+=b */
ONFJMPW,/* w x (x==nil)? x : - (x==nil)? PC+=w */
JMP,/* b - - PC+=b */
JMPW,/* w - - PC+=w */
IFFJMP,/* b x - (x==nil)? PC+=b */
IFFJMPW,/* w x - (x==nil)? PC+=w */
IFTUPJMP,/* b x - (x!=nil)? PC-=b */
IFTUPJMPW,/* w x - (x!=nil)? PC-=w */
IFFUPJMP,/* b x - (x==nil)? PC-=b */
IFFUPJMPW,/* w x - (x==nil)? PC-=w */
CLOSURE,/* b c v_c...v_1 closure(CNST[b], v_c...v_1) */
CLOSUREW,/* w c v_b...v_1 closure(CNST[w], v_c...v_1) */
CALLFUNC,/* b c v_c...v_1 f r_b...r_1 f(v1,...,v_c) */
CALLFUNC0,/* b v_b...v_1 f - f(v1,...,v_b) */
CALLFUNC1,/* b v_b...v_1 f r_1 f(v1,...,v_b) */
RETCODE,/* b - - */
SETLINE,/* b - - LINE=b */
SETLINEW,/* w - - LINE=w */
POP,/* b - - TOP-=(b+1) */
POP0,/* - - - TOP-=1 */
POP1/* - - - TOP-=2 */
OP_SETLINE/* U - - LINE=u */
} OpCode;
#define RFIELDS_PER_FLUSH 32 /* records (SETMAP) */
#define LFIELDS_PER_FLUSH 64 /* lists (SETLIST) */
#define ZEROVARARG 64
#define ISJUMP(o) (OP_JMPNE <= (o) && (o) <= OP_JMP)
#endif

2244
lparser.c

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
/*
** $Id: lparser.h,v 1.1 1997/09/16 19:25:59 roberto Exp roberto $
** Syntax analizer and code generator
** $Id: lparser.h,v 1.15 2000/04/05 17:51:58 roberto Exp roberto $
** LL(1) Parser and code generator for Lua
** See Copyright Notice in lua.h
*/
@@ -11,10 +11,51 @@
#include "lzio.h"
void luaY_codedebugline (int line);
TProtoFunc *luaY_parser (ZIO *z);
void luaY_error (char *s);
void luaY_syntaxerror (char *s, char *token);
/*
** Expression descriptor
*/
typedef enum {
VGLOBAL,
VLOCAL,
VINDEXED,
VEXP
} expkind;
typedef struct expdesc {
expkind k;
union {
int index; /* VGLOBAL: `kstr' index of global name; VLOCAL: stack index */
struct {
int t; /* patch list of `exit when true' */
int f; /* patch list of `exit when false' */
} l;
} u;
} expdesc;
/* state needed to generate code for a given function */
typedef struct FuncState {
Proto *f; /* current function header */
struct FuncState *prev; /* enclosing function */
struct LexState *ls; /* lexical state */
struct lua_State *L; /* copy of the Lua state */
int pc; /* next position to code */
int lasttarget; /* `pc' of last `jump target' */
int jlt; /* list of jumps to `lasttarged' */
int stacklevel; /* number of values on activation register */
int nlocalvar; /* number of active local variables */
int nupvalues; /* number of upvalues */
int nvars; /* number of entries in f->locvars (-1 if no debug information) */
int lastsetline; /* line where last SETLINE was issued */
struct Breaklabel *bl; /* chain of breakable blocks */
expdesc upvalues[MAXUPVALUES]; /* upvalues */
TString *localvar[MAXLOCALS]; /* store local variable names */
} FuncState;
Proto *luaY_parser (lua_State *L, ZIO *z);
#endif

115
lref.c Normal file
View File

@@ -0,0 +1,115 @@
/*
** $Id: lref.c,v 1.10 2000/03/27 20:10:21 roberto Exp roberto $
** reference mechanism
** See Copyright Notice in lua.h
*/
#define LUA_REENTRANT
#include "lapi.h"
#include "lmem.h"
#include "lref.h"
#include "lstate.h"
#include "lua.h"
int lua_ref (lua_State *L, int lock) {
int ref;
luaA_checkCargs(L, 1);
if (ttype(L->top-1) == TAG_NIL)
ref = LUA_REFNIL;
else {
if (L->refFree != NONEXT) { /* is there a free place? */
ref = L->refFree;
L->refFree = L->refArray[ref].st;
}
else { /* no more free places */
luaM_growvector(L, L->refArray, L->refSize, 1, struct Ref, refEM, MAX_INT);
ref = L->refSize++;
}
L->refArray[ref].o = *(L->top-1);
L->refArray[ref].st = lock ? LOCK : HOLD;
}
L->top--;
return ref;
}
void lua_unref (lua_State *L, int ref) {
if (ref >= 0) {
if (ref >= L->refSize || L->refArray[ref].st >= 0)
lua_error(L, "Lua API error - "
"invalid argument for function `lua_unref'");
L->refArray[ref].st = L->refFree;
L->refFree = ref;
}
}
lua_Object lua_getref (lua_State *L, int ref) {
if (ref == LUA_REFNIL)
return luaA_putluaObject(L, &luaO_nilobject);
else if (0 <= ref && ref < L->refSize &&
(L->refArray[ref].st == LOCK || L->refArray[ref].st == HOLD))
return luaA_putluaObject(L, &L->refArray[ref].o);
else
return LUA_NOOBJECT;
}
void lua_beginblock (lua_State *L) {
luaM_growvector(L, L->Cblocks, L->numCblocks, 1, struct C_Lua_Stack,
"too many nested blocks", L->stacksize);
L->Cblocks[L->numCblocks] = L->Cstack;
L->numCblocks++;
}
void lua_endblock (lua_State *L) {
if (L->numCblocks <= 0)
lua_error(L, "Lua API error - no block to end");
--L->numCblocks;
L->Cstack = L->Cblocks[L->numCblocks];
L->top = L->Cstack.base;
}
static int ismarked (const TObject *o) {
/* valid only for locked objects */
switch (o->ttype) {
case TAG_STRING: case TAG_USERDATA:
return o->value.ts->marked;
case TAG_TABLE:
return o->value.a->marked;
case TAG_LCLOSURE: case TAG_CCLOSURE:
return o->value.cl->marked;
default: /* number */
return 1;
}
}
/* for internal debugging only; check if a link of free refs is valid */
#define VALIDLINK(L, st,n) (NONEXT <= (st) && (st) < (n))
void luaR_invalidaterefs (lua_State *L) {
int n = L->refSize;
int i;
for (i=0; i<n; i++) {
struct Ref *r = &L->refArray[i];
if (r->st == HOLD && !ismarked(&r->o))
r->st = COLLECTED;
LUA_ASSERT(L, (r->st == LOCK && ismarked(&r->o)) ||
r->st == COLLECTED ||
r->st == NONEXT ||
(r->st < n && VALIDLINK(L, L->refArray[r->st].st, n)),
"inconsistent ref table");
}
LUA_ASSERT(L, VALIDLINK(L, L->refFree, n), "inconsistent ref table");
}

27
lref.h Normal file
View File

@@ -0,0 +1,27 @@
/*
** $Id: lref.h,v 1.5 1999/12/27 17:33:22 roberto Exp roberto $
** reference mechanism
** See Copyright Notice in lua.h
*/
#ifndef lref_h
#define lref_h
#include "lobject.h"
#define NONEXT -1 /* to end the free list */
#define HOLD -2
#define COLLECTED -3
#define LOCK -4
struct Ref {
TObject o;
int st; /* can be LOCK, HOLD, COLLECTED, or next (for free list) */
};
void luaR_invalidaterefs (lua_State *L);
#endif

132
lstate.c
View File

@@ -1,86 +1,108 @@
/*
** $Id: lstate.c,v 1.5 1997/12/17 20:48:58 roberto Exp roberto $
** $Id: lstate.c,v 1.24 2000/01/13 16:30:47 roberto Exp roberto $
** Global State
** See Copyright Notice in lua.h
*/
#include <stdarg.h>
#define LUA_REENTRANT
#include "lauxlib.h"
#include "lbuiltin.h"
#include "ldo.h"
#include "lfunc.h"
#include "lgc.h"
#include "llex.h"
#include "lmem.h"
#include "lref.h"
#include "lstate.h"
#include "lstring.h"
#include "ltable.h"
#include "ltm.h"
lua_State *lua_state = NULL;
void lua_open (void)
{
if (lua_state) return;
lua_state = luaM_new(lua_State);
L->numCblocks = 0;
L->Cstack.base = 0;
L->Cstack.lua2C = 0;
L->Cstack.num = 0;
static lua_State *newstate_aux (int stacksize, int put_builtin) {
lua_State *L = luaM_new(NULL, lua_State);
L->errorJmp = NULL;
L->rootproto.next = NULL;
L->rootproto.marked = 0;
L->rootcl.next = NULL;
L->rootcl.marked = 0;
L->rootglobal.next = NULL;
L->rootglobal.marked = 0;
L->roottable.next = NULL;
L->roottable.marked = 0;
L->refArray = NULL;
L->refSize = 0;
L->Mbuffer = NULL;
L->Mbuffbase = 0;
L->Mbuffsize = 0;
L->Mbuffnext = 0;
L->Mbuffbase = NULL;
L->Mbuffer = NULL;
L->GCthreshold = GARBAGE_BLOCK;
L->Cblocks = NULL;
L->numCblocks = 0;
L->rootproto = NULL;
L->rootcl = NULL;
L->rootglobal = NULL;
L->roottable = NULL;
L->IMtable = NULL;
L->refArray = NULL;
L->refSize = 0;
L->refFree = NONEXT;
L->nblocks = 0;
luaD_init();
luaS_init();
luaX_init();
luaT_init();
luaB_predefine();
L->GCthreshold = MAX_INT; /* to avoid GC during pre-definitions */
L->debug = 0;
L->callhook = NULL;
L->linehook = NULL;
L->allowhooks = 1;
luaD_init(L, stacksize);
luaS_init(L);
luaX_init(L);
luaT_init(L);
if (put_builtin)
luaB_predefine(L);
L->GCthreshold = L->nblocks*4;
return L;
}
void lua_close (void)
{
TaggedString *alludata = luaS_collectudata();
L->GCthreshold = MAX_INT; /* to avoid GC during GC */
luaC_hashcallIM((Hash *)L->roottable.next); /* GC t.methods for tables */
luaC_strcallIM(alludata); /* GC tag methods for userdata */
luaD_gcIM(&luaO_nilobject); /* GC tag method for nil (signal end of GC) */
luaH_free((Hash *)L->roottable.next);
luaF_freeproto((TProtoFunc *)L->rootproto.next);
luaF_freeclosure((Closure *)L->rootcl.next);
luaS_free(alludata);
luaS_freeall();
luaM_free(L->stack.stack);
luaM_free(L->IMtable);
luaM_free(L->refArray);
luaM_free(L->Mbuffer);
luaM_free(L);
L = NULL;
#ifdef DEBUG
printf("total de blocos: %ld\n", numblocks);
printf("total de memoria: %ld\n", totalmem);
#endif
lua_State *lua_newstate (const char *s, ...) {
static const char *const ops[] = {"stack", "builtin", NULL};
va_list ap;
int stacksize = DEFAULT_STACK_SIZE;
int put_builtin = 1;
va_start(ap, s);
while (s) {
switch (luaL_findstring(s, ops)) {
case 0: /* stack */
stacksize = va_arg(ap, int);
break;
case 1: /* builtin */
put_builtin = va_arg(ap, int);
break;
default: /* invalid argument */
va_end(ap);
return NULL;
}
s = va_arg(ap, const char *);
}
va_end(ap);
return newstate_aux(stacksize, put_builtin);
}
lua_State *lua_setstate (lua_State *st) {
lua_State *old = lua_state;
lua_state = st;
return old;
void lua_close (lua_State *L) {
luaC_collect(L, 1); /* collect all elements */
LUA_ASSERT(L, L->rootproto == NULL, "list should be empty");
LUA_ASSERT(L, L->rootcl == NULL, "list should be empty");
LUA_ASSERT(L, L->rootglobal == NULL, "list should be empty");
LUA_ASSERT(L, L->roottable == NULL, "list should be empty");
luaS_freeall(L);
luaM_free(L, L->stack);
luaM_free(L, L->IMtable);
luaM_free(L, L->refArray);
luaM_free(L, L->Mbuffer);
luaM_free(L, L->Cblocks);
LUA_ASSERT(L, L->numCblocks == 0, "Cblocks still open");
LUA_ASSERT(L, L->nblocks == 0, "wrong count for nblocks");
LUA_ASSERT(L, L->Cstack.base == L->top, "C2Lua not empty");
luaM_free(L, L);
if (L == lua_state) {
LUA_ASSERT(L, memdebug_numblocks == 0, "memory leak!");
LUA_ASSERT(L, memdebug_total == 0,"memory leak!");
lua_state = NULL;
}
}

View File

@@ -1,5 +1,5 @@
/*
** $Id: lstate.h,v 1.10 1998/06/19 16:14:09 roberto Exp roberto $
** $Id: lstate.h,v 1.30 2000/03/10 18:37:44 roberto Exp roberto $
** Global State
** See Copyright Notice in lua.h
*/
@@ -11,76 +11,79 @@
#include "lobject.h"
#include "lua.h"
#include "luadebug.h"
#define MAX_C_BLOCKS 10
#define GARBAGE_BLOCK 150
typedef TObject *StkId; /* index to stack elements */
typedef int StkId; /* index to stack elements */
struct Stack {
TObject *top;
TObject *stack;
TObject *last;
/*
** `jmp_buf' may be an array, so it is better to make sure it has an
** address (and not that it *is* an address...)
*/
struct lua_longjmp {
jmp_buf b;
};
/*
** stack layout for C point of view:
** [lua2C, lua2C+num) - `array' lua2C
** [lua2C+num, base) - space for extra lua_Objects (limbo)
** [base, L->top) - `stack' C2Lua
*/
struct C_Lua_Stack {
StkId base; /* when Lua calls C or C calls Lua, points to */
/* the first slot after the last parameter. */
StkId lua2C; /* points to first element of "array" lua2C */
int num; /* size of "array" lua2C */
StkId base;
StkId lua2C;
int num;
};
typedef struct {
typedef struct stringtable {
int size;
int nuse; /* number of elements (including EMPTYs) */
TaggedString **hash;
TString **hash;
} stringtable;
enum Status {LOCK, HOLD, FREE, COLLECTED};
struct ref {
TObject o;
enum Status status;
};
struct lua_State {
/* thread-specific state */
struct Stack stack; /* Lua stack */
StkId top; /* first free slot in the stack */
StkId stack; /* stack base */
StkId stack_last; /* last free slot in the stack */
int stacksize;
struct C_Lua_Stack Cstack; /* C2lua struct */
jmp_buf *errorJmp; /* current error recover point */
struct lua_longjmp *errorJmp; /* current error recover point */
char *Mbuffer; /* global buffer */
char *Mbuffbase; /* current first position of Mbuffer */
int Mbuffbase; /* current first position of Mbuffer */
int Mbuffsize; /* size of Mbuffer */
int Mbuffnext; /* next position to fill in Mbuffer */
struct C_Lua_Stack Cblocks[MAX_C_BLOCKS];
struct C_Lua_Stack *Cblocks;
int numCblocks; /* number of nested Cblocks */
/* global state */
TObject errorim; /* error tag method */
GCnode rootproto; /* list of all prototypes */
GCnode rootcl; /* list of all closures */
GCnode roottable; /* list of all tables */
GCnode rootglobal; /* list of strings with global values */
Proto *rootproto; /* list of all prototypes */
Closure *rootcl; /* list of all closures */
Hash *roottable; /* list of all tables */
GlobalVar *rootglobal; /* list of global variables */
stringtable *string_root; /* array of hash tables for strings and udata */
struct IM *IMtable; /* table for tag methods */
int IMtable_size; /* size of IMtable */
int last_tag; /* last used tag in IMtable */
struct ref *refArray; /* locked objects */
struct Ref *refArray; /* locked objects */
int refSize; /* size of refArray */
int refFree; /* list of free positions in refArray */
unsigned long GCthreshold;
unsigned long nblocks; /* number of 'blocks' currently allocated */
unsigned long nblocks; /* number of `blocks' currently allocated */
int debug;
lua_Hook callhook;
lua_Hook linehook;
int allowhooks;
};
extern lua_State *lua_state;
#define L lua_state
#endif

360
lstring.c
View File

@@ -1,5 +1,5 @@
/*
** $Id: lstring.c,v 1.12 1998/03/06 16:54:42 roberto Exp roberto $
** $Id: lstring.c,v 1.33 2000/03/10 14:38:10 roberto Exp roberto $
** String table (keeps all strings handled by Lua)
** See Copyright Notice in lua.h
*/
@@ -7,6 +7,8 @@
#include <string.h>
#define LUA_REENTRANT
#include "lmem.h"
#include "lobject.h"
#include "lstate.h"
@@ -14,300 +16,190 @@
#include "lua.h"
#define NUM_HASHS 61
#define gcsizestring(l) (1+(l/64)) /* "weight" for a string with length 'l' */
#define gcsizestring(L, l) numblocks(L, 0, sizeof(TString)+l)
#define gcsizeudata gcsizestring(L, 0)
static TaggedString EMPTY = {{NULL, 2}, 0L, 0,
{{{LUA_T_NIL, {NULL}}, 0L}}, {0}};
void luaS_init (void)
{
void luaS_init (lua_State *L) {
int i;
L->string_root = luaM_newvector(NUM_HASHS, stringtable);
L->string_root = luaM_newvector(L, NUM_HASHS, stringtable);
for (i=0; i<NUM_HASHS; i++) {
L->string_root[i].size = 0;
L->string_root[i].size = 1;
L->string_root[i].nuse = 0;
L->string_root[i].hash = NULL;
L->string_root[i].hash = luaM_newvector(L, 1, TString *);;
L->string_root[i].hash[0] = NULL;
}
}
static unsigned long hash_s (char *s, long l)
{
unsigned long h = 0;
while (l--)
h = ((h<<5)-h)^(unsigned char)*(s++);
void luaS_freeall (lua_State *L) {
int i;
for (i=0; i<NUM_HASHS; i++) {
LUA_ASSERT(L, L->string_root[i].nuse==0, "non-empty string table");
luaM_free(L, L->string_root[i].hash);
}
luaM_free(L, L->string_root);
}
static unsigned long hash_s (const char *s, long l) {
unsigned long h = l; /* seed */
long step = (l>>6)+1; /* if string is too long, don't hash all its chars */
for (; l>0; l-=step)
h = h ^ ((h<<5)+(h>>2)+(unsigned char)*(s++));
return h;
}
static int newsize (stringtable *tb)
{
int size = tb->size;
int realuse = 0;
int i;
/* count how many entries are really in use */
for (i=0; i<size; i++)
if (tb->hash[i] != NULL && tb->hash[i] != &EMPTY)
realuse++;
if (2*(realuse+1) <= size) /* +1 is the new element */
return size; /* don't need to grow, just rehash to clear EMPTYs */
else
return luaO_redimension(size);
}
static void grow (stringtable *tb)
{
int ns = newsize(tb);
TaggedString **newhash = luaM_newvector(ns, TaggedString *);
void luaS_resize (lua_State *L, stringtable *tb, int newsize) {
TString **newhash = luaM_newvector(L, newsize, TString *);
int i;
for (i=0; i<ns; i++)
newhash[i] = NULL;
for (i=0; i<newsize; i++) newhash[i] = NULL;
/* rehash */
tb->nuse = 0;
for (i=0; i<tb->size; i++) {
if (tb->hash[i] != NULL && tb->hash[i] != &EMPTY) {
int h = tb->hash[i]->hash%ns;
while (newhash[h])
h = (h+1)%ns;
newhash[h] = tb->hash[i];
tb->nuse++;
TString *p = tb->hash[i];
while (p) { /* for each node in the list */
TString *next = p->nexthash; /* save next */
int h = p->hash&(newsize-1); /* new position */
LUA_ASSERT(L, p->hash%newsize == (p->hash&(newsize-1)),
"a&(x-1) == a%x, for x power of 2");
p->nexthash = newhash[h]; /* chain it in new position */
newhash[h] = p;
p = next;
}
}
luaM_free(tb->hash);
tb->size = ns;
luaM_free(L, tb->hash);
tb->size = newsize;
tb->hash = newhash;
}
static TaggedString *newone_s (char *str, long l, unsigned long h)
{
TaggedString *ts = (TaggedString *)luaM_malloc(sizeof(TaggedString)+l);
static TString *newone (lua_State *L, long l, unsigned long h) {
TString *ts = (TString *)luaM_malloc(L,
sizeof(TString)+l*sizeof(char));
ts->marked = 0;
ts->nexthash = NULL;
ts->hash = h;
return ts;
}
static TString *newone_s (lua_State *L, const char *str,
long l, unsigned long h) {
TString *ts = newone(L, l, h);
memcpy(ts->str, str, l);
ts->str[l] = 0; /* ending 0 */
ts->u.s.globalval.ttype = LUA_T_NIL; /* initialize global value */
ts->u.s.gv = NULL; /* no global value */
ts->u.s.len = l;
ts->constindex = 0;
L->nblocks += gcsizestring(l);
ts->head.marked = 0;
ts->head.next = (GCnode *)ts; /* signal it is in no list */
ts->hash = h;
L->nblocks += gcsizestring(L, l);
return ts;
}
static TaggedString *newone_u (char *buff, int tag, unsigned long h)
{
TaggedString *ts = luaM_new(TaggedString);
ts->u.d.v = buff;
static TString *newone_u (lua_State *L, void *buff,
int tag, unsigned long h) {
TString *ts = newone(L, 0, h);
ts->u.d.value = buff;
ts->u.d.tag = (tag == LUA_ANYTAG) ? 0 : tag;
ts->constindex = -1; /* tag -> this is a userdata */
L->nblocks++;
ts->head.marked = 0;
ts->head.next = (GCnode *)ts; /* signal it is in no list */
ts->hash = h;
L->nblocks += gcsizeudata;
return ts;
}
static TaggedString *insert_s (char *str, long l, stringtable *tb)
{
TaggedString *ts;
static void newentry (lua_State *L, stringtable *tb, TString *ts, int h) {
ts->nexthash = tb->hash[h]; /* chain new entry */
tb->hash[h] = ts;
tb->nuse++;
if (tb->nuse > tb->size) /* too crowded? */
luaS_resize(L, tb, tb->size*2);
}
TString *luaS_newlstr (lua_State *L, const char *str, long l) {
unsigned long h = hash_s(str, l);
int size = tb->size;
int i;
int j = -1;
if ((long)tb->nuse*3 >= (long)size*2) {
grow(tb);
size = tb->size;
}
for (i = h%size; (ts = tb->hash[i]) != NULL; ) {
if (ts == &EMPTY)
j = i;
else if (ts->constindex >= 0 &&
ts->u.s.len == l &&
(memcmp(str, ts->str, l) == 0))
stringtable *tb = &L->string_root[(l==0) ? 0 :
((unsigned int)(str[0]+str[l-1]))&(NUM_HASHSTR-1)];
int h1 = h&(tb->size-1);
TString *ts;
for (ts = tb->hash[h1]; ts; ts = ts->nexthash) {
if (ts->u.s.len == l && (memcmp(str, ts->str, l) == 0))
return ts;
if (++i == size) i=0;
}
/* not found */
if (j != -1) /* is there an EMPTY space? */
i = j;
else
tb->nuse++;
ts = tb->hash[i] = newone_s(str, l, h);
ts = newone_s(L, str, l, h); /* create new entry */
newentry(L, tb, ts, h1); /* insert it on table */
return ts;
}
static TaggedString *insert_u (void *buff, int tag, stringtable *tb)
{
TaggedString *ts;
unsigned long h = (unsigned long)buff;
int size = tb->size;
int i;
int j = -1;
if ((long)tb->nuse*3 >= (long)size*2) {
grow(tb);
size = tb->size;
}
for (i = h%size; (ts = tb->hash[i]) != NULL; ) {
if (ts == &EMPTY)
j = i;
else if (ts->constindex < 0 && /* is a udata? */
(tag == ts->u.d.tag || tag == LUA_ANYTAG) &&
buff == ts->u.d.v)
return ts;
if (++i == size) i=0;
}
/* not found */
if (j != -1) /* is there an EMPTY space? */
i = j;
else
tb->nuse++;
ts = tb->hash[i] = newone_u(buff, tag, h);
return ts;
}
TaggedString *luaS_createudata (void *udata, int tag)
{
return insert_u(udata, tag, &L->string_root[(unsigned)udata%NUM_HASHS]);
}
TaggedString *luaS_newlstr (char *str, long l)
{
int i = (l==0)?0:(unsigned char)str[0];
return insert_s(str, l, &L->string_root[i%NUM_HASHS]);
}
TaggedString *luaS_new (char *str)
{
return luaS_newlstr(str, strlen(str));
}
TaggedString *luaS_newfixedstring (char *str)
{
TaggedString *ts = luaS_new(str);
if (ts->head.marked == 0)
ts->head.marked = 2; /* avoid GC */
return ts;
}
void luaS_free (TaggedString *l)
{
while (l) {
TaggedString *next = (TaggedString *)l->head.next;
L->nblocks -= (l->constindex == -1) ? 1 : gcsizestring(l->u.s.len);
luaM_free(l);
l = next;
}
}
/*
** Garbage collection functions.
** uses '%' for one hashing with userdata because addresses are too regular,
** so two '&' operations would be highly correlated
*/
static void remove_from_list (GCnode *l)
{
while (l) {
GCnode *next = l->next;
while (next && !next->marked)
next = l->next = next->next;
l = next;
TString *luaS_createudata (lua_State *L, void *udata, int tag) {
unsigned long h = IntPoint(L, udata);
stringtable *tb = &L->string_root[(h%NUM_HASHUDATA)+NUM_HASHSTR];
int h1 = h&(tb->size-1);
TString *ts;
for (ts = tb->hash[h1]; ts; ts = ts->nexthash) {
if (udata == ts->u.d.value && (tag == ts->u.d.tag || tag == LUA_ANYTAG))
return ts;
}
/* not found */
ts = newone_u(L, udata, tag, h);
newentry(L, tb, ts, h1);
return ts;
}
TaggedString *luaS_collector (void)
{
TaggedString *frees = NULL;
int i;
remove_from_list(&(L->rootglobal));
for (i=0; i<NUM_HASHS; i++) {
stringtable *tb = &L->string_root[i];
int j;
for (j=0; j<tb->size; j++) {
TaggedString *t = tb->hash[j];
if (t == NULL) continue;
if (t->head.marked == 1)
t->head.marked = 0;
else if (!t->head.marked) {
t->head.next = (GCnode *)frees;
frees = t;
tb->hash[j] = &EMPTY;
}
}
TString *luaS_new (lua_State *L, const char *str) {
return luaS_newlstr(L, str, strlen(str));
}
TString *luaS_newfixed (lua_State *L, const char *str) {
TString *ts = luaS_new(L, str);
if (ts->marked == 0) ts->marked = FIXMARK; /* avoid GC */
return ts;
}
void luaS_free (lua_State *L, TString *t) {
if (t->constindex == -1) /* is userdata? */
L->nblocks -= gcsizeudata;
else { /* is string */
L->nblocks -= gcsizestring(L, t->u.s.len);
luaM_free(L, t->u.s.gv);
}
return frees;
luaM_free(L, t);
}
TaggedString *luaS_collectudata (void)
{
TaggedString *frees = NULL;
int i;
L->rootglobal.next = NULL; /* empty list of globals */
for (i=0; i<NUM_HASHS; i++) {
stringtable *tb = &L->string_root[i];
int j;
for (j=0; j<tb->size; j++) {
TaggedString *t = tb->hash[j];
if (t == NULL || t == &EMPTY || t->constindex != -1)
continue; /* get only user data */
t->head.next = (GCnode *)frees;
frees = t;
tb->hash[j] = &EMPTY;
}
GlobalVar *luaS_assertglobal (lua_State *L, TString *ts) {
GlobalVar *gv = ts->u.s.gv;
if (!gv) { /* no global value yet? */
gv = luaM_new(L, GlobalVar);
gv->value.ttype = TAG_NIL; /* initial value */
gv->name = ts;
gv->next = L->rootglobal; /* chain in global list */
L->rootglobal = gv;
ts->u.s.gv = gv;
}
return frees;
return gv;
}
void luaS_freeall (void)
{
int i;
for (i=0; i<NUM_HASHS; i++) {
stringtable *tb = &L->string_root[i];
int j;
for (j=0; j<tb->size; j++) {
TaggedString *t = tb->hash[j];
if (t == &EMPTY) continue;
luaM_free(t);
}
luaM_free(tb->hash);
}
luaM_free(L->string_root);
GlobalVar *luaS_assertglobalbyname (lua_State *L, const char *name) {
return luaS_assertglobal(L, luaS_new(L, name));
}
void luaS_rawsetglobal (TaggedString *ts, TObject *newval)
{
ts->u.s.globalval = *newval;
if (ts->head.next == (GCnode *)ts) { /* is not in list? */
ts->head.next = L->rootglobal.next;
L->rootglobal.next = (GCnode *)ts;
}
int luaS_globaldefined (lua_State *L, const char *name) {
TString *ts = luaS_new(L, name);
return ts->u.s.gv && ts->u.s.gv->value.ttype != TAG_NIL;
}
char *luaS_travsymbol (int (*fn)(TObject *))
{
TaggedString *g;
for (g=(TaggedString *)L->rootglobal.next; g; g=(TaggedString *)g->head.next)
if (fn(&g->u.s.globalval))
return g->str;
return NULL;
}
int luaS_globaldefined (char *name)
{
TaggedString *ts = luaS_new(name);
return ts->u.s.globalval.ttype != LUA_T_NIL;
}

View File

@@ -1,5 +1,5 @@
/*
** $Id: lstring.h,v 1.6 1997/12/01 20:31:25 roberto Exp roberto $
** $Id: lstring.h,v 1.17 2000/03/10 14:38:10 roberto Exp roberto $
** String table (keep all strings handled by Lua)
** See Copyright Notice in lua.h
*/
@@ -9,20 +9,33 @@
#include "lobject.h"
#include "lstate.h"
void luaS_init (void);
TaggedString *luaS_createudata (void *udata, int tag);
TaggedString *luaS_collector (void);
void luaS_free (TaggedString *l);
TaggedString *luaS_newlstr (char *str, long l);
TaggedString *luaS_new (char *str);
TaggedString *luaS_newfixedstring (char *str);
void luaS_rawsetglobal (TaggedString *ts, TObject *newval);
char *luaS_travsymbol (int (*fn)(TObject *));
int luaS_globaldefined (char *name);
TaggedString *luaS_collectudata (void);
void luaS_freeall (void);
#define NUM_HASHSTR 32
#define NUM_HASHUDATA 31
#define NUM_HASHS (NUM_HASHSTR+NUM_HASHUDATA)
/*
** any taggedstring with mark>=FIXMARK is never collected.
** Marks>=RESERVEDMARK are used to identify reserved words.
*/
#define FIXMARK 2
#define RESERVEDMARK 3
void luaS_init (lua_State *L);
void luaS_resize (lua_State *L, stringtable *tb, int newsize);
TString *luaS_createudata (lua_State *L, void *udata, int tag);
void luaS_freeall (lua_State *L);
void luaS_free (lua_State *L, TString *ts);
TString *luaS_newlstr (lua_State *L, const char *str, long l);
TString *luaS_new (lua_State *L, const char *str);
TString *luaS_newfixed (lua_State *L, const char *str);
GlobalVar *luaS_assertglobal (lua_State *L, TString *ts);
GlobalVar *luaS_assertglobalbyname (lua_State *L, const char *name);
int luaS_globaldefined (lua_State *L, const char *name);
#endif

646
lstrlib.c
View File

@@ -1,6 +1,6 @@
/*
** $Id: lstrlib.c,v 1.17 1998/06/29 18:24:06 roberto Exp roberto $
** Standard library for strings and pattern-matching
** $Id: lstrlib.c,v 1.40 2000/02/08 16:34:31 roberto Exp roberto $
** Standard library for string operations and pattern-matching
** See Copyright Notice in lua.h
*/
@@ -10,166 +10,177 @@
#include <stdlib.h>
#include <string.h>
#define LUA_REENTRANT
#include "lauxlib.h"
#include "lua.h"
#include "lualib.h"
static void addnchar (char *s, int n)
{
char *b = luaL_openspace(n);
static void addnchar (lua_State *L, const char *s, int n) {
char *b = luaL_openspace(L, n);
memcpy(b, s, n);
luaL_addsize(n);
luaL_addsize(L, n);
}
static void str_len (void)
{
static void str_len (lua_State *L) {
long l;
luaL_check_lstr(1, &l);
lua_pushnumber(l);
luaL_check_lstr(L, 1, &l);
lua_pushnumber(L, l);
}
static void closeandpush (void)
{
lua_pushlstring(luaL_buffer(), luaL_getsize());
static void closeandpush (lua_State *L) {
lua_pushlstring(L, luaL_buffer(L), luaL_getsize(L));
}
static long posrelat (long pos, long len)
{
static long posrelat (long pos, long len) {
/* relative string position: negative means back from end */
return (pos>=0) ? pos : len+pos+1;
}
static void str_sub (void)
{
static void str_sub (lua_State *L) {
long l;
char *s = luaL_check_lstr(1, &l);
long start = posrelat(luaL_check_number(2), l);
long end = posrelat(luaL_opt_number(3, -1), l);
if (1 <= start && start <= end && end <= l)
lua_pushlstring(s+start-1, end-start+1);
else lua_pushstring("");
const char *s = luaL_check_lstr(L, 1, &l);
long start = posrelat(luaL_check_long(L, 2), l);
long end = posrelat(luaL_opt_long(L, 3, -1), l);
if (start < 1) start = 1;
if (end > l) end = l;
if (start <= end)
lua_pushlstring(L, s+start-1, end-start+1);
else lua_pushstring(L, "");
}
static void str_lower (void)
{
static void str_lower (lua_State *L) {
long l;
int i;
char *s = luaL_check_lstr(1, &l);
luaL_resetbuffer();
const char *s = luaL_check_lstr(L, 1, &l);
luaL_resetbuffer(L);
for (i=0; i<l; i++)
luaL_addchar(tolower((unsigned char)(s[i])));
closeandpush();
luaL_addchar(L, tolower((unsigned char)(s[i])));
closeandpush(L);
}
static void str_upper (void)
{
static void str_upper (lua_State *L) {
long l;
int i;
char *s = luaL_check_lstr(1, &l);
luaL_resetbuffer();
const char *s = luaL_check_lstr(L, 1, &l);
luaL_resetbuffer(L);
for (i=0; i<l; i++)
luaL_addchar(toupper((unsigned char)(s[i])));
closeandpush();
luaL_addchar(L, toupper((unsigned char)(s[i])));
closeandpush(L);
}
static void str_rep (void)
{
static void str_rep (lua_State *L) {
long l;
char *s = luaL_check_lstr(1, &l);
int n = (int)luaL_check_number(2);
luaL_resetbuffer();
const char *s = luaL_check_lstr(L, 1, &l);
int n = luaL_check_int(L, 2);
luaL_resetbuffer(L);
while (n-- > 0)
addnchar(s, l);
closeandpush();
addnchar(L, s, l);
closeandpush(L);
}
static void str_byte (void)
{
static void str_byte (lua_State *L) {
long l;
char *s = luaL_check_lstr(1, &l);
long pos = posrelat(luaL_opt_number(2, 1), l);
luaL_arg_check(0<pos && pos<=l, 2, "out of range");
lua_pushnumber((unsigned char)s[pos-1]);
const char *s = luaL_check_lstr(L, 1, &l);
long pos = posrelat(luaL_opt_long(L, 2, 1), l);
luaL_arg_check(L, 0<pos && pos<=l, 2, "out of range");
lua_pushnumber(L, (unsigned char)s[pos-1]);
}
static void str_char (void) {
static void str_char (lua_State *L) {
int i = 0;
luaL_resetbuffer();
while (lua_getparam(++i) != LUA_NOOBJECT) {
double c = luaL_check_number(i);
luaL_arg_check((unsigned char)c == c, i, "invalid value");
luaL_addchar((int)c);
luaL_resetbuffer(L);
while (lua_getparam(L, ++i) != LUA_NOOBJECT) {
int c = luaL_check_int(L, i);
luaL_arg_check(L, (unsigned char)c == c, i, "invalid value");
luaL_addchar(L, (unsigned char)c);
}
closeandpush();
closeandpush(L);
}
/*
** =======================================================
** {======================================================
** PATTERN MATCHING
** =======================================================
*/
#define MAX_CAPT 9
#ifndef MAX_CAPTURES
#define MAX_CAPTURES 32 /* arbitrary limit */
#endif
struct Capture {
const char *src_end; /* end ('\0') of source string */
int level; /* total number of captures (finished or unfinished) */
char *src_end; /* end ('\0') of source string */
struct {
char *init;
const char *init;
int len; /* -1 signals unfinished capture */
} capture[MAX_CAPT];
} capture[MAX_CAPTURES];
};
#define ESC '%'
#define SPECIALS "^$*?.([%-"
#define ESC '%'
#define SPECIALS "^$*+?.([%-"
static void push_captures (struct Capture *cap)
{
static void push_captures (lua_State *L, struct Capture *cap) {
int i;
for (i=0; i<cap->level; i++)
lua_pushlstring(cap->capture[i].init, cap->capture[i].len);
for (i=0; i<cap->level; i++) {
int l = cap->capture[i].len;
if (l == -1) lua_error(L, "unfinished capture");
lua_pushlstring(L, cap->capture[i].init, l);
}
}
static int check_cap (int l, struct Capture *cap)
{
static int check_capture (lua_State *L, int l, struct Capture *cap) {
l -= '1';
if (!(0 <= l && l < cap->level && cap->capture[l].len != -1))
lua_error("invalid capture index");
lua_error(L, "invalid capture index");
return l;
}
static int capture_to_close (struct Capture *cap)
{
static int capture_to_close (lua_State *L, struct Capture *cap) {
int level = cap->level;
for (level--; level>=0; level--)
if (cap->capture[level].len == -1) return level;
lua_error("invalid pattern capture");
lua_error(L, "invalid pattern capture");
return 0; /* to avoid warnings */
}
static char *bracket_end (char *p)
{
return (*p == 0) ? NULL : strchr((*p=='^') ? p+2 : p+1, ']');
const char *luaI_classend (lua_State *L, const char *p) {
switch (*p++) {
case ESC:
if (*p == '\0') lua_error(L, "malformed pattern (ends with `%')");
return p+1;
case '[':
if (*p == '^') p++;
do { /* look for a ']' */
if (*p == '\0') lua_error(L, "malformed pattern (missing `]')");
if (*(p++) == ESC && *p != '\0') p++; /* skip escapes (e.g. '%]') */
} while (*p != ']');
return p+1;
default:
return p;
}
}
static int matchclass (int c, int cl)
{
static int match_class (int c, int cl) {
int res;
switch (tolower(cl)) {
case 'a' : res = isalpha(c); break;
@@ -180,57 +191,64 @@ static int matchclass (int c, int cl)
case 's' : res = isspace(c); break;
case 'u' : res = isupper(c); break;
case 'w' : res = isalnum(c); break;
case 'x' : res = isxdigit(c); break;
case 'z' : res = (c == '\0'); break;
default: return (cl == c);
}
return (islower((unsigned char)cl) ? res : !res);
return (islower(cl) ? res : !res);
}
int luaI_singlematch (int c, char *p, char **ep)
{
static int matchbracketclass (int c, const char *p, const char *endclass) {
int sig = 1;
if (*(p+1) == '^') {
sig = 0;
p++; /* skip the '^' */
}
while (++p < endclass) {
if (*p == ESC) {
p++;
if (match_class(c, (unsigned char)*p))
return sig;
}
else if ((*(p+1) == '-') && (p+2 < endclass)) {
p+=2;
if ((int)(unsigned char)*(p-2) <= c && c <= (int)(unsigned char)*p)
return sig;
}
else if ((int)(unsigned char)*p == c) return sig;
}
return !sig;
}
int luaI_singlematch (int c, const char *p, const char *ep) {
switch (*p) {
case '.': /* matches any char */
*ep = p+1;
return 1;
case '\0': /* end of pattern; matches nothing */
*ep = p;
return 0;
case ESC:
if (*(++p) == '\0')
luaL_verror("incorrect pattern (ends with `%c')", ESC);
*ep = p+1;
return matchclass(c, (unsigned char)*p);
case '[': {
char *end = bracket_end(p+1);
int sig = *(p+1) == '^' ? (p++, 0) : 1;
if (end == NULL) lua_error("incorrect pattern (missing `]')");
*ep = end+1;
while (++p < end) {
if (*p == ESC) {
if (((p+1) < end) && matchclass(c, (unsigned char)*++p))
return sig;
}
else if ((*(p+1) == '-') && (p+2 < end)) {
p+=2;
if ((unsigned char)*(p-2) <= c && c <= (unsigned char)*p)
return sig;
}
else if ((unsigned char)*p == c) return sig;
}
return !sig;
}
return match_class(c, (unsigned char)*(p+1));
case '[':
return matchbracketclass(c, p, ep-1);
default:
*ep = p+1;
return ((unsigned char)*p == c);
}
}
static char *matchbalance (char *s, int b, int e, struct Capture *cap)
{
if (*s != b) return NULL;
static const char *match (lua_State *L, const char *s, const char *p, struct Capture *cap);
static const char *matchbalance (lua_State *L, const char *s, const char *p,
struct Capture *cap) {
if (*p == 0 || *(p+1) == 0)
lua_error(L, "unbalanced pattern");
if (*s != *p) return NULL;
else {
int b = *p;
int e = *(p+1);
int cont = 1;
while (++s < cap->src_end) {
if (*s == e) {
@@ -243,147 +261,191 @@ static char *matchbalance (char *s, int b, int e, struct Capture *cap)
}
static char *matchitem (char *s, char *p, struct Capture *cap, char **ep)
{
if (*p == ESC) {
p++;
if (isdigit((unsigned char)*p)) { /* capture */
int l = check_cap(*p, cap);
int len = cap->capture[l].len;
*ep = p+1;
if (cap->src_end-s >= len && memcmp(cap->capture[l].init, s, len) == 0)
return s+len;
else return NULL;
}
else if (*p == 'b') { /* balanced string */
p++;
if (*p == 0 || *(p+1) == 0)
lua_error("unbalanced pattern");
*ep = p+2;
return matchbalance(s, *p, *(p+1), cap);
}
else p--; /* and go through */
static const char *max_expand (lua_State *L, const char *s, const char *p, const char *ep,
struct Capture *cap) {
int i = 0; /* counts maximum expand for item */
while ((s+i)<cap->src_end && luaI_singlematch((unsigned char)*(s+i), p, ep))
i++;
/* keeps trying to match mith the maximum repetitions */
while (i>=0) {
const char *res = match(L, (s+i), ep+1, cap);
if (res) return res;
i--; /* else didn't match; reduce 1 repetition to try again */
}
/* "luaI_singlematch" sets "ep" (so must be called even when *s == 0) */
return (luaI_singlematch((unsigned char)*s, p, ep) && s<cap->src_end) ?
s+1 : NULL;
return NULL;
}
static char *match (char *s, char *p, struct Capture *cap)
{
static const char *min_expand (lua_State *L, const char *s, const char *p, const char *ep,
struct Capture *cap) {
for (;;) {
const char *res = match(L, s, ep+1, cap);
if (res != NULL)
return res;
else if (s<cap->src_end && luaI_singlematch((unsigned char)*s, p, ep))
s++; /* try with one more repetition */
else return NULL;
}
}
static const char *start_capture (lua_State *L, const char *s, const char *p,
struct Capture *cap) {
const char *res;
int level = cap->level;
if (level >= MAX_CAPTURES) lua_error(L, "too many captures");
cap->capture[level].init = s;
cap->capture[level].len = -1;
cap->level = level+1;
if ((res=match(L, s, p+1, cap)) == NULL) /* match failed? */
cap->level--; /* undo capture */
return res;
}
static const char *end_capture (lua_State *L, const char *s, const char *p,
struct Capture *cap) {
int l = capture_to_close(L, cap);
const char *res;
cap->capture[l].len = s - cap->capture[l].init; /* close capture */
if ((res = match(L, s, p+1, cap)) == NULL) /* match failed? */
cap->capture[l].len = -1; /* undo capture */
return res;
}
static const char *match_capture (lua_State *L, const char *s, int level,
struct Capture *cap) {
int l = check_capture(L, level, cap);
int len = cap->capture[l].len;
if (cap->src_end-s >= len &&
memcmp(cap->capture[l].init, s, len) == 0)
return s+len;
else return NULL;
}
static const char *match (lua_State *L, const char *s, const char *p, struct Capture *cap) {
init: /* using goto's to optimize tail recursion */
switch (*p) {
case '(': { /* start capture */
char *res;
if (cap->level >= MAX_CAPT) lua_error("too many captures");
cap->capture[cap->level].init = s;
cap->capture[cap->level].len = -1;
cap->level++;
if ((res=match(s, p+1, cap)) == NULL) /* match failed? */
cap->level--; /* undo capture */
return res;
}
case ')': { /* end capture */
int l = capture_to_close(cap);
char *res;
cap->capture[l].len = s - cap->capture[l].init; /* close capture */
if ((res = match(s, p+1, cap)) == NULL) /* match failed? */
cap->capture[l].len = -1; /* undo capture */
return res;
}
case '\0': case '$': /* (possibly) end of pattern */
if (*p == 0 || (*(p+1) == 0 && s == cap->src_end))
return s;
/* else go through */
default: { /* it is a pattern item */
char *ep; /* get what is next */
char *s1 = matchitem(s, p, cap, &ep);
case '(': /* start capture */
return start_capture(L, s, p, cap);
case ')': /* end capture */
return end_capture(L, s, p, cap);
case ESC: /* may be %[0-9] or %b */
if (isdigit((unsigned char)(*(p+1)))) { /* capture? */
s = match_capture(L, s, *(p+1), cap);
if (s == NULL) return NULL;
p+=2; goto init; /* else return match(L, s, p+2, cap) */
}
else if (*(p+1) == 'b') { /* balanced string? */
s = matchbalance(L, s, p+2, cap);
if (s == NULL) return NULL;
p+=4; goto init; /* else return match(L, s, p+4, cap); */
}
else goto dflt; /* case default */
case '\0': /* end of pattern */
return s; /* match succeeded */
case '$':
if (*(p+1) == '\0') /* is the '$' the last char in pattern? */
return (s == cap->src_end) ? s : NULL; /* check end of string */
else goto dflt;
default: dflt: { /* it is a pattern item */
const char *ep = luaI_classend(L, p); /* points to what is next */
int m = s<cap->src_end && luaI_singlematch((unsigned char)*s, p, ep);
switch (*ep) {
case '*': { /* repetition */
char *res;
if (s1 && s1>s && ((res=match(s1, p, cap)) != NULL))
return res;
p=ep+1; goto init; /* else return match(s, ep+1, cap); */
}
case '?': { /* optional */
char *res;
if (s1 && ((res=match(s1, ep+1, cap)) != NULL))
const char *res;
if (m && ((res=match(L, s+1, ep+1, cap)) != NULL))
return res;
p=ep+1; goto init; /* else return match(s, ep+1, cap); */
}
case '-': { /* repetition */
char *res;
if ((res = match(s, ep+1, cap)) != NULL)
return res;
else if (s1 && s1>s) {
s = s1;
goto init; /* return match(s1, p, cap); */
}
else
return NULL;
p=ep+1; goto init; /* else return match(L, s, ep+1, cap); */
}
case '*': /* 0 or more repetitions */
return max_expand(L, s, p, ep, cap);
case '+': /* 1 or more repetitions */
return (m ? max_expand(L, s+1, p, ep, cap) : NULL);
case '-': /* 0 or more repetitions (minimum) */
return min_expand(L, s, p, ep, cap);
default:
if (s1) { s=s1; p=ep; goto init; } /* return match(s1, ep, cap); */
else return NULL;
if (!m) return NULL;
s++; p=ep; goto init; /* else return match(L, s+1, ep, cap); */
}
}
}
}
static void str_find (void)
{
long l;
char *s = luaL_check_lstr(1, &l);
char *p = luaL_check_string(2);
long init = posrelat(luaL_opt_number(3, 1), l) - 1;
static const char *memfind (const char *s1, long l1, const char *s2, long l2) {
if (l2 == 0) return s1; /* empty strings are everywhere ;-) */
else {
const char *init; /* to search for a `*s2' inside `s1' */
l2--; /* 1st char will be checked by `memchr' */
l1 = l1-l2; /* `s2' cannot be found after that */
while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
init++; /* 1st char is already checked */
if (memcmp(init, s2+1, l2) == 0)
return init-1;
else { /* correct `l1' and `s1' to try again */
l1 -= init-s1;
s1 = init;
}
}
return NULL; /* not found */
}
}
static void str_find (lua_State *L) {
long l1, l2;
const char *s = luaL_check_lstr(L, 1, &l1);
const char *p = luaL_check_lstr(L, 2, &l2);
long init = posrelat(luaL_opt_long(L, 3, 1), l1) - 1;
struct Capture cap;
luaL_arg_check(0 <= init && init <= l, 3, "out of range");
if (lua_getparam(4) != LUA_NOOBJECT ||
luaL_arg_check(L, 0 <= init && init <= l1, 3, "out of range");
if (lua_getparam(L, 4) != LUA_NOOBJECT ||
strpbrk(p, SPECIALS) == NULL) { /* no special characters? */
char *s2 = strstr(s+init, p);
const char *s2 = memfind(s+init, l1, p, l2);
if (s2) {
lua_pushnumber(s2-s+1);
lua_pushnumber(s2-s+strlen(p));
lua_pushnumber(L, s2-s+1);
lua_pushnumber(L, s2-s+l2);
return;
}
}
else {
int anchor = (*p == '^') ? (p++, 1) : 0;
char *s1=s+init;
cap.src_end = s+l;
const char *s1=s+init;
cap.src_end = s+l1;
do {
char *res;
const char *res;
cap.level = 0;
if ((res=match(s1, p, &cap)) != NULL) {
lua_pushnumber(s1-s+1); /* start */
lua_pushnumber(res-s); /* end */
push_captures(&cap);
if ((res=match(L, s1, p, &cap)) != NULL) {
lua_pushnumber(L, s1-s+1); /* start */
lua_pushnumber(L, res-s); /* end */
push_captures(L, &cap);
return;
}
} while (s1++<cap.src_end && !anchor);
}
lua_pushnil(); /* if arrives here, it didn't find */
lua_pushnil(L); /* not found */
}
static void add_s (lua_Object newp, struct Capture *cap)
{
if (lua_isstring(newp)) {
char *news = lua_getstring(newp);
int l = lua_strlen(newp);
static void add_s (lua_State *L, lua_Object newp, struct Capture *cap) {
if (lua_isstring(L, newp)) {
const char *news = lua_getstring(L, newp);
int l = lua_strlen(L, newp);
int i;
for (i=0; i<l; i++) {
if (news[i] != ESC)
luaL_addchar(news[i]);
luaL_addchar(L, news[i]);
else {
i++; /* skip ESC */
if (!isdigit((unsigned char)news[i]))
luaL_addchar(news[i]);
luaL_addchar(L, news[i]);
else {
int level = check_cap(news[i], cap);
addnchar(cap->capture[level].init, cap->capture[level].len);
int level = check_capture(L, news[i], cap);
addnchar(L, cap->capture[level].init, cap->capture[level].len);
}
}
}
@@ -392,139 +454,156 @@ static void add_s (lua_Object newp, struct Capture *cap)
lua_Object res;
int status;
int oldbuff;
lua_beginblock();
push_captures(cap);
lua_beginblock(L);
push_captures(L, cap);
/* function may use buffer, so save it and create a new one */
oldbuff = luaL_newbuffer(0);
status = lua_callfunction(newp);
oldbuff = luaL_newbuffer(L, 0);
status = lua_callfunction(L, newp);
/* restore old buffer */
luaL_oldbuffer(oldbuff);
luaL_oldbuffer(L, oldbuff);
if (status != 0) {
lua_endblock();
lua_error(NULL);
lua_endblock(L);
lua_error(L, NULL);
}
res = lua_getresult(1);
if (lua_isstring(res))
addnchar(lua_getstring(res), lua_strlen(res));
lua_endblock();
res = lua_getresult(L, 1);
if (lua_isstring(L, res))
addnchar(L, lua_getstring(L, res), lua_strlen(L, res));
lua_endblock(L);
}
}
static void str_gsub (void)
{
static void str_gsub (lua_State *L) {
long srcl;
char *src = luaL_check_lstr(1, &srcl);
char *p = luaL_check_string(2);
lua_Object newp = lua_getparam(3);
int max_s = (int)luaL_opt_number(4, srcl+1);
const char *src = luaL_check_lstr(L, 1, &srcl);
const char *p = luaL_check_string(L, 2);
lua_Object newp = lua_getparam(L, 3);
int max_s = luaL_opt_int(L, 4, srcl+1);
int anchor = (*p == '^') ? (p++, 1) : 0;
int n = 0;
struct Capture cap;
luaL_arg_check(lua_isstring(newp) || lua_isfunction(newp), 3,
luaL_arg_check(L, lua_isstring(L, newp) || lua_isfunction(L, newp), 3,
"string or function expected");
luaL_resetbuffer();
luaL_resetbuffer(L);
cap.src_end = src+srcl;
while (n < max_s) {
char *e;
const char *e;
cap.level = 0;
e = match(src, p, &cap);
e = match(L, src, p, &cap);
if (e) {
n++;
add_s(newp, &cap);
add_s(L, newp, &cap);
}
if (e && e>src) /* non empty match? */
src = e; /* skip it */
else if (src < cap.src_end)
luaL_addchar(*src++);
luaL_addchar(L, *src++);
else break;
if (anchor) break;
}
addnchar(src, cap.src_end-src);
closeandpush();
lua_pushnumber(n); /* number of substitutions */
addnchar(L, src, cap.src_end-src);
closeandpush(L);
lua_pushnumber(L, n); /* number of substitutions */
}
/* }====================================================== */
static void luaI_addquoted (char *s)
{
luaL_addchar('"');
for (; *s; s++) {
if (strchr("\"\\\n", *s))
luaL_addchar('\\');
luaL_addchar(*s);
static void luaI_addquoted (lua_State *L, int arg) {
long l;
const char *s = luaL_check_lstr(L, arg, &l);
luaL_addchar(L, '"');
while (l--) {
switch (*s) {
case '"': case '\\': case '\n':
luaL_addchar(L, '\\');
luaL_addchar(L, *s);
break;
case '\0': addnchar(L, "\\000", 4); break;
default: luaL_addchar(L, *s);
}
s++;
}
luaL_addchar('"');
luaL_addchar(L, '"');
}
#define MAX_FORMAT 200
/* maximum size of each format specification (such as '%-099.99d') */
#define MAX_FORMAT 20 /* arbitrary limit */
static void str_format (void)
{
static void str_format (lua_State *L) {
int arg = 1;
char *strfrmt = luaL_check_string(arg);
struct Capture cap;
cap.src_end = strfrmt+strlen(strfrmt)+1;
luaL_resetbuffer();
const char *strfrmt = luaL_check_string(L, arg);
luaL_resetbuffer(L);
while (*strfrmt) {
if (*strfrmt != '%')
luaL_addchar(*strfrmt++);
luaL_addchar(L, *strfrmt++);
else if (*++strfrmt == '%')
luaL_addchar(*strfrmt++); /* %% */
luaL_addchar(L, *strfrmt++); /* %% */
else { /* format item */
char form[MAX_FORMAT]; /* store the format ('%...') */
char *buff;
char *initf = strfrmt;
struct Capture cap;
char form[MAX_FORMAT]; /* to store the format ('%...') */
char *buff; /* to store the formatted item */
const char *initf = strfrmt;
form[0] = '%';
cap.level = 0;
if (isdigit((unsigned char)initf[0]) && initf[1] == '$') {
arg = initf[0] - '0';
if (isdigit((unsigned char)*initf) && *(initf+1) == '$') {
arg = *initf - '0';
initf += 2; /* skip the 'n$' */
}
arg++;
strfrmt = match(initf, "[-+ #0]*(%d*)%.?(%d*)", &cap);
if (cap.capture[0].len > 2 || cap.capture[1].len > 2) /* < 100? */
lua_error("invalid format (width or precision too long)");
cap.src_end = strfrmt+strlen(strfrmt)+1;
cap.level = 0;
strfrmt = match(L, initf, "[-+ #0]*(%d*)%.?(%d*)", &cap);
if (cap.capture[0].len > 2 || cap.capture[1].len > 2 || /* < 100? */
strfrmt-initf > MAX_FORMAT-2)
lua_error(L, "invalid format (width or precision too long)");
strncpy(form+1, initf, strfrmt-initf+1); /* +1 to include conversion */
form[strfrmt-initf+2] = 0;
buff = luaL_openspace(1000); /* to store the formatted value */
buff = luaL_openspace(L, 512); /* 512 > len(format('%99.99f', -1e308)) */
switch (*strfrmt++) {
case 'q':
luaI_addquoted(luaL_check_string(arg));
continue;
case 's': {
char *s = luaL_check_string(arg);
buff = luaL_openspace(strlen(s));
sprintf(buff, form, s);
break;
}
case 'c': case 'd': case 'i':
sprintf(buff, form, (int)luaL_check_number(arg));
sprintf(buff, form, luaL_check_int(L, arg));
break;
case 'o': case 'u': case 'x': case 'X':
sprintf(buff, form, (unsigned int)luaL_check_number(arg));
sprintf(buff, form, (unsigned int)luaL_check_number(L, arg));
break;
case 'e': case 'E': case 'f': case 'g': case 'G':
sprintf(buff, form, luaL_check_number(arg));
sprintf(buff, form, luaL_check_number(L, arg));
break;
case 'q':
luaI_addquoted(L, arg);
continue; /* skip the "addsize" at the end */
case 's': {
long l;
const char *s = luaL_check_lstr(L, arg, &l);
if (cap.capture[1].len == 0 && l >= 100) {
/* no precision and string is too long to be formatted;
keep original string */
addnchar(L, s, l);
continue; /* skip the "addsize" at the end */
}
else {
sprintf(buff, form, s);
break;
}
}
default: /* also treat cases 'pnLlh' */
lua_error("invalid option in `format'");
lua_error(L, "invalid option in `format'");
}
luaL_addsize(strlen(buff));
luaL_addsize(L, strlen(buff));
}
}
closeandpush(); /* push the result */
closeandpush(L); /* push the result */
}
static struct luaL_reg strlib[] = {
static const struct luaL_reg strlib[] = {
{"strlen", str_len},
{"strsub", str_sub},
{"strlower", str_lower},
{"strupper", str_upper},
{"strchar", str_char},
{"strrep", str_rep},
{"ascii", str_byte}, /* for compatibility */
{"ascii", str_byte}, /* for compatibility with 3.0 and earlier */
{"strbyte", str_byte},
{"format", str_format},
{"strfind", str_find},
@@ -535,7 +614,6 @@ static struct luaL_reg strlib[] = {
/*
** Open string library
*/
void strlib_open (void)
{
luaL_openlib(strlib, (sizeof(strlib)/sizeof(strlib[0])));
void lua_strlibopen (lua_State *L) {
luaL_openl(L, strlib);
}

326
ltable.c
View File

@@ -1,10 +1,24 @@
/*
** $Id: ltable.c,v 1.11 1998/01/13 18:06:27 roberto Exp roberto $
** $Id: ltable.c,v 1.38 2000/03/29 20:19:20 roberto Exp roberto $
** Lua tables (hash)
** See Copyright Notice in lua.h
*/
#include <stdlib.h>
/*
** Implementation of tables (aka arrays, objects, or hash tables);
** uses a mix of chained scatter table with Brent's variation.
** A main invariant of these tables is that, if an element is not
** in its main position (i.e. the `original' position that its hash gives
** to it), then the colliding element is in its own main position.
** In other words, there are collisions only when two elements have the
** same main position (i.e. the same hash values for that table size).
** Because of that, the load factor of these tables can be 100% without
** performance penalties.
*/
#define LUA_REENTRANT
#include "lauxlib.h"
#include "lmem.h"
@@ -14,203 +28,197 @@
#include "lua.h"
#define gcsize(n) (1+(n/16))
#define nuse(t) ((t)->nuse)
#define nodevector(t) ((t)->node)
#define REHASH_LIMIT 0.70 /* avoid more than this % full */
#define TagDefault LUA_T_ARRAY;
#define gcsize(L, n) numblocks(L, n*2, sizeof(Hash))
static long int hashindex (TObject *ref)
{
long int h;
switch (ttype(ref)) {
case LUA_T_NUMBER:
h = (long int)nvalue(ref);
break;
case LUA_T_STRING: case LUA_T_USERDATA:
h = (IntPoint)tsvalue(ref);
break;
case LUA_T_ARRAY:
h = (IntPoint)avalue(ref);
break;
case LUA_T_PROTO:
h = (IntPoint)tfvalue(ref);
break;
case LUA_T_CPROTO:
h = (IntPoint)fvalue(ref);
break;
case LUA_T_CLOSURE:
h = (IntPoint)clvalue(ref);
break;
default:
lua_error("unexpected type to index table");
h = 0; /* to avoid warnings */
}
return (h >= 0 ? h : -(h+1));
}
#define TagDefault TAG_TABLE
static int present (Hash *t, TObject *key)
{
int tsize = nhash(t);
long int h = hashindex(key);
int h1 = h%tsize;
TObject *rf = ref(node(t, h1));
if (ttype(rf) != LUA_T_NIL && !luaO_equalObj(key, rf)) {
int h2 = h%(tsize-2) + 1;
do {
h1 += h2;
if (h1 >= tsize) h1 -= tsize;
rf = ref(node(t, h1));
} while (ttype(rf) != LUA_T_NIL && !luaO_equalObj(key, rf));
}
return h1;
}
/*
** Alloc a vector node
** returns the `main' position of an element in a table (that is, the index
** of its hash value)
*/
static Node *hashnodecreate (int nhash)
{
Node *v = luaM_newvector(nhash, Node);
Node *luaH_mainposition (const Hash *t, const TObject *key) {
unsigned long h;
switch (ttype(key)) {
case TAG_NUMBER:
h = (unsigned long)(long)nvalue(key);
break;
case TAG_STRING: case TAG_USERDATA:
h = tsvalue(key)->hash;
break;
case TAG_TABLE:
h = IntPoint(L, avalue(key));
break;
case TAG_LCLOSURE: case TAG_CCLOSURE:
h = IntPoint(L, clvalue(key));
break;
default:
return NULL; /* invalid key */
}
LUA_ASSERT(L, h%(unsigned int)t->size == (h&((unsigned int)t->size-1)),
"a&(x-1) == a%x, for x power of 2");
return &t->node[h&((unsigned int)t->size-1)];
}
const TObject *luaH_get (lua_State *L, const Hash *t, const TObject *key) {
Node *n = luaH_mainposition(t, key);
if (!n)
lua_error(L, "unexpected type to index table");
else do {
if (luaO_equalObj(key, &n->key))
return &n->val;
n = n->next;
} while (n);
return &luaO_nilobject; /* key not found */
}
int luaH_pos (lua_State *L, const Hash *t, const TObject *key) {
const TObject *v = luaH_get(L, t, key);
return (v == &luaO_nilobject) ? -1 : /* key not found */
(int)(((const char *)v - (const char *)(&t->node[0].val))/sizeof(Node));
}
static Node *hashnodecreate (lua_State *L, int nhash) {
Node *v = luaM_newvector(L, nhash, Node);
int i;
for (i=0; i<nhash; i++)
ttype(ref(&v[i])) = LUA_T_NIL;
for (i=0; i<nhash; i++) {
ttype(&v[i].key) = ttype(&v[i].val) = TAG_NIL;
v[i].next = NULL;
}
return v;
}
/*
** Delete a hash
*/
static void hashdelete (Hash *t)
{
luaM_free(nodevector(t));
luaM_free(t);
static void setnodevector (lua_State *L, Hash *t, int size) {
t->node = hashnodecreate(L, size);
t->size = size;
t->firstfree = &t->node[size-1]; /* first free position to be used */
L->nblocks += gcsize(L, size);
}
void luaH_free (Hash *frees)
{
while (frees) {
Hash *next = (Hash *)frees->head.next;
L->nblocks -= gcsize(frees->nhash);
hashdelete(frees);
frees = next;
}
}
Hash *luaH_new (int nhash)
{
Hash *t = luaM_new(Hash);
nhash = luaO_redimension((int)((float)nhash/REHASH_LIMIT));
nodevector(t) = hashnodecreate(nhash);
nhash(t) = nhash;
nuse(t) = 0;
Hash *luaH_new (lua_State *L, int size) {
Hash *t = luaM_new(L, Hash);
setnodevector(L, t, luaO_power2(size));
t->htag = TagDefault;
luaO_insertlist(&(L->roottable), (GCnode *)t);
L->nblocks += gcsize(nhash);
t->next = L->roottable;
L->roottable = t;
t->marked = 0;
return t;
}
static int newsize (Hash *t)
{
void luaH_free (lua_State *L, Hash *t) {
L->nblocks -= gcsize(L, t->size);
luaM_free(L, t->node);
luaM_free(L, t);
}
static int newsize (const Hash *t) {
Node *v = t->node;
int size = nhash(t);
int size = t->size;
int realuse = 0;
int i;
for (i=0; i<size; i++) {
if (ttype(ref(v+i)) != LUA_T_NIL && ttype(val(v+i)) != LUA_T_NIL)
if (ttype(&v[i].val) != TAG_NIL)
realuse++;
}
if (2*(realuse+1) <= size) /* +1 is the new element */
return size; /* don't need to grow, just rehash */
else
return luaO_redimension(size);
return luaO_power2(realuse+realuse/4+1);
}
static void rehash (Hash *t)
{
int nold = nhash(t);
Node *vold = nodevector(t);
int nnew = newsize(t);
static void rehash (lua_State *L, Hash *t) {
int oldsize = t->size;
Node *nold = t->node;
int i;
nodevector(t) = hashnodecreate(nnew);
nhash(t) = nnew;
for (i=0; i<nold; i++) {
Node *n = vold+i;
if (ttype(ref(n)) != LUA_T_NIL && ttype(val(n)) != LUA_T_NIL)
*node(t, present(t, ref(n))) = *n; /* copy old node to luaM_new hash */
L->nblocks -= gcsize(L, oldsize);
setnodevector(L, t, newsize(t)); /* create new array of nodes */
for (i=0; i<oldsize; i++) {
Node *old = nold+i;
if (ttype(&old->val) != TAG_NIL)
luaH_set(L, t, &old->key, &old->val);
}
L->nblocks += gcsize(nnew)-gcsize(nold);
luaM_free(vold);
}
/*
** If the hash node is present, return its pointer, otherwise return
** null.
*/
TObject *luaH_get (Hash *t, TObject *ref)
{
int h = present(t, ref);
if (ttype(ref(node(t, h))) != LUA_T_NIL) return val(node(t, h));
else return NULL;
luaM_free(L, nold); /* free old array */
}
/*
** If the hash node is present, return its pointer, otherwise create a luaM_new
** node for the given reference and also return its pointer.
** sets a pair key-value in a hash table; first, check whether key is
** already present; if not, check whether key's main position is free;
** if not, check whether colliding node is in its main position or not;
** if it is not, move colliding node to an empty place and put new pair
** in its main position; otherwise (colliding node is in its main position),
** new pair goes to an empty position.
** Tricky point: the only place where an old element is moved is when
** we move the colliding node to an empty place; nevertheless, its old
** value is still in that position until we set the value for the new
** pair; therefore, even when `val' points to an element of this table
** (this happens when we use `luaH_move'), there is no problem.
*/
TObject *luaH_set (Hash *t, TObject *ref)
{
Node *n = node(t, present(t, ref));
if (ttype(ref(n)) == LUA_T_NIL) {
nuse(t)++;
if ((float)nuse(t) > (float)nhash(t)*REHASH_LIMIT) {
rehash(t);
n = node(t, present(t, ref));
void luaH_set (lua_State *L, Hash *t, const TObject *key, const TObject *val) {
Node *mp = luaH_mainposition(t, key);
Node *n = mp;
if (!mp)
lua_error(L, "unexpected type to index table");
do { /* check whether `key' is somewhere in the chain */
if (luaO_equalObj(key, &n->key)) {
n->val = *val; /* update value */
return; /* that's all */
}
else n = n->next;
} while (n);
/* `key' not found; must insert it */
if (ttype(&mp->key) != TAG_NIL) { /* main position is not free? */
Node *othern; /* main position of colliding node */
n = t->firstfree; /* get a free place */
/* is colliding node out of its main position? (can only happens if
its position if after "firstfree") */
if (mp > n && (othern=luaH_mainposition(t, &mp->key)) != mp) {
/* yes; move colliding node into free position */
while (othern->next != mp) othern = othern->next; /* find previous */
othern->next = n; /* redo the chain with `n' in place of `mp' */
*n = *mp; /* copy colliding node into free pos. (mp->next also goes) */
mp->next = NULL; /* now `mp' is free */
}
else { /* colliding node is in its own main position */
/* new node will go into free position */
n->next = mp->next; /* chain new position */
mp->next = n;
mp = n;
}
*ref(n) = *ref;
ttype(val(n)) = LUA_T_NIL;
}
return (val(n));
mp->key = *key;
mp->val = *val;
for (;;) { /* check free places */
if (ttype(&t->firstfree->key) == TAG_NIL)
return; /* OK; table still has a free place */
else if (t->firstfree == t->node) break; /* cannot decrement from here */
else (t->firstfree)--;
}
rehash(L, t); /* no more free places */
}
static Node *hashnext (Hash *t, int i)
{
Node *n;
int tsize = nhash(t);
if (i >= tsize)
return NULL;
n = node(t, i);
while (ttype(ref(n)) == LUA_T_NIL || ttype(val(n)) == LUA_T_NIL) {
if (++i >= tsize)
return NULL;
n = node(t, i);
}
return node(t, i);
void luaH_setint (lua_State *L, Hash *t, int key, const TObject *val) {
TObject index;
ttype(&index) = TAG_NUMBER;
nvalue(&index) = key;
luaH_set(L, t, &index, val);
}
Node *luaH_next (TObject *o, TObject *r)
{
Hash *t = avalue(o);
if (ttype(r) == LUA_T_NIL)
return hashnext(t, 0);
else {
int i = present(t, r);
Node *n = node(t, i);
luaL_arg_check(ttype(ref(n))!=LUA_T_NIL && ttype(val(n))!=LUA_T_NIL,
2, "key not found");
return hashnext(t, i+1);
}
const TObject *luaH_getint (lua_State *L, const Hash *t, int key) {
TObject index;
ttype(&index) = TAG_NUMBER;
nvalue(&index) = key;
return luaH_get(L, t, &index);
}

View File

@@ -1,5 +1,5 @@
/*
** $Id: ltable.h,v 1.4 1997/11/19 17:29:23 roberto Exp roberto $
** $Id: ltable.h,v 1.17 1999/11/23 13:58:02 roberto Exp roberto $
** Lua tables (hash)
** See Copyright Notice in lua.h
*/
@@ -10,15 +10,23 @@
#include "lobject.h"
#define node(t,i) (&(t)->node[i])
#define ref(n) (&(n)->ref)
#define node(t,i) (&(t)->node[i])
#define key(n) (&(n)->key)
#define val(n) (&(n)->val)
#define nhash(t) ((t)->nhash)
Hash *luaH_new (int nhash);
void luaH_free (Hash *frees);
TObject *luaH_get (Hash *t, TObject *ref);
TObject *luaH_set (Hash *t, TObject *ref);
Node *luaH_next (TObject *o, TObject *r);
#define luaH_move(L, t,from,to) (luaH_setint(L, t, to, luaH_getint(L, t, from)))
Hash *luaH_new (lua_State *L, int nhash);
void luaH_free (lua_State *L, Hash *t);
const TObject *luaH_get (lua_State *L, const Hash *t, const TObject *key);
void luaH_set (lua_State *L, Hash *t, const TObject *key, const TObject *val);
int luaH_pos (lua_State *L, const Hash *t, const TObject *r);
void luaH_setint (lua_State *L, Hash *t, int key, const TObject *val);
const TObject *luaH_getint (lua_State *L, const Hash *t, int key);
unsigned long luaH_hash (lua_State *L, const TObject *key);
/* exported only for debugging */
Node *luaH_mainposition (const Hash *t, const TObject *key);
#endif

417
ltests.c Normal file
View File

@@ -0,0 +1,417 @@
/*
** $Id: ltests.c,v 1.15 2000/04/13 16:51:01 roberto Exp roberto $
** Internal Module for Debugging of the Lua Implementation
** See Copyright Notice in lua.h
*/
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LUA_REENTRANT
#include "lapi.h"
#include "lauxlib.h"
#include "lmem.h"
#include "lopcodes.h"
#include "lstate.h"
#include "lstring.h"
#include "ltable.h"
#include "lua.h"
#include "luadebug.h"
void luaB_opentests (lua_State *L);
/*
** The whole module only makes sense with DEBUG on
*/
#ifdef DEBUG
static void setnameval (lua_State *L, lua_Object t, const char *name, int val) {
lua_pushobject(L, t);
lua_pushstring(L, name);
lua_pushnumber(L, val);
lua_settable(L);
}
/*
** {======================================================
** Disassembler
** =======================================================
*/
#define O(o) sprintf(buff, "%s", o)
#define U(o) sprintf(buff, "%-12s%4u", o, GETARG_U(i))
#define S(o) sprintf(buff, "%-12s%4d", o, GETARG_S(i))
#define AB(o) sprintf(buff, "%-12s%4d %4d", o, GETARG_A(i), GETARG_B(i))
static int pushop (lua_State *L, Instruction i) {
char buff[100];
switch (GET_OPCODE(i)) {
case OP_END: O("END"); lua_pushstring(L, buff); return 0;
case OP_RETURN: U("RETURN"); break;
case OP_CALL: AB("CALL"); break;
case OP_TAILCALL: AB("TAILCALL"); break;
case OP_PUSHNIL: U("PUSHNIL"); break;
case OP_POP: U("POP"); break;
case OP_PUSHINT: S("PUSHINT"); break;
case OP_PUSHSTRING: U("PUSHSTRING"); break;
case OP_PUSHNUM: U("PUSHNUM"); break;
case OP_PUSHNEGNUM: U("PUSHNEGNUM"); break;
case OP_PUSHUPVALUE: U("PUSHUPVALUE"); break;
case OP_GETLOCAL: U("GETLOCAL"); break;
case OP_GETGLOBAL: U("GETGLOBAL"); break;
case OP_GETTABLE: O("GETTABLE"); break;
case OP_GETDOTTED: U("GETDOTTED"); break;
case OP_GETINDEXED: U("GETINDEXED"); break;
case OP_PUSHSELF: U("PUSHSELF"); break;
case OP_CREATETABLE: U("CREATETABLE"); break;
case OP_SETLOCAL: U("SETLOCAL"); break;
case OP_SETGLOBAL: U("SETGLOBAL"); break;
case OP_SETTABLE: AB("SETTABLE"); break;
case OP_SETLIST: AB("SETLIST"); break;
case OP_SETMAP: U("SETMAP"); break;
case OP_ADD: O("ADD"); break;
case OP_ADDI: S("ADDI"); break;
case OP_SUB: O("SUB"); break;
case OP_MULT: O("MULT"); break;
case OP_DIV: O("DIV"); break;
case OP_POW: O("POW"); break;
case OP_CONCAT: U("CONCAT"); break;
case OP_MINUS: O("MINUS"); break;
case OP_NOT: O("NOT"); break;
case OP_JMPNE: S("JMPNE"); break;
case OP_JMPEQ: S("JMPEQ"); break;
case OP_JMPLT: S("JMPLT"); break;
case OP_JMPLE: S("JMPLE"); break;
case OP_JMPGT: S("JMPGT"); break;
case OP_JMPGE: S("JMPGE"); break;
case OP_JMPT: S("JMPT"); break;
case OP_JMPF: S("JMPF"); break;
case OP_JMPONT: S("JMPONT"); break;
case OP_JMPONF: S("JMPONF"); break;
case OP_JMP: S("JMP"); break;
case OP_PUSHNILJMP: O("PUSHNILJMP"); break;
case OP_FORPREP: S("OP_FORPREP"); break;
case OP_FORLOOP: S("OP_FORLOOP"); break;
case OP_CLOSURE: AB("CLOSURE"); break;
case OP_SETLINE: U("SETLINE"); break;
}
lua_pushstring(L, buff);
return 1;
}
static void listcode (lua_State *L) {
lua_Object o = luaL_nonnullarg(L, 1);
lua_Object t = lua_createtable(L);
Instruction *pc;
Proto *p;
int res;
luaL_arg_check(L, ttype(o) == TAG_LCLOSURE, 1, "Lua function expected");
p = clvalue(o)->f.l;
setnameval(L, t, "maxstack", p->maxstacksize);
setnameval(L, t, "numparams", p->numparams);
pc = p->code;
do {
lua_pushobject(L, t);
lua_pushnumber(L, pc - p->code + 1);
res = pushop(L, *pc++);
lua_settable(L);
} while (res);
lua_pushobject(L, t);
}
/* }====================================================== */
static void get_limits (lua_State *L) {
lua_Object t = lua_createtable(L);
setnameval(L, t, "SIZE_OP", SIZE_OP);
setnameval(L, t, "SIZE_U", SIZE_U);
setnameval(L, t, "SIZE_A", SIZE_A);
setnameval(L, t, "SIZE_B", SIZE_B);
setnameval(L, t, "MAXARG_U", MAXARG_U);
setnameval(L, t, "MAXARG_S", MAXARG_S);
setnameval(L, t, "MAXARG_A", MAXARG_A);
setnameval(L, t, "MAXARG_B", MAXARG_B);
setnameval(L, t, "MAXSTACK", MAXSTACK);
setnameval(L, t, "MAXLOCALS", MAXLOCALS);
setnameval(L, t, "MAXUPVALUES", MAXUPVALUES);
setnameval(L, t, "MAXVARSLH", MAXVARSLH);
setnameval(L, t, "MAXPARAMS", MAXPARAMS);
setnameval(L, t, "LFPF", LFIELDS_PER_FLUSH);
setnameval(L, t, "RFPF", RFIELDS_PER_FLUSH);
lua_pushobject(L, t);
}
static void mem_query (lua_State *L) {
lua_pushnumber(L, memdebug_total);
lua_pushnumber(L, memdebug_numblocks);
lua_pushnumber(L, memdebug_maxmem);
}
static void hash_query (lua_State *L) {
lua_Object o = luaL_nonnullarg(L, 1);
if (lua_getparam(L, 2) == LUA_NOOBJECT) {
luaL_arg_check(L, ttype(o) == TAG_STRING, 1, "string expected");
lua_pushnumber(L, tsvalue(o)->hash);
}
else {
const Hash *t = avalue(luaL_tablearg(L, 2));
lua_pushnumber(L, luaH_mainposition(t, o) - t->node);
}
}
static void table_query (lua_State *L) {
const Hash *t = avalue(luaL_tablearg(L, 1));
int i = luaL_opt_int(L, 2, -1);
if (i == -1) {
lua_pushnumber(L, t->size);
lua_pushnumber(L, t->firstfree - t->node);
}
else if (i < t->size) {
luaA_pushobject(L, &t->node[i].key);
luaA_pushobject(L, &t->node[i].val);
if (t->node[i].next)
lua_pushnumber(L, t->node[i].next - t->node);
}
}
static void string_query (lua_State *L) {
int h = luaL_check_int(L, 1) - 1;
int s = luaL_opt_int(L, 2, 0) - 1;
if (s==-1) {
if (h < NUM_HASHS) {
lua_pushnumber(L, L->string_root[h].nuse);
lua_pushnumber(L, L->string_root[h].size);
}
}
else {
TString *ts = L->string_root[h].hash[s];
for (ts = L->string_root[h].hash[s]; ts; ts = ts->nexthash) {
if (ts->constindex == -1) lua_pushstring(L, "<USERDATA>");
else lua_pushstring(L, ts->str);
}
}
}
/*
** {======================================================
** function to test the API with C. It interprets a kind of "assembler"
** language with calls to the API, so the test can be driven by Lua code
** =======================================================
*/
static const char *const delimits = " \t\n,;";
static void skip (const char **pc) {
while (**pc != '\0' && strchr(delimits, **pc)) (*pc)++;
}
static int getnum (const char **pc) {
int res = 0;
skip(pc);
while (isdigit(**pc)) res = res*10 + (*(*pc)++) - '0';
return res;
}
static int getreg (lua_State *L, const char **pc) {
skip(pc);
if (*(*pc)++ != 'r') lua_error(L, "`testC' expecting a register");
return getnum(pc);
}
static const char *getname (const char **pc) {
static char buff[30];
int i = 0;
skip(pc);
while (**pc != '\0' && !strchr(delimits, **pc))
buff[i++] = *(*pc)++;
buff[i] = '\0';
return buff;
}
#define EQ(s1) (strcmp(s1, inst) == 0)
static void testC (lua_State *L) {
lua_Object reg[10];
const char *pc = luaL_check_string(L, 1);
for (;;) {
const char *inst = getname(&pc);
if EQ("") return;
else if EQ("pushnum") {
lua_pushnumber(L, getnum(&pc));
}
else if EQ("createtable") {
reg[getreg(L, &pc)] = lua_createtable(L);
}
else if EQ("closure") {
lua_CFunction f = lua_getcfunction(L, lua_getglobal(L, getname(&pc)));
lua_pushcclosure(L, f, getnum(&pc));
}
else if EQ("pop") {
reg[getreg(L, &pc)] = lua_pop(L);
}
else if EQ("getglobal") {
int n = getreg(L, &pc);
reg[n] = lua_getglobal(L, getname(&pc));
}
else if EQ("rawgetglobal") {
int n = getreg(L, &pc);
reg[n] = lua_rawgetglobal(L, getname(&pc));
}
else if EQ("ref") {
lua_pushnumber(L, lua_ref(L, 0));
reg[getreg(L, &pc)] = lua_pop(L);
}
else if EQ("reflock") {
lua_pushnumber(L, lua_ref(L, 1));
reg[getreg(L, &pc)] = lua_pop(L);
}
else if EQ("getref") {
int n = getreg(L, &pc);
reg[n] = lua_getref(L, (int)lua_getnumber(L, reg[getreg(L, &pc)]));
}
else if EQ("unref") {
lua_unref(L, (int)lua_getnumber(L, reg[getreg(L, &pc)]));
}
else if EQ("getparam") {
int n = getreg(L, &pc);
reg[n] = lua_getparam(L, getnum(&pc)+1); /* skips the command itself */
}
else if EQ("getresult") {
int n = getreg(L, &pc);
reg[n] = lua_getparam(L, getnum(&pc));
}
else if EQ("setglobal") {
lua_setglobal(L, getname(&pc));
}
else if EQ("rawsetglobal") {
lua_rawsetglobal(L, getname(&pc));
}
else if EQ("pushstring") {
lua_pushstring(L, getname(&pc));
}
else if EQ("pushreg") {
lua_pushobject(L, reg[getreg(L, &pc)]);
}
else if EQ("call") {
if (lua_call(L, getname(&pc))) lua_error(L, NULL);
}
else if EQ("gettable") {
reg[getreg(L, &pc)] = lua_gettable(L);
}
else if EQ("rawgettable") {
reg[getreg(L, &pc)] = lua_rawgettable(L);
}
else if EQ("settable") {
lua_settable(L);
}
else if EQ("rawsettable") {
lua_rawsettable(L);
}
else if EQ("tag") {
lua_pushnumber(L, lua_tag(L, reg[getreg(L, &pc)]));
}
else if EQ("type") {
lua_pushstring(L, lua_type(L, reg[getreg(L, &pc)]));
}
else if EQ("nextvar") {
lua_pushstring(L, lua_nextvar(L, lua_getstring(L, reg[getreg(L, &pc)])));
}
else if EQ("next") {
int n = getreg(L, &pc);
n = lua_next(L, reg[n], (int)lua_getnumber(L, reg[getreg(L, &pc)]));
lua_pushnumber(L, n);
}
else if EQ("equal") {
int n1 = getreg(L, &pc);
int n2 = getreg(L, &pc);
lua_pushnumber(L, lua_equal(L, reg[n1], reg[n2]));
}
else if EQ("pushusertag") {
int val = getreg(L, &pc);
int tag = getreg(L, &pc);
lua_pushusertag(L, (void *)(int)lua_getnumber(L, reg[val]),
(int)lua_getnumber(L, reg[tag]));
}
else if EQ("udataval") {
int n = getreg(L, &pc);
lua_pushnumber(L, (int)lua_getuserdata(L, reg[getreg(L, &pc)]));
reg[n] = lua_pop(L);
}
else if EQ("settagmethod") {
int n = getreg(L, &pc);
lua_settagmethod(L, (int)lua_getnumber(L, reg[n]), getname(&pc));
}
else if EQ("beginblock") {
lua_beginblock(L);
}
else if EQ("endblock") {
lua_endblock(L);
}
else if EQ("newstate") {
int stacksize = getnum(&pc);
lua_State *L1 = lua_newstate("stack", stacksize,
"builtin", getnum(&pc), NULL);
lua_pushuserdata(L, L1);
}
else if EQ("closestate") {
lua_close((lua_State *)lua_getuserdata(L, reg[getreg(L, &pc)]));
}
else if EQ("doremote") {
lua_Object ol1 = reg[getreg(L, &pc)];
lua_Object str = reg[getreg(L, &pc)];
lua_State *L1;
lua_Object temp;
int i;
if (!lua_isuserdata(L, ol1) || !lua_isstring(L, str))
lua_error(L, "bad arguments for `doremote'");
L1 = (lua_State *)lua_getuserdata(L, ol1);
lua_dostring(L1, lua_getstring(L, str));
i = 1;
while ((temp = lua_getresult(L1, i++)) != LUA_NOOBJECT)
lua_pushstring(L, lua_getstring(L1, temp));
}
else luaL_verror(L, "unknown command in `testC': %.20s", inst);
}
}
/* }====================================================== */
static const struct luaL_reg tests_funcs[] = {
{"hash", hash_query},
{"limits", get_limits},
{"listcode", listcode},
{"querystr", string_query},
{"querytab", table_query},
{"testC", testC},
{"totalmem", mem_query}
};
void luaB_opentests (lua_State *L) {
luaL_openl(L, tests_funcs);
}
#endif

265
ltm.c
View File

@@ -1,5 +1,5 @@
/*
** $Id: ltm.c,v 1.15 1998/03/11 13:59:50 roberto Exp roberto $
** $Id: ltm.c,v 1.38 2000/03/29 20:19:20 roberto Exp roberto $
** Tag methods
** See Copyright Notice in lua.h
*/
@@ -8,6 +8,8 @@
#include <stdio.h>
#include <string.h>
#define LUA_REENTRANT
#include "lauxlib.h"
#include "lmem.h"
#include "lobject.h"
@@ -15,249 +17,142 @@
#include "ltm.h"
char *luaT_eventname[] = { /* ORDER IM */
"gettable", "settable", "index", "getglobal", "setglobal", "add",
"sub", "mul", "div", "pow", "unm", "lt", "le", "gt", "ge",
"concat", "gc", "function", NULL
const char *const luaT_eventname[] = { /* ORDER IM */
"gettable", "settable", "index", "getglobal", "setglobal", "add", "sub",
"mul", "div", "pow", "unm", "lt", "concat", "gc", "function",
"le", "gt", "ge", /* deprecated options!! */
NULL
};
static int luaI_checkevent (char *name, char *list[])
{
int e = luaL_findstring(name, list);
static int luaI_checkevent (lua_State *L, const char *name, int t) {
int e = luaL_findstring(name, luaT_eventname);
if (e >= IM_N)
luaL_verror(L, "event `%.50s' is deprecated", name);
if (e == IM_GC && t == TAG_TABLE)
luaL_verror(L, "event `gc' for tables is deprecated");
if (e < 0)
luaL_verror("`%.50s' is not a valid event name", name);
luaL_verror(L, "`%.50s' is not a valid event name", name);
return e;
}
/* events in LUA_T_NIL are all allowed, since this is used as a
/* events in TAG_NIL are all allowed, since this is used as a
* 'placeholder' for "default" fallbacks
*/
static char validevents[NUM_TAGS][IM_N] = { /* ORDER LUA_T, ORDER IM */
{1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1}, /* LUA_T_USERDATA */
{1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1}, /* LUA_T_NUMBER */
{1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, /* LUA_T_STRING */
{0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, /* LUA_T_ARRAY */
{1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0}, /* LUA_T_PROTO */
{1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0}, /* LUA_T_CPROTO */
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1} /* LUA_T_NIL */
/* ORDER LUA_T, ORDER IM */
static const char luaT_validevents[NUM_TAGS][IM_N] = {
{1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1}, /* TAG_USERDATA */
{1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1}, /* TAG_NUMBER */
{1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, /* TAG_STRING */
{0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1}, /* TAG_TABLE */
{1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0}, /* TAG_LCLOSURE */
{1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0}, /* TAG_CCLOSURE */
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1} /* TAG_NIL */
};
static int validevent (int t, int e)
{ /* ORDER LUA_T */
return (t < LUA_T_NIL) ? 1 : validevents[-t][e];
int luaT_validevent (int t, int e) { /* ORDER LUA_T */
return (t > TAG_NIL) ? 1 : luaT_validevents[t][e];
}
static void init_entry (int tag)
{
static void init_entry (lua_State *L, int tag) {
int i;
for (i=0; i<IM_N; i++)
ttype(luaT_getim(tag, i)) = LUA_T_NIL;
ttype(luaT_getim(L, tag, i)) = TAG_NIL;
}
void luaT_init (void)
{
void luaT_init (lua_State *L) {
int t;
L->IMtable_size = NUM_TAGS*2;
L->last_tag = -(NUM_TAGS-1);
L->IMtable = luaM_newvector(L->IMtable_size, struct IM);
for (t=L->last_tag; t<=0; t++)
init_entry(t);
L->last_tag = NUM_TAGS-1;
luaM_growvector(L, L->IMtable, 0, NUM_TAGS, struct IM, arrEM, MAX_INT);
for (t=0; t<=L->last_tag; t++)
init_entry(L, t);
}
int lua_newtag (void)
{
--L->last_tag;
if ((-L->last_tag) >= L->IMtable_size)
L->IMtable_size = luaM_growvector(&L->IMtable, L->IMtable_size,
struct IM, memEM, MAX_INT);
init_entry(L->last_tag);
int lua_newtag (lua_State *L) {
++L->last_tag;
luaM_growvector(L, L->IMtable, L->last_tag, 1, struct IM, arrEM, MAX_INT);
init_entry(L, L->last_tag);
return L->last_tag;
}
static void checktag (int tag)
{
if (!(L->last_tag <= tag && tag <= 0))
luaL_verror("%d is not a valid tag", tag);
static void checktag (lua_State *L, int tag) {
if (!(0 <= tag && tag <= L->last_tag))
luaL_verror(L, "%d is not a valid tag", tag);
}
void luaT_realtag (int tag)
{
if (!(L->last_tag <= tag && tag < LUA_T_NIL))
luaL_verror("tag %d is not result of `newtag'", tag);
void luaT_realtag (lua_State *L, int tag) {
if (!(NUM_TAGS <= tag && tag <= L->last_tag))
luaL_verror(L, "tag %d was not created by `newtag'", tag);
}
int lua_copytagmethods (int tagto, int tagfrom)
{
int lua_copytagmethods (lua_State *L, int tagto, int tagfrom) {
int e;
checktag(tagto);
checktag(tagfrom);
checktag(L, tagto);
checktag(L, tagfrom);
for (e=0; e<IM_N; e++) {
if (validevent(tagto, e))
*luaT_getim(tagto, e) = *luaT_getim(tagfrom, e);
if (luaT_validevent(tagto, e))
*luaT_getim(L, tagto, e) = *luaT_getim(L, tagfrom, e);
}
return tagto;
}
int luaT_efectivetag (TObject *o)
{
int t;
switch (t = ttype(o)) {
case LUA_T_ARRAY:
return o->value.a->htag;
case LUA_T_USERDATA: {
int luaT_effectivetag (lua_State *L, const TObject *o) {
lua_Type t = ttype(o);
switch (t) {
case TAG_USERDATA: {
int tag = o->value.ts->u.d.tag;
return (tag >= 0) ? LUA_T_USERDATA : tag;
return (tag > L->last_tag) ? TAG_USERDATA : tag; /* deprecated test */
}
case LUA_T_CLOSURE:
return o->value.cl->consts[0].ttype;
#ifdef DEBUG
case LUA_T_PMARK: case LUA_T_CMARK:
case LUA_T_CLMARK: case LUA_T_LINE:
LUA_INTERNALERROR("invalid type");
#endif
default:
return t;
case TAG_TABLE: return o->value.a->htag;
default: return t;
}
}
TObject *luaT_gettagmethod (int t, char *event)
{
int e = luaI_checkevent(event, luaT_eventname);
checktag(t);
if (validevent(t, e))
return luaT_getim(t,e);
const TObject *luaT_gettagmethod (lua_State *L, int t, const char *event) {
int e;
e = luaI_checkevent(L, event, t);
checktag(L, t);
if (luaT_validevent(t, e))
return luaT_getim(L, t,e);
else
return &luaO_nilobject;
}
void luaT_settagmethod (int t, char *event, TObject *func)
{
TObject temp = *func;
int e = luaI_checkevent(event, luaT_eventname);
checktag(t);
if (!validevent(t, e))
luaL_verror("settagmethod: cannot change tag method `%.20s' for tag %d",
luaT_eventname[e], t);
*func = *luaT_getim(t,e);
*luaT_getim(t, e) = temp;
void luaT_settagmethod (lua_State *L, int t, const char *event, TObject *func) {
TObject temp;
int e;
e = luaI_checkevent(L, event, t);
checktag(L, t);
if (!luaT_validevent(t, e))
luaL_verror(L, "cannot change `%.20s' tag method for type `%.20s'%.20s",
luaT_eventname[e], luaO_typenames[t],
(t == TAG_TABLE || t == TAG_USERDATA) ? " with default tag"
: "");
temp = *func;
*func = *luaT_getim(L, t,e);
*luaT_getim(L, t, e) = temp;
}
char *luaT_travtagmethods (int (*fn)(TObject *))
{
const char *luaT_travtagmethods (lua_State *L,
int (*fn)(lua_State *, TObject *)) { /* ORDER IM */
int e;
if (fn(&L->errorim))
return "error";
for (e=IM_GETTABLE; e<=IM_FUNCTION; e++) { /* ORDER IM */
for (e=IM_GETTABLE; e<=IM_FUNCTION; e++) {
int t;
for (t=0; t>=L->last_tag; t--)
if (fn(luaT_getim(t,e)))
for (t=0; t<=L->last_tag; t++)
if (fn(L, luaT_getim(L, t,e)))
return luaT_eventname[e];
}
return NULL;
}
/*
* ===================================================================
* compatibility with old fallback system
*/
#ifdef LUA_COMPAT2_5
#include "lapi.h"
static void errorFB (void)
{
lua_Object o = lua_getparam(1);
if (lua_isstring(o))
fprintf(stderr, "lua: %s\n", lua_getstring(o));
else
fprintf(stderr, "lua: unknown error\n");
}
static void nilFB (void) { }
static void typeFB (void)
{
lua_error("unexpected type");
}
static void fillvalids (IMS e, TObject *func)
{
int t;
for (t=LUA_T_NIL; t<=LUA_T_USERDATA; t++)
if (validevent(t, e))
*luaT_getim(t, e) = *func;
}
void luaT_setfallback (void)
{
static char *oldnames [] = {"error", "getglobal", "arith", "order", NULL};
TObject oldfunc;
lua_CFunction replace;
char *name = luaL_check_string(1);
lua_Object func = lua_getparam(2);
luaL_arg_check(lua_isfunction(func), 2, "function expected");
switch (luaL_findstring(name, oldnames)) {
case 0: /* old error fallback */
oldfunc = L->errorim;
L->errorim = *luaA_Address(func);
replace = errorFB;
break;
case 1: /* old getglobal fallback */
oldfunc = *luaT_getim(LUA_T_NIL, IM_GETGLOBAL);
*luaT_getim(LUA_T_NIL, IM_GETGLOBAL) = *luaA_Address(func);
replace = nilFB;
break;
case 2: { /* old arith fallback */
int i;
oldfunc = *luaT_getim(LUA_T_NUMBER, IM_POW);
for (i=IM_ADD; i<=IM_UNM; i++) /* ORDER IM */
fillvalids(i, luaA_Address(func));
replace = typeFB;
break;
}
case 3: { /* old order fallback */
int i;
oldfunc = *luaT_getim(LUA_T_NIL, IM_LT);
for (i=IM_LT; i<=IM_GE; i++) /* ORDER IM */
fillvalids(i, luaA_Address(func));
replace = typeFB;
break;
}
default: {
int e;
if ((e = luaL_findstring(name, luaT_eventname)) >= 0) {
oldfunc = *luaT_getim(LUA_T_NIL, e);
fillvalids(e, luaA_Address(func));
replace = (e == IM_GC || e == IM_INDEX) ? nilFB : typeFB;
}
else {
luaL_verror("`%.50s' is not a valid fallback name", name);
replace = NULL; /* to avoid warnings */
}
}
}
if (oldfunc.ttype != LUA_T_NIL)
luaA_pushobject(&oldfunc);
else
lua_pushcfunction(replace);
}
#endif

30
ltm.h
View File

@@ -1,5 +1,5 @@
/*
** $Id: ltm.h,v 1.3 1997/11/19 17:29:23 roberto Exp roberto $
** $Id: ltm.h,v 1.11 2000/03/20 19:14:54 roberto Exp roberto $
** Tag methods
** See Copyright Notice in lua.h
*/
@@ -28,35 +28,31 @@ typedef enum {
IM_POW,
IM_UNM,
IM_LT,
IM_LE,
IM_GT,
IM_GE,
IM_CONCAT,
IM_GC,
IM_FUNCTION
IM_FUNCTION,
IM_N /* number of elements in the enum */
} IMS;
#define IM_N 18
struct IM {
TObject int_method[IM_N];
};
#define luaT_getim(tag,event) (&L->IMtable[-(tag)].int_method[event])
#define luaT_getimbyObj(o,e) (luaT_getim(luaT_efectivetag(o),(e)))
#define luaT_getim(L,tag,event) (&L->IMtable[tag].int_method[event])
#define luaT_getimbyObj(L,o,e) (luaT_getim(L, luaT_effectivetag(L, o),(e)))
extern char *luaT_eventname[];
extern const char *const luaT_eventname[];
void luaT_init (void);
void luaT_realtag (int tag);
int luaT_efectivetag (TObject *o);
void luaT_settagmethod (int t, char *event, TObject *func);
TObject *luaT_gettagmethod (int t, char *event);
char *luaT_travtagmethods (int (*fn)(TObject *));
void luaT_init (lua_State *L);
void luaT_realtag (lua_State *L, int tag);
int luaT_effectivetag (lua_State *L, const TObject *o);
void luaT_settagmethod (lua_State *L, int t, const char *event, TObject *func);
const TObject *luaT_gettagmethod (lua_State *L, int t, const char *event);
const char *luaT_travtagmethods (lua_State *L, int (*fn)(lua_State *, TObject *));
int luaT_validevent (int t, int e); /* used by compatibility module */
void luaT_setfallback (void); /* only if LUA_COMPAT2_5 */
#endif

220
lua.c
View File

@@ -1,5 +1,5 @@
/*
** $Id: lua.c,v 1.13 1998/01/19 19:49:49 roberto Exp roberto $
** $Id: lua.c,v 1.36 2000/03/30 17:19:48 roberto Exp roberto $
** Lua stand-alone interpreter
** See Copyright Notice in lua.h
*/
@@ -15,92 +15,131 @@
#include "lualib.h"
#ifndef OLD_ANSI
#include <locale.h>
#else
#define setlocale(a,b) 0
#ifndef PROMPT
#define PROMPT "> "
#endif
#ifdef _POSIX_SOURCE
#include <unistd.h>
#else
#define isatty(x) (x==0) /* assume stdin is a tty */
static int isatty (int x) { return x==0; } /* assume stdin is a tty */
#endif
typedef void (*handler)(int); /* type for signal actions */
static void laction (int i);
static handler lreset (void)
{
lua_linehook = NULL;
lua_callhook = NULL;
static lua_Hook old_linehook = NULL;
static lua_Hook old_callhook = NULL;
static handler lreset (void) {
return signal(SIGINT, laction);
}
static void lstop (void)
{
static void lstop (void) {
lua_setlinehook(lua_state, old_linehook);
lua_setcallhook(lua_state, old_callhook);
lreset();
lua_error("interrupted!");
}
static void laction (int i)
{
lua_linehook = (lua_LHFunction)lstop;
lua_callhook = (lua_CHFunction)lstop;
static void laction (int i) {
(void)i; /* to avoid warnings */
signal(SIGINT, SIG_DFL); /* if another SIGINT happens before lstop,
terminate process (default action) */
old_linehook = lua_setlinehook(lua_state, (lua_Hook)lstop);
old_callhook = lua_setcallhook(lua_state, (lua_Hook)lstop);
}
static int ldo (int (*f)(char *), char *name)
{
static int ldo (int (*f)(lua_State *L, const char *), const char *name) {
int res;
handler h = lreset();
res = f(name); /* dostring | dofile */
res = f(lua_state, name); /* dostring | dofile */
signal(SIGINT, h); /* restore old action */
return res;
}
static void print_message (void)
{
static void print_message (void) {
fprintf(stderr,
"Lua: command line options:\n"
" -v print version information\n"
" -d turn debug on\n"
" -e stat dostring `stat'\n"
" -q interactive mode without prompt\n"
" -i interactive mode with prompt\n"
" - executes stdin as a file\n"
" a=b sets global `a' with string `b'\n"
" name dofile `name'\n\n");
"usage: lua [options]. Available options are:\n"
" - execute stdin as a file\n"
" -d turn debug on\n"
" -e stat execute string `stat'\n"
" -f name execute file `name' with remaining arguments in table `arg'\n"
" -i enter interactive mode with prompt\n"
" -q enter interactive mode without prompt\n"
" -sNUM set stack size to NUM (must be first option)\n"
" -v print version information\n"
" a=b set global `a' to string `b'\n"
" name execute file `name'\n"
);
}
static void assign (char *arg)
{
if (strlen(arg) >= 500)
fprintf(stderr, "lua: shell argument too long");
else {
char buffer[500];
char *eq = strchr(arg, '=');
lua_pushstring(eq+1);
strncpy(buffer, arg, eq-arg);
buffer[eq-arg] = 0;
lua_setglobal(buffer);
static void print_version (void) {
printf("%s %s\n", LUA_VERSION, LUA_COPYRIGHT);
}
static void assign (char *arg) {
char *eq = strchr(arg, '=');
*eq = '\0'; /* spilt `arg' in two strings (name & value) */
lua_pushstring(eq+1);
lua_setglobal(arg);
}
static lua_Object getargs (char *argv[]) {
lua_Object args = lua_createtable();
int i;
for (i=0; argv[i]; i++) {
/* arg[i] = argv[i] */
lua_pushobject(args); lua_pushnumber(i);
lua_pushstring(argv[i]); lua_settable();
}
/* arg.n = maximum index in table `arg' */
lua_pushobject(args); lua_pushstring("n");
lua_pushnumber(i-1); lua_settable();
return args;
}
static void l_getargs (void) {
char **argv = (char **)lua_getuserdata(lua_getparam(1));
lua_pushobject(getargs(argv));
}
static void file_input (const char *argv) {
int result = ldo(lua_dofile, argv);
if (result) {
if (result == 2) {
fprintf(stderr, "lua: cannot execute file ");
perror(argv);
}
exit(1);
}
}
#define BUF_SIZE 512
static void manual_input (int prompt)
{
static void manual_input (int version, int prompt) {
int cont = 1;
if (version) print_version();
while (cont) {
char buffer[BUF_SIZE];
char buffer[BUFSIZ];
int i = 0;
lua_beginblock();
if (prompt)
printf("%s", lua_getstring(lua_getglobal("_PROMPT")));
if (prompt) {
const char *s = lua_getstring(lua_getglobal("_PROMPT"));
if (!s) s = PROMPT;
fputs(s, stdout);
}
for(;;) {
int c = getchar();
if (c == EOF) {
@@ -112,13 +151,13 @@ static void manual_input (int prompt)
buffer[i-1] = '\n';
else break;
}
else if (i >= BUF_SIZE-1) {
fprintf(stderr, "lua: argument line too long\n");
else if (i >= BUFSIZ-1) {
fprintf(stderr, "lua: input line too long\n");
break;
}
else buffer[i++] = c;
else buffer[i++] = (char)c;
}
buffer[i] = 0;
buffer[i] = '\0';
ldo(lua_dostring, buffer);
lua_endblock();
}
@@ -126,48 +165,76 @@ static void manual_input (int prompt)
}
int main (int argc, char *argv[])
{
int i;
setlocale(LC_ALL, "");
lua_iolibopen();
lua_strlibopen();
lua_mathlibopen();
lua_pushstring("> "); lua_setglobal("_PROMPT");
if (argc < 2) { /* no arguments? */
int main (int argc, char *argv[]) {
int i = 1;
if (i < argc && argv[1][0] == '-' && argv[1][1] == 's') {
int stacksize = atoi(&argv[1][2]);
if (stacksize == 0) {
fprintf(stderr, "lua: invalid stack size ('%s')\n", &argv[1][2]);
exit(1);
}
i++;
lua_state = lua_newstate("stack", stacksize, NULL);
}
else
lua_state = lua_newstate(NULL);
lua_userinit();
lua_pushuserdata(argv);
lua_pushcclosure(l_getargs, 1);
lua_setglobal("getargs");
if (i >= argc) { /* no other arguments? */
if (isatty(0)) {
printf("%s %s\n", LUA_VERSION, LUA_COPYRIGHT);
manual_input(1);
manual_input(1, 1);
}
else
ldo(lua_dofile, NULL); /* executes stdin as a file */
}
else for (i=1; i<argc; i++) {
else for (; i<argc; i++) {
if (argv[i][0] == '-') { /* option? */
switch (argv[i][1]) {
case 0:
ldo(lua_dofile, NULL); /* executes stdin as a file */
break;
case 'i':
manual_input(1);
manual_input(0, 1);
break;
case 'q':
manual_input(0);
manual_input(0, 0);
break;
case 'd':
lua_debug = 1;
lua_setdebug(lua_state, 1);
if (i+1 >= argc) { /* last argument? */
manual_input(1, 1);
}
break;
case 'v':
printf("%s %s\n(written by %s)\n\n",
LUA_VERSION, LUA_COPYRIGHT, LUA_AUTHORS);
print_version();
break;
case 'e':
i++;
if (i >= argc) {
print_message();
exit(1);
}
if (ldo(lua_dostring, argv[i]) != 0) {
fprintf(stderr, "lua: error running argument `%s'\n", argv[i]);
return 1;
exit(1);
}
break;
case 'f':
i++;
if (i >= argc) {
print_message();
exit(1);
}
lua_pushobject(getargs(argv+i)); /* collect remaining arguments */
lua_setglobal("arg");
file_input(argv[i]);
goto endloop; /* stop scanning arguments */
break;
case 's':
fprintf(stderr, "lua: stack size (`-s') must be the first option\n");
exit(1);
default:
print_message();
exit(1);
@@ -175,17 +242,10 @@ int main (int argc, char *argv[])
}
else if (strchr(argv[i], '='))
assign(argv[i]);
else {
int result = ldo(lua_dofile, argv[i]);
if (result) {
if (result == 2) {
fprintf(stderr, "lua: cannot execute file ");
perror(argv[i]);
}
exit(1);
}
}
else
file_input(argv[i]);
}
endloop:
#ifdef DEBUG
lua_close();
#endif

292
lua.h
View File

@@ -1,5 +1,5 @@
/*
** $Id: lua.h,v 1.22 1998/06/15 21:34:14 roberto Exp roberto $
** $Id: lua.h,v 1.47 2000/04/14 17:48:20 roberto Exp roberto $
** Lua - An Extensible Extension Language
** TeCGraf: Grupo de Tecnologia em Computacao Grafica, PUC-Rio, Brazil
** e-mail: lua@tecgraf.puc-rio.br
@@ -11,158 +11,217 @@
#ifndef lua_h
#define lua_h
#define LUA_VERSION "Lua 3.1"
#define LUA_COPYRIGHT "Copyright (C) 1994-1998 TeCGraf, PUC-Rio"
#define LUA_VERSION "Lua 4.0 (alpha)"
#define LUA_COPYRIGHT "Copyright (C) 1994-2000 TeCGraf, PUC-Rio"
#define LUA_AUTHORS "W. Celes, R. Ierusalimschy & L. H. de Figueiredo"
#define LUA_NOOBJECT 0
#define LUA_NOREF (-2)
#define LUA_REFNIL (-1)
#define LUA_ANYTAG (-1)
typedef void (*lua_CFunction) (void);
typedef unsigned int lua_Object;
#define LUA_ANYTAG (-1)
typedef struct lua_State lua_State;
extern lua_State *lua_state;
void lua_open (void);
void lua_close (void);
lua_State *lua_setstate (lua_State *st);
typedef void (*lua_CFunction) (lua_State *L);
lua_Object lua_settagmethod (int tag, char *event); /* In: new method */
lua_Object lua_gettagmethod (int tag, char *event);
lua_Object lua_seterrormethod (void); /* In: new method */
typedef struct TObject *lua_Object;
int lua_newtag (void);
int lua_copytagmethods (int tagto, int tagfrom);
void lua_settag (int tag); /* In: object */
#define LUA_NOOBJECT ((lua_Object)0)
void lua_error (char *s);
int lua_dofile (char *filename); /* Out: returns */
int lua_dostring (char *string); /* Out: returns */
int lua_dobuffer (char *buff, int size, char *name);
/* Out: returns */
int lua_callfunction (lua_Object f);
lua_State *lua_newstate (const char *s, ...);
void lua_close (lua_State *L);
lua_Object lua_settagmethod (lua_State *L, int tag, const char *event);
/* In: new method */
lua_Object lua_gettagmethod (lua_State *L, int tag, const char *event);
int lua_newtag (lua_State *L);
int lua_copytagmethods (lua_State *L, int tagto, int tagfrom);
void lua_settag (lua_State *L, int tag); /* In: object */
void lua_error (lua_State *L, const char *s);
int lua_dofile (lua_State *L, const char *filename);
/* Out: returns */
int lua_dostring (lua_State *L, const char *str);
/* Out: returns */
int lua_dobuffer (lua_State *L, const char *buff, int size,
const char *name); /* Out: returns */
int lua_callfunction (lua_State *L, lua_Object f);
/* In: parameters; Out: returns */
void lua_beginblock (void);
void lua_endblock (void);
void lua_beginblock (lua_State *L);
void lua_endblock (lua_State *L);
lua_Object lua_lua2C (int number);
#define lua_getparam(_) lua_lua2C(_)
#define lua_getresult(_) lua_lua2C(_)
lua_Object lua_lua2C (lua_State *L, int number);
#define lua_getparam lua_lua2C
#define lua_getresult lua_lua2C
int lua_isnil (lua_Object object);
int lua_istable (lua_Object object);
int lua_isuserdata (lua_Object object);
int lua_iscfunction (lua_Object object);
int lua_isnumber (lua_Object object);
int lua_isstring (lua_Object object);
int lua_isfunction (lua_Object object);
const char *lua_type (lua_State *L, lua_Object obj);
double lua_getnumber (lua_Object object);
char *lua_getstring (lua_Object object);
long lua_strlen (lua_Object object);
lua_CFunction lua_getcfunction (lua_Object object);
void *lua_getuserdata (lua_Object object);
int lua_isnil (lua_State *L, lua_Object obj);
int lua_istable (lua_State *L, lua_Object obj);
int lua_isuserdata (lua_State *L, lua_Object obj);
int lua_iscfunction (lua_State *L, lua_Object obj);
int lua_isnumber (lua_State *L, lua_Object obj);
int lua_isstring (lua_State *L, lua_Object obj);
int lua_isfunction (lua_State *L, lua_Object obj);
int lua_equal (lua_State *L, lua_Object o1, lua_Object o2);
double lua_getnumber (lua_State *L, lua_Object obj);
const char *lua_getstring (lua_State *L, lua_Object obj);
long lua_strlen (lua_State *L, lua_Object obj);
lua_CFunction lua_getcfunction (lua_State *L, lua_Object obj);
void *lua_getuserdata (lua_State *L, lua_Object obj);
void lua_pushnil (void);
void lua_pushnumber (double n);
void lua_pushlstring (char *s, long len);
void lua_pushstring (char *s);
void lua_pushcclosure (lua_CFunction fn, int n);
void lua_pushusertag (void *u, int tag);
void lua_pushobject (lua_Object object);
void lua_pushnil (lua_State *L);
void lua_pushnumber (lua_State *L, double n);
void lua_pushlstring (lua_State *L, const char *s, long len);
void lua_pushstring (lua_State *L, const char *s);
void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);
void lua_pushusertag (lua_State *L, void *u, int tag);
void lua_pushobject (lua_State *L, lua_Object obj);
lua_Object lua_pop (void);
lua_Object lua_pop (lua_State *L);
lua_Object lua_getglobal (char *name);
lua_Object lua_rawgetglobal (char *name);
void lua_setglobal (char *name); /* In: value */
void lua_rawsetglobal (char *name); /* In: value */
lua_Object lua_getglobal (lua_State *L, const char *name);
lua_Object lua_rawgetglobal (lua_State *L, const char *name);
void lua_setglobal (lua_State *L, const char *name); /* In: value */
void lua_rawsetglobal (lua_State *L, const char *name);/* In: value */
void lua_settable (void); /* In: table, index, value */
void lua_rawsettable (void); /* In: table, index, value */
lua_Object lua_gettable (void); /* In: table, index */
lua_Object lua_rawgettable (void); /* In: table, index */
void lua_settable (lua_State *L); /* In: table, index, value */
void lua_rawsettable (lua_State *L); /* In: table, index, value */
lua_Object lua_gettable (lua_State *L); /* In: table, index */
lua_Object lua_rawgettable (lua_State *L); /* In: table, index */
int lua_tag (lua_Object object);
int lua_tag (lua_State *L, lua_Object obj);
const char *lua_nextvar (lua_State *L, const char *varname); /* Out: value */
int lua_next (lua_State *L, lua_Object o, int i);
/* Out: ref, value */
int lua_ref (lua_State *L, int lock); /* In: value */
lua_Object lua_getref (lua_State *L, int ref);
void lua_unref (lua_State *L, int ref);
lua_Object lua_createtable (lua_State *L);
long lua_collectgarbage (lua_State *L, long limit);
int lua_ref (int lock); /* In: value */
lua_Object lua_getref (int ref);
void lua_unref (int ref);
lua_Object lua_createtable (void);
long lua_collectgarbage (long limit);
/* =============================================================== */
/* some useful macros/derived functions */
int (lua_call) (char *name);
#define lua_call(name) lua_callfunction(lua_getglobal(name))
void (lua_pushref) (int ref);
#define lua_pushref(ref) lua_pushobject(lua_getref(ref))
int (lua_refobject) (lua_Object o, int l);
#define lua_refobject(o,l) (lua_pushobject(o), lua_ref(l))
void (lua_register) (char *n, lua_CFunction f);
#define lua_register(n,f) (lua_pushcfunction(f), lua_setglobal(n))
void (lua_pushuserdata) (void *u);
#define lua_pushuserdata(u) lua_pushusertag(u, 0)
void (lua_pushcfunction) (lua_CFunction f);
#define lua_pushcfunction(f) lua_pushcclosure(f, 0)
int (lua_clonetag) (int t);
#define lua_clonetag(t) lua_copytagmethods(lua_newtag(), (t))
/* ==========================================================================
** for compatibility with old versions. Avoid using these macros/functions
** If your program does need any of these, define LUA_COMPAT2_5
/*
** ===============================================================
** some useful macros
** ===============================================================
*/
#ifdef LUA_REENTRANT
#ifdef LUA_COMPAT2_5
#define lua_call(L,name) lua_callfunction(L, lua_getglobal(L, name))
#define lua_pushref(L,ref) lua_pushobject(L, lua_getref(L, ref))
#define lua_refobject(L,o,l) (lua_pushobject(L, o), lua_ref(L, l))
#define lua_register(L,n,f) (lua_pushcfunction(L, f), lua_setglobal(L, n))
#define lua_pushuserdata(L,u) lua_pushusertag(L, u, 0)
#define lua_pushcfunction(L,f) lua_pushcclosure(L, f, 0)
#define lua_clonetag(L,t) lua_copytagmethods(L, lua_newtag(L), (t))
#else
lua_Object lua_setfallback (char *event, lua_CFunction fallback);
#define lua_storeglobal lua_setglobal
#define lua_type lua_tag
#define lua_lockobject(o) lua_refobject(o,1)
#define lua_lock() lua_ref(1)
#define lua_getlocked lua_getref
#define lua_pushlocked lua_pushref
#define lua_unlock lua_unref
#define lua_pushliteral(o) lua_pushstring(o)
#define lua_getindexed(o,n) (lua_pushobject(o), lua_pushnumber(n), lua_gettable())
#define lua_getfield(o,f) (lua_pushobject(o), lua_pushstring(f), lua_gettable())
#define lua_copystring(o) (strdup(lua_getstring(o)))
#define lua_getsubscript lua_gettable
#define lua_storesubscript lua_settable
#define lua_call(name) lua_callfunction(lua_getglobal(name))
#define lua_pushref(ref) lua_pushobject(lua_getref(ref))
#define lua_refobject(o,l) (lua_pushobject(o), lua_ref(l))
#define lua_register(n,f) (lua_pushcfunction(f), lua_setglobal(n))
#define lua_pushuserdata(u) lua_pushusertag(u, 0)
#define lua_pushcfunction(f) lua_pushcclosure(f, 0)
#define lua_clonetag(t) lua_copytagmethods(lua_newtag(), (t))
#endif
#ifndef LUA_REENTRANT
/*
** ===============================================================
** Macros for single-state use
** ===============================================================
*/
extern lua_State *lua_state;
#define lua_open() ((void)(lua_state?0:(lua_state=lua_newstate(0))))
#define lua_close() (lua_close)(lua_state)
#define lua_settagmethod(tag,event) (lua_settagmethod)(lua_state, tag,event)
#define lua_gettagmethod(tag,event) (lua_gettagmethod)(lua_state, tag,event)
#define lua_newtag() (lua_newtag)(lua_state)
#define lua_copytagmethods(tagto,tagfrom) \
(lua_copytagmethods)(lua_state, tagto,tagfrom)
#define lua_settag(tag) (lua_settag)(lua_state, tag)
#define lua_error(s) (lua_error)(lua_state, s)
#define lua_dofile(filename) (lua_dofile)(lua_state, filename)
#define lua_dostring(str) (lua_dostring)(lua_state, str)
#define lua_callfunction(f) (lua_callfunction)(lua_state, f)
#define lua_beginblock() (lua_beginblock)(lua_state)
#define lua_endblock() (lua_endblock)(lua_state)
#define lua_lua2C(number) (lua_lua2C)(lua_state, number)
#define lua_type(obj) (lua_type)(lua_state, obj)
#define lua_isnil(obj) (lua_isnil)(lua_state, obj)
#define lua_istable(obj) (lua_istable)(lua_state, obj)
#define lua_isuserdata(obj) (lua_isuserdata)(lua_state, obj)
#define lua_iscfunction(obj) (lua_iscfunction)(lua_state, obj)
#define lua_isnumber(obj) (lua_isnumber)(lua_state, obj)
#define lua_isstring(obj) (lua_isstring)(lua_state, obj)
#define lua_isfunction(obj) (lua_isfunction)(lua_state, obj)
#define lua_equal(o1,o2) (lua_equal)(lua_state, o1,o2)
#define lua_getnumber(obj) (lua_getnumber)(lua_state, obj)
#define lua_getstring(obj) (lua_getstring)(lua_state, obj)
#define lua_strlen(obj) (lua_strlen)(lua_state, obj)
#define lua_getcfunction(obj) (lua_getcfunction)(lua_state, obj)
#define lua_getuserdata(obj) (lua_getuserdata)(lua_state, obj)
#define lua_pushnil() (lua_pushnil)(lua_state)
#define lua_pushnumber(n) (lua_pushnumber)(lua_state, n)
#define lua_pushlstring(s,len) (lua_pushlstring)(lua_state, s,len)
#define lua_pushstring(s) (lua_pushstring)(lua_state, s)
#define lua_pushusertag(u,tag) (lua_pushusertag)(lua_state, u,tag)
#define lua_pushobject(obj) (lua_pushobject)(lua_state, obj)
#define lua_pop() (lua_pop)(lua_state)
#define lua_getglobal(name) (lua_getglobal)(lua_state, name)
#define lua_rawgetglobal(name) (lua_rawgetglobal)(lua_state, name)
#define lua_setglobal(name) (lua_setglobal)(lua_state, name)
#define lua_rawsetglobal(name) (lua_rawsetglobal)(lua_state, name)
#define lua_settable() (lua_settable)(lua_state)
#define lua_rawsettable() (lua_rawsettable)(lua_state)
#define lua_gettable() (lua_gettable)(lua_state)
#define lua_rawgettable() (lua_rawgettable)(lua_state)
#define lua_tag(obj) (lua_tag)(lua_state, obj)
#define lua_nextvar(varname) (lua_nextvar)(lua_state, varname)
#define lua_next(o,i) (lua_next)(lua_state, o,i)
#define lua_ref(lock) (lua_ref)(lua_state, lock)
#define lua_getref(ref) (lua_getref)(lua_state, ref)
#define lua_unref(ref) (lua_unref)(lua_state, ref)
#define lua_createtable() (lua_createtable)(lua_state)
#define lua_collectgarbage(limit) (lua_collectgarbage)(lua_state, limit)
/*
** the following typecast is a little dirty, but we know of no other
** way to keep compatibility with old definition of `lua_CFunction'
*/
#define lua_pushcclosure(fn,n) \
(lua_pushcclosure)(lua_state, (lua_CFunction)(fn), n)
#endif
#endif
/******************************************************************************
* Copyright (c) 1994-1998 TeCGraf, PUC-Rio. All rights reserved.
* Copyright (C) 1994-2000 TeCGraf, PUC-Rio. All rights reserved.
*
* Permission is hereby granted, without written agreement and without license
* or royalty fees, to use, copy, modify, and distribute this software and its
@@ -192,5 +251,6 @@ lua_Object lua_setfallback (char *event, lua_CFunction fallback);
* The Lua language and this implementation have been entirely designed and
* written by Waldemar Celes Filho, Roberto Ierusalimschy and
* Luiz Henrique de Figueiredo at TeCGraf, PUC-Rio.
*
* This implementation contains no third-party code.
******************************************************************************/

View File

@@ -1,5 +1,5 @@
/*
** $Id: luadebug.h,v 1.1 1997/09/16 19:25:59 roberto Exp roberto $
** $Id: luadebug.h,v 1.9 2000/01/19 12:00:45 roberto Exp roberto $
** Debugging API
** See Copyright Notice in lua.h
*/
@@ -11,23 +11,44 @@
#include "lua.h"
typedef lua_Object lua_Function;
typedef struct lua_Debug lua_Debug; /* activation record */
typedef struct lua_Localvar lua_Localvar;
typedef void (*lua_LHFunction) (int line);
typedef void (*lua_CHFunction) (lua_Function func, char *file, int line);
lua_Function lua_stackedfunction (int level);
void lua_funcinfo (lua_Object func, char **filename, int *linedefined);
int lua_currentline (lua_Function func);
char *lua_getobjname (lua_Object o, char **name);
lua_Object lua_getlocal (lua_Function func, int local_number, char **name);
int lua_setlocal (lua_Function func, int local_number);
typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);
extern lua_LHFunction lua_linehook;
extern lua_CHFunction lua_callhook;
extern int lua_debug;
int lua_getstack (lua_State *L, int level, lua_Debug *ar);
int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);
int lua_getlocal (lua_State *L, const lua_Debug *ar, lua_Localvar *v);
int lua_setlocal (lua_State *L, const lua_Debug *ar, lua_Localvar *v);
int lua_setdebug (lua_State *L, int debug);
lua_Hook lua_setcallhook (lua_State *L, lua_Hook func);
lua_Hook lua_setlinehook (lua_State *L, lua_Hook func);
struct lua_Debug {
const char *event; /* `call', `return' */
const char *source; /* (S) */
int linedefined; /* (S) */
const char *what; /* (S) `Lua' function, `C' function, Lua `main' */
int currentline; /* (l) */
const char *name; /* (n) */
const char *namewhat; /* (n) global, tag method, local, field */
int nups; /* (u) number of upvalues */
lua_Object func; /* (f) function being executed */
/* private part */
lua_Object _func; /* active function */
};
struct lua_Localvar {
int index;
const char *name;
lua_Object value;
};
#endif

View File

@@ -1,5 +1,5 @@
/*
** $Id: lualib.h,v 1.3 1997/12/17 20:48:58 roberto Exp roberto $
** $Id: lualib.h,v 1.7 1999/08/16 20:52:00 roberto Exp roberto $
** Lua standard libraries
** See Copyright Notice in lua.h
*/
@@ -10,25 +10,36 @@
#include "lua.h"
void lua_iolibopen (void);
void lua_strlibopen (void);
void lua_mathlibopen (void);
void lua_iolibopen (lua_State *L);
void lua_strlibopen (lua_State *L);
void lua_mathlibopen (lua_State *L);
void lua_dblibopen (lua_State *L);
void lua_userinit (lua_State *L);
/* To keep compatibility with old versions */
/*
** ===============================================================
** Macros for single-state use
** ===============================================================
*/
#define iolib_open lua_iolibopen
#define strlib_open lua_strlibopen
#define mathlib_open lua_mathlibopen
#ifndef LUA_REENTRANT
#define lua_iolibopen() (lua_iolibopen)(lua_state)
#define lua_strlibopen() (lua_strlibopen)(lua_state)
#define lua_mathlibopen() (lua_mathlibopen)(lua_state)
#define lua_dblibopen() (lua_dblibopen)(lua_state)
#define lua_userinit() (lua_userinit)(lua_state)
#endif
/* Auxiliary functions (private) */
int luaI_singlematch (int c, char *p, char **ep);
const char *luaI_classend (lua_State *L, const char *p);
int luaI_singlematch (int c, const char *p, const char *ep);
#endif

326
lundump.c
View File

@@ -1,226 +1,278 @@
/*
** $Id: lundump.c,v 1.10 1998/06/25 15:50:09 lhf Exp $
** $Id: lundump.c,v 1.28 2000/04/24 19:32:58 lhf Exp $
** load bytecodes from files
** See Copyright Notice in lua.h
*/
#include <stdio.h>
#include <string.h>
#define LUA_REENTRANT
#include "lauxlib.h"
#include "lfunc.h"
#include "lmem.h"
#include "lopcodes.h"
#include "lstring.h"
#include "lundump.h"
#define LoadBlock(b,size,Z) ezread(Z,b,size)
#define LoadNative(t,Z) LoadBlock(&t,sizeof(t),Z)
#define LoadBlock(L,b,size,Z) ezread(L,Z,b,size)
#define LoadByte ezgetc
#if ID_NUMBER==ID_NATIVE
#define doLoadNumber(f,Z) LoadNative(f,Z)
#else
#define doLoadNumber(f,Z) f=LoadNumber(Z)
#endif
static void unexpectedEOZ(ZIO* Z)
static const char* ZNAME(ZIO* Z)
{
luaL_verror("unexpected end of file in %s",zname(Z));
const char* s=zname(Z);
return (*s=='@') ? s+1 : s;
}
static int ezgetc(ZIO* Z)
static void unexpectedEOZ (lua_State* L, ZIO* Z)
{
luaL_verror(L,"unexpected end of file in `%.255s'",ZNAME(Z));
}
static int ezgetc (lua_State* L, ZIO* Z)
{
int c=zgetc(Z);
if (c==EOZ) unexpectedEOZ(Z);
if (c==EOZ) unexpectedEOZ(L,Z);
return c;
}
static void ezread(ZIO* Z, void* b, int n)
static void ezread (lua_State* L, ZIO* Z, void* b, int n)
{
int r=zread(Z,b,n);
if (r!=0) unexpectedEOZ(Z);
if (r!=0) unexpectedEOZ(L,Z);
}
static unsigned int LoadWord(ZIO* Z)
static unsigned int LoadWord (lua_State* L, ZIO* Z)
{
unsigned int hi=ezgetc(Z);
unsigned int lo=ezgetc(Z);
unsigned int hi=ezgetc(L,Z);
unsigned int lo=ezgetc(L,Z);
return (hi<<8)|lo;
}
static unsigned long LoadLong(ZIO* Z)
static unsigned long LoadLong (lua_State* L, ZIO* Z)
{
unsigned long hi=LoadWord(Z);
unsigned long lo=LoadWord(Z);
unsigned long hi=LoadWord(L,Z);
unsigned long lo=LoadWord(L,Z);
return (hi<<16)|lo;
}
#if ID_NUMBER==ID_REAL4
/* LUA_NUMBER */
/* assumes sizeof(long)==4 and sizeof(float)==4 (IEEE) */
static float LoadFloat(ZIO* Z)
static Number LoadNumber (lua_State* L, ZIO* Z)
{
unsigned long l=LoadLong(Z);
float f=*(float*)&l;
return f;
}
#endif
#if ID_NUMBER==ID_REAL8
/* LUA_NUMBER */
/* assumes sizeof(long)==4 and sizeof(double)==8 (IEEE) */
static double LoadDouble(ZIO* Z)
{
unsigned long l[2];
double f;
int x=1;
if (*(char*)&x==1) /* little-endian */
{
l[1]=LoadLong(Z);
l[0]=LoadLong(Z);
}
else /* big-endian */
{
l[0]=LoadLong(Z);
l[1]=LoadLong(Z);
}
f=*(double*)l;
return f;
}
#endif
static Byte* LoadCode(ZIO* Z)
{
unsigned long size=LoadLong(Z);
unsigned int s=size;
void* b;
if (s!=size) luaL_verror("code too long (%ld bytes) in %s",size,zname(Z));
b=luaM_malloc(size);
LoadBlock(b,size,Z);
return b;
char b[256];
int size=ezgetc(L,Z);
LoadBlock(L,b,size,Z);
b[size]=0;
return luaU_str2d(L,b,ZNAME(Z));
}
static TaggedString* LoadTString(ZIO* Z)
static int LoadInt (lua_State* L, ZIO* Z, const char* message)
{
int size=LoadWord(Z);
unsigned long l=LoadLong(L,Z);
unsigned int i=l;
if (i!=l) luaL_verror(L,"%s in `%.255s';\n"
" read %lu; expected %u",message,ZNAME(Z),l,-1);
return i;
}
static TString* LoadString (lua_State* L, ZIO* Z)
{
long size=LoadLong(L,Z);
if (size==0)
return NULL;
else
{
char* s=luaL_openspace(size);
LoadBlock(s,size,Z);
return luaS_newlstr(s,size-1);
char* s=luaL_openspace(L,size);
LoadBlock(L,s,size,Z);
return luaS_newlstr(L,s,size-1); /* remove trailing '\0' */
}
}
static void LoadLocals(TProtoFunc* tf, ZIO* Z)
static void SwapCode (lua_State* L, Instruction* code, int size, ZIO* Z)
{
int i,n=LoadWord(Z);
unsigned char* p;
int c;
if (sizeof(Instruction)==4)
while (size--)
{
p=(unsigned char *) code++;
c=p[0]; p[0]=p[3]; p[3]=c;
c=p[1]; p[1]=p[2]; p[2]=c;
}
else if (sizeof(Instruction)==2)
while (size--)
{
p=(unsigned char *) code++;
c=p[0]; p[0]=p[1]; p[1]=c;
}
else
luaL_verror(L,"cannot swap code with %d-byte instructions in `%.255s'",
(int)sizeof(Instruction),ZNAME(Z));
}
static void LoadCode (lua_State* L, Proto* tf, ZIO* Z)
{
int size=LoadInt(L,Z,"code too long");
Instruction t=0,tt=TEST_CODE;
tf->code=luaM_newvector(L,size,Instruction);
LoadBlock(L,tf->code,size*sizeof(*tf->code),Z);
if (tf->code[size-1]!=OP_END) luaL_verror(L,"bad code in `%.255s'",ZNAME(Z));
LoadBlock(L,&t,sizeof(t),Z);
if (t!=tt)
{
Instruction ot=t;
SwapCode(L,&t,1,Z);
if (t!=tt) luaL_verror(L,"cannot swap code in `%.255s';\n"
" read 0x%08X; swapped to 0x%08X; expected 0x%08X",
ZNAME(Z),(unsigned long)ot,(unsigned long)t,(unsigned long)tt);
SwapCode(L,tf->code,size,Z);
}
}
static void LoadLocals (lua_State* L, Proto* tf, ZIO* Z)
{
int i,n=LoadInt(L,Z,"too many locals");
if (n==0) return;
tf->locvars=luaM_newvector(n+1,LocVar);
tf->locvars=luaM_newvector(L,n+1,LocVar);
for (i=0; i<n; i++)
{
tf->locvars[i].line=LoadWord(Z);
tf->locvars[i].varname=LoadTString(Z);
tf->locvars[i].line=LoadInt(L,Z,"too many lines");
tf->locvars[i].varname=LoadString(L,Z);
}
tf->locvars[i].line=-1; /* flag end of vector */
tf->locvars[i].varname=NULL;
}
static TProtoFunc* LoadFunction(ZIO* Z);
static Proto* LoadFunction (lua_State* L, ZIO* Z, int native);
static void LoadConstants(TProtoFunc* tf, ZIO* Z)
static void LoadConstants (lua_State* L, Proto* tf, ZIO* Z, int native)
{
int i,n=LoadWord(Z);
tf->nconsts=n;
if (n==0) return;
tf->consts=luaM_newvector(n,TObject);
for (i=0; i<n; i++)
int i,n;
tf->nkstr=n=LoadInt(L,Z,"too many strings");
if (n>0)
{
TObject* o=tf->consts+i;
int c=ezgetc(Z);
switch (c)
tf->kstr=luaM_newvector(L,n,TString*);
for (i=0; i<n; i++)
{
case ID_NUM:
ttype(o)=LUA_T_NUMBER;
doLoadNumber(nvalue(o),Z);
break;
case ID_STR:
ttype(o)=LUA_T_STRING;
tsvalue(o)=LoadTString(Z);
break;
case ID_FUN:
ttype(o)=LUA_T_PROTO;
tfvalue(o)=LoadFunction(Z);
break;
default:
luaL_verror("bad constant #%d in %s: type=%d ('%c')",i,zname(Z),c,c);
break;
TString* s=LoadString(L,Z);
int isglobal=LoadByte(L,Z);
if (isglobal) luaS_assertglobal(L,s);
tf->kstr[i]=s;
}
}
tf->nknum=n=LoadInt(L,Z,"too many numbers");
if (n>0)
{
tf->knum=luaM_newvector(L,n,Number);
if (native)
LoadBlock(L,tf->knum,n*sizeof(*tf->knum),Z);
else
for (i=0; i<n; i++) tf->knum[i]=LoadNumber(L,Z);
}
tf->nkproto=n=LoadInt(L,Z,"too many functions");
if (n>0)
{
tf->kproto=luaM_newvector(L,n,Proto*);
for (i=0; i<n; i++) tf->kproto[i]=LoadFunction(L,Z,native);
}
}
static TProtoFunc* LoadFunction(ZIO* Z)
static Proto* LoadFunction (lua_State* L, ZIO* Z, int native)
{
TProtoFunc* tf=luaF_newproto();
tf->lineDefined=LoadWord(Z);
tf->fileName=LoadTString(Z);
tf->code=LoadCode(Z);
LoadLocals(tf,Z);
LoadConstants(tf,Z);
Proto* tf=luaF_newproto(L);
tf->source=LoadString(L,Z);
if (tf->source==NULL) tf->source=luaS_new(L,zname(Z));
tf->lineDefined=LoadInt(L,Z,"lineDefined too large");
tf->numparams=LoadInt(L,Z,"too many parameters");
tf->is_vararg=LoadByte(L,Z);
tf->maxstacksize=LoadInt(L,Z,"too much stack needed");
LoadCode(L,tf,Z);
LoadLocals(L,tf,Z);
LoadConstants(L,tf,Z,native);
return tf;
}
static void LoadSignature(ZIO* Z)
static void LoadSignature (lua_State* L, ZIO* Z)
{
char* s=SIGNATURE;
while (*s!=0 && ezgetc(Z)==*s)
const char* s=SIGNATURE;
while (*s!=0 && ezgetc(L,Z)==*s)
++s;
if (*s!=0) luaL_verror("bad signature in %s",zname(Z));
if (*s!=0) luaL_verror(L,"bad signature in `%.255s'",ZNAME(Z));
}
static void LoadHeader(ZIO* Z)
#define V(v) v/16,v%16
static int LoadHeader (lua_State* L, ZIO* Z)
{
int version,id,sizeofR;
real f=-TEST_NUMBER,tf=TEST_NUMBER;
LoadSignature(Z);
version=ezgetc(Z);
int version,sizeofR,native;
LoadSignature(L,Z);
version=ezgetc(L,Z);
if (version>VERSION)
luaL_verror(
"%s too new: version=0x%02x; expected at most 0x%02x",
zname(Z),version,VERSION);
luaL_verror(L,"`%.255s' too new:\n"
" read version %d.%d; expected at most %d.%d",
ZNAME(Z),V(version),V(VERSION));
if (version<VERSION0) /* check last major change */
luaL_verror(
"%s too old: version=0x%02x; expected at least 0x%02x",
zname(Z),version,VERSION0);
id=ezgetc(Z); /* test number representation */
sizeofR=ezgetc(Z);
if (id!=ID_NUMBER || sizeofR!=sizeof(real))
luaL_verror(L,"`%.255s' too old:\n"
" read version %d.%d; expected at least %d.%d",
ZNAME(Z),V(version),V(VERSION));
{
luaL_verror("unknown number signature in %s: "
"read 0x%02x%02x; expected 0x%02x%02x",
zname(Z),id,sizeofR,ID_NUMBER,sizeof(real));
int I=ezgetc(L,Z);
int i=ezgetc(L,Z);
int op=ezgetc(L,Z);
int b=ezgetc(L,Z);
if (I!=sizeof(Instruction) || i!=SIZE_INSTRUCTION || op!=SIZE_OP || b!=SIZE_B)
luaL_verror(L,"virtual machine mismatch in `%.255s':\n"
" read %d-bit,%d-byte instructions, %d-bit opcodes, %d-bit b-arguments;\n"
" expected %d-bit,%d-byte instructions, %d-bit opcodes, %d-bit b-arguments",
ZNAME(Z),i,I,op,b,SIZE_INSTRUCTION,(int)sizeof(Instruction),SIZE_OP,SIZE_B);
}
doLoadNumber(f,Z);
if (f!=tf)
luaL_verror("unknown number representation in %s: "
"read " NUMBER_FMT "; expected " NUMBER_FMT "", /* LUA_NUMBER */
zname(Z),(double)f,(double)tf);
sizeofR=ezgetc(L,Z);
native=(sizeofR!=0);
if (native) /* test number representation */
{
if (sizeofR!=sizeof(Number))
luaL_verror(L,"native number size mismatch in `%.255s':\n"
" read %d; expected %d",
ZNAME(Z),sizeofR,(int)sizeof(Number));
else
{
Number f=0,tf=TEST_NUMBER;
LoadBlock(L,&f,sizeof(f),Z);
if ((long)f!=(long)tf) /* disregard errors in last bit of fraction */
luaL_verror(L,"unknown number format in `%.255s':\n"
" read " NUMBER_FMT "; expected " NUMBER_FMT,
ZNAME(Z),f,tf);
}
}
return native;
}
static TProtoFunc* LoadChunk(ZIO* Z)
static Proto* LoadChunk (lua_State* L, ZIO* Z)
{
LoadHeader(Z);
return LoadFunction(Z);
return LoadFunction(L,Z,LoadHeader(L,Z));
}
/*
** load one chunk from a file or buffer
** return main if ok and NULL at EOF
*/
TProtoFunc* luaU_undump1(ZIO* Z)
Proto* luaU_undump1 (lua_State* L, ZIO* Z)
{
int c=zgetc(Z);
if (c==ID_CHUNK)
return LoadChunk(Z);
return LoadChunk(L,Z);
else if (c!=EOZ)
luaL_verror("%s is not a Lua binary file",zname(Z));
luaL_verror(L,"`%.255s' is not a Lua binary file",ZNAME(Z));
return NULL;
}
/*
* convert number from text
*/
double luaU_str2d (lua_State* L, const char* b, const char* where)
{
double x;
if (!luaO_str2d(b,&x))
luaL_verror(L,"cannot convert number `%.255s' in `%.255s'",b,where);
return x;
}

View File

@@ -1,5 +1,5 @@
/*
** $Id: lundump.h,v 1.7 1998/06/25 15:50:09 lhf Exp $
** $Id: lundump.h,v 1.19 2000/04/24 17:32:29 lhf Exp $
** load pre-compiled Lua chunks
** See Copyright Notice in lua.h
*/
@@ -10,72 +10,34 @@
#include "lobject.h"
#include "lzio.h"
TProtoFunc* luaU_undump1(ZIO* Z); /* load one chunk */
/* load one chunk */
Proto* luaU_undump1 (lua_State* L, ZIO* Z);
#define SIGNATURE "Lua"
#define VERSION 0x31 /* last format change was in 3.1 */
#define VERSION0 0x31 /* last major change was in 3.1 */
/* convert number from text */
double luaU_str2d (lua_State* L, const char* b, const char* where);
#define IsMain(f) (f->lineDefined==0)
/* definitions for headers of binary files */
#define VERSION 0x40 /* last format change was in 4.0 */
#define VERSION0 0x40 /* last major change was in 4.0 */
#define ID_CHUNK 27 /* binary files start with ESC... */
#define SIGNATURE "Lua" /* ...followed by this signature */
#define ID_CHUNK 27 /* ESC */
#define ID_NUM 'N'
#define ID_STR 'S'
#define ID_FUN 'F'
/* formats for error messages */
#define xSOURCE "<%d:%.255s>"
#define SOURCE "<%.255s:%d>"
#define IN " in %p " SOURCE
#define INLOC tf,tf->source->str,tf->lineDefined
/* number representation */
#define ID_INT4 'l' /* 4-byte integers */
#define ID_REAL4 'f' /* 4-byte reals */
#define ID_REAL8 'd' /* 8-byte reals */
#define ID_NATIVE '?' /* whatever your machine uses */
/* format for numbers in listings and error messages */
#ifndef NUMBER_FMT
#define NUMBER_FMT "%.16g" /* LUA_NUMBER */
#endif
/*
* use a multiple of PI for testing number representation.
* multiplying by 1E8 gives notrivial integer values.
*/
/* a multiple of PI for testing native format */
/* multiplying by 1E8 gives non-trivial integer values */
#define TEST_NUMBER 3.14159265358979323846E8
/* LUA_NUMBER
* choose one below for the number representation in precompiled chunks.
* the default is ID_REAL8 because the default for LUA_NUM_TYPE is double.
* if your machine does not use IEEE 754, use ID_NATIVE.
* the next version will support conversion to/from IEEE 754.
*
* if you change LUA_NUM_TYPE, make sure you set ID_NUMBER accordingly,
* specially if sizeof(long)!=4.
* for types other than the ones listed below, you'll have to write your own
* dump and undump routines.
*/
#ifndef ID_NUMBER
#define ID_NUMBER ID_NATIVE
#endif
#if 0
#define ID_NUMBER ID_INT4
#define ID_NUMBER ID_REAL4
#define ID_NUMBER ID_REAL8
#define ID_NUMBER ID_NATIVE
#endif
/* something for testing byte order in instructions */
#define TEST_CODE 0x01020304
#endif
#if ID_NUMBER==ID_REAL4
#define DumpNumber DumpFloat
#define LoadNumber LoadFloat
#define SIZEOF_NUMBER 4
#elif ID_NUMBER==ID_REAL8
#define DumpNumber DumpDouble
#define LoadNumber LoadDouble
#define SIZEOF_NUMBER 8
#elif ID_NUMBER==ID_INT4
#define DumpNumber DumpLong
#define LoadNumber LoadLong
#define SIZEOF_NUMBER 4
#elif ID_NUMBER==ID_NATIVE
#define DumpNumber DumpNative
#define LoadNumber LoadNative
#define SIZEOF_NUMBER sizeof(real)
#else
#error bad ID_NUMBER
#endif

1066
lvm.c

File diff suppressed because it is too large Load Diff

27
lvm.h
View File

@@ -1,5 +1,5 @@
/*
** $Id: lvm.h,v 1.3 1997/10/16 10:59:34 roberto Exp roberto $
** $Id: lvm.h,v 1.20 2000/03/29 20:19:20 roberto Exp roberto $
** Lua virtual machine
** See Copyright Notice in lua.h
*/
@@ -10,20 +10,25 @@
#include "ldo.h"
#include "lobject.h"
#include "ltm.h"
#define tonumber(o) ((ttype(o) != LUA_T_NUMBER) && (luaV_tonumber(o) != 0))
#define tostring(o) ((ttype(o) != LUA_T_STRING) && (luaV_tostring(o) != 0))
#define tonumber(o) ((ttype(o) != TAG_NUMBER) && (luaV_tonumber(o) != 0))
#define tostring(L,o) ((ttype(o) != TAG_STRING) && (luaV_tostring(L, o) != 0))
void luaV_pack (StkId firstel, int nvararg, TObject *tab);
void luaV_pack (lua_State *L, StkId firstel, int nvararg, TObject *tab);
int luaV_tonumber (TObject *obj);
int luaV_tostring (TObject *obj);
void luaV_gettable (void);
void luaV_settable (TObject *t, int mode);
void luaV_getglobal (TaggedString *ts);
void luaV_setglobal (TaggedString *ts);
StkId luaV_execute (Closure *cl, TProtoFunc *tf, StkId base);
void luaV_closure (int nelems);
int luaV_tostring (lua_State *L, TObject *obj);
void luaV_setn (lua_State *L, Hash *t, int val);
void luaV_gettable (lua_State *L, StkId top);
void luaV_settable (lua_State *L, StkId t, StkId top);
void luaV_rawsettable (lua_State *L, StkId t);
void luaV_getglobal (lua_State *L, GlobalVar *gv, StkId top);
void luaV_setglobal (lua_State *L, GlobalVar *gv, StkId top);
StkId luaV_execute (lua_State *L, const Closure *cl, StkId base);
void luaV_Cclosure (lua_State *L, lua_CFunction c, int nelems);
void luaV_Lclosure (lua_State *L, Proto *l, int nelems);
int luaV_lessthan (lua_State *L, const TObject *l, const TObject *r, StkId top);
#endif

74
lzio.c
View File

@@ -1,5 +1,5 @@
/*
** $Id: lzio.c,v 1.2 1997/11/21 19:00:46 roberto Exp roberto $
** $Id: lzio.c,v 1.10 2000/02/08 16:39:42 roberto Exp roberto $
** a generic input stream interface
** See Copyright Notice in lua.h
*/
@@ -15,65 +15,63 @@
/* ----------------------------------------------------- memory buffers --- */
static int zmfilbuf (ZIO* z)
{
return EOZ;
static int zmfilbuf (ZIO* z) {
(void)z; /* to avoid warnings */
return EOZ;
}
ZIO* zmopen (ZIO* z, char* b, int size, char *name)
{
if (b==NULL) return NULL;
z->n=size;
z->p= (unsigned char *)b;
z->filbuf=zmfilbuf;
z->u=NULL;
z->name=name;
return z;
ZIO* zmopen (ZIO* z, const char* b, int size, const char *name) {
if (b==NULL) return NULL;
z->n = size;
z->p = (const unsigned char *)b;
z->filbuf = zmfilbuf;
z->u = NULL;
z->name = name;
return z;
}
/* ------------------------------------------------------------ strings --- */
ZIO* zsopen (ZIO* z, char* s, char *name)
{
if (s==NULL) return NULL;
return zmopen(z,s,strlen(s),name);
ZIO* zsopen (ZIO* z, const char* s, const char *name) {
if (s==NULL) return NULL;
return zmopen(z, s, strlen(s), name);
}
/* -------------------------------------------------------------- FILEs --- */
static int zffilbuf (ZIO* z)
{
int n=fread(z->buffer,1,ZBSIZE,z->u);
if (n==0) return EOZ;
z->n=n-1;
z->p=z->buffer;
return *(z->p++);
static int zffilbuf (ZIO* z) {
int n;
if (feof((FILE *)z->u)) return EOZ;
n = fread(z->buffer, 1, ZBSIZE, (FILE *)z->u);
if (n==0) return EOZ;
z->n = n-1;
z->p = z->buffer;
return *(z->p++);
}
ZIO* zFopen (ZIO* z, FILE* f, char *name)
{
if (f==NULL) return NULL;
z->n=0;
z->p=z->buffer;
z->filbuf=zffilbuf;
z->u=f;
z->name=name;
return z;
ZIO* zFopen (ZIO* z, FILE* f, const char *name) {
if (f==NULL) return NULL;
z->n = 0;
z->p = z->buffer;
z->filbuf = zffilbuf;
z->u = f;
z->name = name;
return z;
}
/* --------------------------------------------------------------- read --- */
int zread (ZIO *z, void *b, int n)
{
int zread (ZIO *z, void *b, int n) {
while (n) {
int m;
if (z->n == 0) {
if (z->filbuf(z) == EOZ)
return n; /* retorna quantos faltaram ler */
zungetc(z); /* poe o resultado de filbuf no buffer */
return n; /* return number of missing bytes */
zungetc(z); /* put result from `filbuf' in the buffer */
}
m = (n <= z->n) ? n : z->n; /* minimo de n e z->n */
m = (n <= z->n) ? n : z->n; /* min. between n and z->n */
memcpy(b, z->p, m);
z->n -= m;
z->p += m;

20
lzio.h
View File

@@ -1,5 +1,5 @@
/*
** $Id: lzio.h,v 1.3 1997/12/22 20:57:18 roberto Exp roberto $
** $Id: lzio.h,v 1.4 1998/01/09 14:57:43 roberto Exp roberto $
** Buffered streams
** See Copyright Notice in lua.h
*/
@@ -22,9 +22,9 @@
typedef struct zio ZIO;
ZIO* zFopen (ZIO* z, FILE* f, char *name); /* open FILEs */
ZIO* zsopen (ZIO* z, char* s, char *name); /* string */
ZIO* zmopen (ZIO* z, char* b, int size, char *name); /* memory */
ZIO* zFopen (ZIO* z, FILE* f, const char *name); /* open FILEs */
ZIO* zsopen (ZIO* z, const char* s, const char *name); /* string */
ZIO* zmopen (ZIO* z, const char* b, int size, const char *name); /* memory */
int zread (ZIO* z, void* b, int n); /* read next n bytes */
@@ -38,12 +38,12 @@ int zread (ZIO* z, void* b, int n); /* read next n bytes */
#define ZBSIZE 256 /* buffer size */
struct zio {
int n; /* bytes still unread */
unsigned char* p; /* current position in buffer */
int (*filbuf)(ZIO* z);
void* u; /* additional data */
char *name;
unsigned char buffer[ZBSIZE]; /* buffer */
int n; /* bytes still unread */
const unsigned char* p; /* current position in buffer */
int (*filbuf)(ZIO* z);
void* u; /* additional data */
const char *name;
unsigned char buffer[ZBSIZE]; /* buffer */
};

128
makefile
View File

@@ -1,5 +1,5 @@
#
## $Id: makefile,v 1.12 1998/05/27 13:03:40 roberto Exp roberto $
## $Id: makefile,v 1.24 2000/04/14 17:52:09 roberto Exp roberto $
## Makefile
## See Copyright Notice in lua.h
#
@@ -12,53 +12,64 @@
# define (undefine) _POSIX_SOURCE if your system is (not) POSIX compliant
#
# define (undefine) OLD_ANSI if your system does NOT have some new ANSI
# facilities (e.g. strerror, locale.h, memmove). Although they are ANSI,
# SunOS does not comply; so, add "-DOLD_ANSI" on SunOS
#
# define LUA_COMPAT2_5 if yous system does need to be compatible with
# version 2.5 (or older)
# facilities (e.g. strerror, locale.h, memmove). SunOS does not comply;
# so, add "-DOLD_ANSI" on SunOS
#
# define LUA_NUM_TYPE if you need numbers to be different from double
# (for instance, -DLUA_NUM_TYPE=float)
#
# define LUA_COMPAT_READPATTERN if you need read patterns
# (only for compatibility with previous versions)
CONFIG = -DPOPEN -D_POSIX_SOURCE
#CONFIG = -DLUA_COMPAT2_5 -DOLD_ANSI -DDEBUG
#CONFIG = -DOLD_ANSI -DDEBUG -DLUA_COMPAT_READPATTERN
# Compilation parameters
CC = gcc
CWARNS = -Wall -Wmissing-prototypes -Wshadow -pedantic -Wpointer-arith -Wcast-align -Waggregate-return
CWARNS = -Wall -W -Wmissing-prototypes -Wshadow -pedantic -Wpointer-arith -Wcast-align -Waggregate-return -Wcast-qual -Wnested-externs -Wwrite-strings
CFLAGS = $(CONFIG) $(CWARNS) -ansi -O2
# To make early versions
CO_OPTIONS =
AR = ar
ARFLAGS = rvl
# Aplication modules
LUAOBJS = \
lstate.o \
lref.o \
lapi.o \
lauxlib.o \
lbuffer.o \
lbuiltin.o \
ldo.o \
lfunc.o \
lgc.o \
llex.o \
lmem.o \
lobject.o \
lparser.o \
lstate.o \
lstring.o \
ltable.o \
ltm.o \
lvm.o \
ldo.o \
lobject.o \
lbuffer.o \
lfunc.o \
lgc.o \
lcode.o \
lparser.o \
llex.o \
lundump.o \
lzio.o
lzio.o \
ldebug.o \
ltests.o
LIBOBJS = \
liolib.o \
lmathlib.o \
lstrlib.o
lstrlib.o \
ldblib.o \
linit.o
lua : lua.o liblua.a liblualib.a
@@ -78,47 +89,66 @@ liblua.so.1.0 : lua.o
clear :
rcsclean
rm -f *.o
rm -f
co lua.h lualib.h luadebug.h
rm -f *.o *.a
%.h : RCS/%.h,v
co $@
co $(CO_OPTIONS) $@
%.c : RCS/%.c,v
co $@
co $(CO_OPTIONS) $@
lapi.o: lapi.c lapi.h lua.h lobject.h lauxlib.h ldo.h lstate.h lfunc.h \
lgc.h lmem.h lstring.h ltable.h ltm.h luadebug.h lvm.h
lapi.o: lapi.c lapi.h lobject.h llimits.h lua.h lauxlib.h ldo.h \
lstate.h luadebug.h lfunc.h lgc.h lmem.h lref.h lstring.h ltable.h \
ltm.h lvm.h
lauxlib.o: lauxlib.c lauxlib.h lua.h luadebug.h
lbuffer.o: lbuffer.c lauxlib.h lua.h lmem.h lstate.h lobject.h
lbuiltin.o: lbuiltin.c lapi.h lua.h lobject.h lauxlib.h lbuiltin.h \
ldo.h lstate.h lfunc.h lmem.h lstring.h ltable.h ltm.h lundump.h \
lzio.h
ldo.o: ldo.c ldo.h lobject.h lua.h lstate.h lfunc.h lgc.h lmem.h \
lparser.h lzio.h ltm.h luadebug.h lundump.h lvm.h
lfunc.o: lfunc.c lfunc.h lobject.h lua.h lmem.h lstate.h
lgc.o: lgc.c ldo.h lobject.h lua.h lstate.h lfunc.h lgc.h lmem.h \
lstring.h ltable.h ltm.h
lbuffer.o: lbuffer.c lauxlib.h lua.h lmem.h lstate.h lobject.h \
llimits.h luadebug.h
lbuiltin.o: lbuiltin.c lapi.h lobject.h llimits.h lua.h lauxlib.h \
lbuiltin.h ldo.h lstate.h luadebug.h lfunc.h lmem.h lstring.h \
ltable.h ltm.h lundump.h lzio.h lvm.h
lcode.o: lcode.c /usr/include/stdlib.h lcode.h llex.h lobject.h \
llimits.h lua.h lzio.h lopcodes.h lparser.h ldo.h lstate.h luadebug.h \
lmem.h lstring.h
ldblib.o: ldblib.c lauxlib.h lua.h luadebug.h lualib.h
ldebug.o: ldebug.c lapi.h lobject.h llimits.h lua.h lauxlib.h ldebug.h \
luadebug.h ldo.h lstate.h lfunc.h ltable.h ltm.h
ldo.o: ldo.c lauxlib.h lua.h ldebug.h lobject.h llimits.h luadebug.h \
ldo.h lstate.h lgc.h lmem.h lparser.h lzio.h lstring.h ltm.h \
lundump.h lvm.h
lfunc.o: lfunc.c lfunc.h lobject.h llimits.h lua.h lmem.h lstate.h \
luadebug.h
lgc.o: lgc.c ldo.h lobject.h llimits.h lua.h lstate.h luadebug.h \
lfunc.h lgc.h lmem.h lref.h lstring.h ltable.h ltm.h
linit.o: linit.c lua.h lualib.h
liolib.o: liolib.c lauxlib.h lua.h luadebug.h lualib.h
llex.o: llex.c lauxlib.h lua.h llex.h lobject.h lzio.h lmem.h \
lparser.h lstate.h lstring.h luadebug.h
llex.o: llex.c lauxlib.h lua.h llex.h lobject.h llimits.h lzio.h \
lmem.h lparser.h lstate.h luadebug.h lstring.h
lmathlib.o: lmathlib.c lauxlib.h lua.h lualib.h
lmem.o: lmem.c lmem.h lstate.h lobject.h lua.h
lobject.o: lobject.c lobject.h lua.h
lparser.o: lparser.c lauxlib.h lua.h ldo.h lobject.h lstate.h lfunc.h \
llex.h lzio.h lmem.h lopcodes.h lparser.h lstring.h luadebug.h
lstate.o: lstate.c lbuiltin.h ldo.h lobject.h lua.h lstate.h lfunc.h \
lgc.h llex.h lzio.h lmem.h lstring.h ltable.h ltm.h
lstring.o: lstring.c lmem.h lobject.h lua.h lstate.h lstring.h
lmem.o: lmem.c lmem.h lua.h lobject.h llimits.h lstate.h luadebug.h
lobject.o: lobject.c lobject.h llimits.h lua.h
lparser.o: lparser.c lcode.h llex.h lobject.h llimits.h lua.h lzio.h \
lopcodes.h lparser.h ldo.h lstate.h luadebug.h lfunc.h lmem.h \
lstring.h
lref.o: lref.c lapi.h lobject.h llimits.h lua.h lmem.h lref.h lstate.h \
luadebug.h
lstate.o: lstate.c lauxlib.h lua.h lbuiltin.h ldo.h lobject.h \
llimits.h lstate.h luadebug.h lgc.h llex.h lzio.h lmem.h lref.h \
lstring.h ltm.h
lstring.o: lstring.c lmem.h lua.h lobject.h llimits.h lstate.h \
luadebug.h lstring.h
lstrlib.o: lstrlib.c lauxlib.h lua.h lualib.h
ltable.o: ltable.c lauxlib.h lua.h lmem.h lobject.h lstate.h ltable.h
ltm.o: ltm.c lauxlib.h lua.h lmem.h lobject.h lstate.h ltm.h
ltable.o: ltable.c lauxlib.h lua.h lmem.h lobject.h llimits.h lstate.h \
luadebug.h ltable.h
ltests.o: ltests.c lapi.h lobject.h llimits.h lua.h lauxlib.h lmem.h \
lopcodes.h lstate.h luadebug.h lstring.h ltable.h
ltm.o: ltm.c lauxlib.h lua.h lmem.h lobject.h llimits.h lstate.h \
luadebug.h ltm.h
lua.o: lua.c lua.h luadebug.h lualib.h
lundump.o: lundump.c lauxlib.h lua.h lfunc.h lobject.h lmem.h \
lstring.h lundump.h lzio.h
lvm.o: lvm.c lauxlib.h lua.h ldo.h lobject.h lstate.h lfunc.h lgc.h \
lmem.h lopcodes.h lstring.h ltable.h ltm.h luadebug.h lvm.h
lundump.o: lundump.c lauxlib.h lua.h lfunc.h lobject.h llimits.h \
lmem.h lopcodes.h lstring.h lstate.h luadebug.h lundump.h lzio.h
lvm.o: lvm.c lauxlib.h lua.h ldebug.h lobject.h llimits.h luadebug.h \
ldo.h lstate.h lfunc.h lgc.h lopcodes.h lstring.h ltable.h ltm.h \
lvm.h
lzio.o: lzio.c lzio.h

1713
manual.tex

File diff suppressed because it is too large Load Diff