History

Lua 3.2

Lua Team committed 27 years ago

Commit ee14b801 parent 9d0e0be70 files · +4793 −3426Browse files

Unified · Split

70 files
  1. COPYRIGHT +8 −4
  2. HISTORY +18 −1
  3. INSTALL +24 −12
  4. MANIFEST +5 −1
  5. Makefile +8 −5
  6. README +11 −3
  7. config +31 −17
  8. doc/idx.html +26 −6
  9. doc/index.html +15 −6
  10. doc/luac.html +77 −41
  11. doc/luac.man +65 −42
  12. doc/manual.html +628 −298
  13. doc/readme.html +31 −0
  14. etc/README +4 −3
  15. etc/bin2c.c +7 −2
  16. etc/trace.c +14 −18
  17. include/lauxlib.h +7 −1
  18. include/lua.h +13 −16
  19. include/luadebug.h +6 −5
  20. include/lualib.h +5 −3
  21. src/lapi.c +165 −103
  22. src/lapi.h +3 −1
  23. src/lauxlib.c +29 −7
  24. src/lbuffer.c +25 −35
  25. src/lbuiltin.c +488 −278
  26. src/ldo.c +90 −132
  27. src/ldo.h +3 −3
  28. src/lfunc.c +2 −2
  29. src/lgc.c +9 −22
  30. src/lib/Makefile +2 −2
  31. src/lib/ldblib.c +217 −0
  32. src/lib/linit.c +17 −0
  33. src/lib/liolib.c +344 −209
  34. src/lib/lmathlib.c +57 −67
  35. src/lib/lstrlib.c +230 −177
  36. src/llex.c +52 −78
  37. src/llex.h +7 −5
  38. src/lmem.c +80 −53
  39. src/lmem.h +7 −9
  40. src/lobject.c +61 −15
  41. src/lobject.h +9 −15
  42. src/lopcodes.h +113 −156
  43. src/lparser.c +314 −256
  44. src/lparser.h +2 −2
  45. src/lstate.c +12 −12
  46. src/lstate.h +20 −12
  47. src/lstring.c +62 −77
  48. src/ltable.c +65 −104
  49. src/ltable.h +10 −4
  50. src/ltm.c +38 −53
  51. src/ltm.h +3 −3
  52. src/lua/Makefile +2 −2
  53. src/lua/README +21 −3
  54. src/lua/lua.c +29 −35
  55. src/luac/Makefile +3 −3
  56. src/luac/README +17 −14
  57. src/luac/dump.c +61 −65
  58. src/luac/luac.c +51 −48
  59. src/luac/luac.h +29 −14
  60. src/luac/opcode.c +50 −35
  61. src/luac/opcode.h +66 −130
  62. src/luac/opt.c +147 −94
  63. src/luac/print.c +86 −96
  64. src/luac/stubs.c +72 −19
  65. src/luac/test.c +253 −0
  66. src/lundump.c +91 −80
  67. src/lundump.h +24 −63
  68. src/lvm.c +234 −336
  69. src/lvm.h +7 −2
  70. src/lzio.c +11 −11
COPYRIGHT+8−4
@@ -4,14 +4,18 @@ Lua COPYRIGHT NOTICE · 3 unmodified lines
44 Lua is free and non-proprietary.
55 It can be used for both academic and commercial purposes at absolutely no cost.
66 There are no royalties or GNU-like "copyleft" restrictions.
7−On the other hand, Lua is not in the public domain; TeCGraf keeps its copyright.
8−If you use Lua, please give us credit, but we would appreciate *not* receiving
7+Lua (probably) qualifies as Open Source software.
8+Nevertheless, Lua is not in the public domain and TeCGraf keeps its copyright.
9+
10+If you use Lua, please give us credit (a nice way to do this is to include a
11+logo in a web page for your product), but we would appreciate *not* receiving
912 lengthy legal documents to sign.
10−The legal details are below.
13+
14+The legal details are below.
1115
1216 ===============================================================================
1317
14−Copyright (c) 1994-1998 TeCGraf, PUC-Rio. All rights reserved.
18+Copyright (c) 1994-1999 TeCGraf, PUC-Rio. All rights reserved.
1519
1620 Permission is hereby granted, without written agreement and without license
1721 or royalty fees, to use, copy, modify, and distribute this software and its
HISTORY+18−1
@@ -1,6 +1,18 @@
1−This is version 3.1.
1+This is Lua 3.2
2+
3+* Changes from version 3.1 to 3.2
4+ -------------------------------
5+ + redirected all output in Lua's core to _ERRORMESSAGE and _ALERT.
6+ + increased limit on the number of constants and globals per function
7+ (from 2^16 to 2^24).
8+ + debugging info (lua_debug and hooks) moved into lua_state and new API
9+ functions provided to get and set this info.
10+ + new debug lib gives full debugging access within Lua.
11+ + new table functions "foreachi", "sort", "tinsert", "tremove", "getn".
12+ + new io functions "flush", "seek".
213
314 * Changes from version 3.0 to 3.1
15+ -------------------------------
416 + NEW FEATURE: anonymous functions with closures (via "upvalues").
517 + new syntax:
618 - local variables in chunks.
@@ -23,6 +35,7 @@ This is version 3.1. · 16 unmodified lines
2335 handles control-C interruptions gracefully.
2436
2537 * Changes from version 2.5 to 3.0
38+ -------------------------------
2639 + NEW CONCEPT: "tag methods".
2740 Tag methods replace fallbacks as the meta-mechanism for extending the
2841 semantics of Lua. Whereas fallbacks had a global nature, tag methods
@@ -37,6 +50,7 @@ This is version 3.1. · 8 unmodified lines
3750 + luac can now also undump.
3851
3952 * Changes from version 2.4 to 2.5
53+ -------------------------------
4054 + io and string libraries are now based on pattern matching;
4155 the old libraries are still available for compatibility
4256 + dofile and dostring can now return values (via return statement)
@@ -44,6 +58,7 @@ This is version 3.1. · 1 unmodified line
4458 + expanded documentation, with more examples
4559
4660 * Changes from version 2.2 to 2.4
61+ -------------------------------
4762 + external compiler creates portable binary files that can be loaded faster
4863 + interface for debugging and profiling
4964 + new "getglobal" fallback
@@ -53,11 +68,13 @@ This is version 3.1. · 3 unmodified lines
5368 + expanded documentation, with more examples
5469
5570 * Changes from version 2.1 to 2.2
71+ -------------------------------
5672 + functions now may be declared with any "lvalue" as a name
5773 + garbage collection of functions
5874 + support for pipes
5975
6076 * Changes from version 1.1 to 2.1
77+ -------------------------------
6178 + object-oriented support
6279 + fallbacks
6380 + simplified syntax for tables
INSTALL+24−12
@@ -1,5 +1,7 @@
1−* Installation
1+This is Lua 3.2
22
3+* Installation
4+ ------------
35 Building Lua on a Unix system should be very easy:
46
57 1. Edit "config" to suit your platform, if at all necessary.
@@ -8,7 +10,7 @@ · 2 unmodified lines
810 See below for instructions for Windows and Macintosh.
911
1012 * What you get
11−
13+ ------------
1214 If "make" succeeds, you get:
1315 * an interpreter in ./bin/lua and a compiler in ./bin/luac;
1416 * libraries in ./lib;
@@ -19,26 +21,36 @@ · 4 unmodified lines
1921 and some useful stuff in ./etc.
2022 You don't need these directories for development.
2123
22−* If you have problems (and solutions!)
24+ See also the README files in the various subdirectories.
25+ A convenient staring point is ./doc/readme.html.
2326
27+* If you have problems (and solutions!)
28+ -------------------------------------
2429 If "make" fails, please let us know (lua@tecgraf.puc-rio.br).
2530 If you make changes to "config", please send them to us.
2631
2732 * Shared libraries
28−
33+ ----------------
2934 If you are running SunOs 4.x, type the following after "make" succeeds:
30− ld -o lib/liblua.so.3.1 src/*.o
31− ld -o lib/liblualib.so.3.1 src/lib/*.o
35+ ld -o lib/liblua.so.3.2 src/*.o
36+ ld -o lib/liblualib.so.3.2 src/lib/*.o
3237
33− If you want the interpreter to use shared libraries, then do:
38+ If you are running Linux, type the following after "make" succeeds:
39+ ld -o lib/liblua.so.3.2 -shared src/*.o
40+ ld -o lib/liblualib.so.3.2 -shared src/lib/*.o
41+ cd lib
42+ ln -s liblua.so.3.2 liblua.so
43+ ln -s liblualib.so.3.2 liblualib.so.3.2
44+
45+ If you want the interpreter to use shared libraries, then do this too:
3446 rm bin/lua
3547 cd src/lua; make
48+ You may need to include lib/ in the LD_LIBRAY_PATH environment variable.
3649
37− For AIX, the OpenGL clone Mesa includes a script for making shared libraries.
38− For other systems, please tell us how!
50+ Building shared libraries in other systems is similar but details differ.
3951
4052 * Installation on Windows or Macintosh
41−
53+ ------------------------------------
4254 The instructions for building Lua on a Mac or Windows machine depend on
4355 the particular compiler you are using.
4456 The simplest way is to create a folder with all .c and .h files.
@@ -49,11 +61,11 @@ · 4 unmodified lines
4961 llex.c lmem.c lobject.c lparser.c lstate.c lstring.c ltable.c
5062 ltm.c lundump.c lvm.c lzio.c
5163
52− standard lib: liolib.c lmathlib.c lstrlib.c
64+ standard lib: linit.c ldblib.c liolib.c lmathlib.c lstrlib.c
5365
5466 interpreter: basic lib, standard lib, lua.c
5567
56− compiler: basic lib, dump.c luac.c print.c stubs.c opcode.c opt.c
68+ compiler: basic lib, dump.c luac.c opcode.c opt.c print.c stubs.c test.c
5769
5870 Of course, to use Lua as a library, you'll have to know how to create
5971 and use libraries with your compiler.
MANIFEST+5−1
@@ -1,4 +1,4 @@
1−MANIFEST contents of Lua 3.1 distribution on Sat Jul 11 22:48:43 EST 1998
1+MANIFEST contents of Lua 3.2 distribution on Thu Jul 8 10:34:45 EST 1999
22 lua
33 lua/COPYRIGHT
44 lua/HISTORY
@@ -14,6 +14,7 @@ lua/doc/index.html · 9 unmodified lines
1414 lua/doc/luac.html
1515 lua/doc/luac.man
1616 lua/doc/manual.html
17+lua/doc/readme.html
1718 lua/etc
1819 lua/etc/Makefile
1920 lua/etc/README
@@ -45,6 +46,8 @@ lua/src/lgc.h · 25 unmodified lines
4546 lua/src/lib
4647 lua/src/lib/Makefile
4748 lua/src/lib/README
49+lua/src/lib/ldblib.c
50+lua/src/lib/linit.c
4851 lua/src/lib/liolib.c
4952 lua/src/lib/lmathlib.c
5053 lua/src/lib/lstrlib.c
@@ -80,6 +83,7 @@ lua/src/luac/opcode.h · 29 unmodified lines
8083 lua/src/luac/opt.c
8184 lua/src/luac/print.c
8285 lua/src/luac/stubs.c
86+lua/src/luac/test.c
8387 lua/src/lundump.c
8488 lua/src/lundump.h
8589 lua/src/lvm.c
Makefile+8−5
@@ -1,8 +1,11 @@
11 # makefile for lua hierarchy
22
33 all co clean klean:
4− cd include; make $@
5− cd src; make $@
6− cd src/luac; make $@
7− cd src/lib; make $@
8− cd src/lua; make $@
4+ cd include; $(MAKE) $@
5+ cd src; $(MAKE) $@
6+ cd src/luac; $(MAKE) $@
7+ cd src/lib; $(MAKE) $@
8+ cd src/lua; $(MAKE) $@
9+
10+strip:
11+ strip bin/lua*
README+11−3
@@ -1,4 +1,7 @@
1+This is Lua 3.2
2+
13 * What is Lua?
4+ ------------
25 Lua is a programming language originally designed for extending applications,
36 but also frequently used as a general-purpose, stand-alone language.
47 Lua combines simple procedural syntax (similar to Pascal) with powerful
@@ -11,12 +14,13 @@ · 6 unmodified lines
1114 and compiles unmodified in all known platforms. The implementation goals
1215 are simplicity, efficiency, portability, and low embedding cost.
1316
14− Lua has been awarded the first prize (technological category) in the Second
15− Compaq Award for Research and Development in Computer Science. This award
17+ Lua was awarded the first prize (technological category) in the Second Compaq
18+ Award for Research and Development in Computer Science in 1997. This award
1619 is a joint venture of Compaq Computer in Brazil, the Brazilian Ministry of
1720 Science and Technology, and the Brazilian Academy of Sciences.
1821
1922 * Availability
23+ ------------
2024 Lua is freely available for both academic and commercial purposes and
2125 can be downloaded from the sites below. See COPYRIGHT for details.
2226
@@ -24,19 +28,23 @@ · 1 unmodified line
2428 http://csg.uwaterloo.ca/~lhf/lua/
2529 In Brazil: ftp://ftp.tecgraf.puc-rio.br/pub/lua/lua.tar.gz
2630 In Canada: ftp://csg.uwaterloo.ca/pub/lhf/lua/lua.tar.gz
31+ In the US: ftp://ftp.cdrom.com/pub/languages/lua/lua.tar.gz
2732 In Germany: ftp://ftp.uni-trier.de/pub/languages/lua/lua.tar.gz
33+ In Germany: ftp://ftp.gwdg.de/pub/languages/lua/lua.tar.gz
2834 In Greece: ftp://ftp.ntua.gr/pub/lang/lua/lua.tar.gz
2935
3036 * Installation
37+ ------------
3138 See INSTALL.
3239
3340 * Contacting the authors
41+ ----------------------
3442 Lua has been designed and implemented by Waldemar Celes,
3543 Roberto Ierusalimschy and Luiz Henrique de Figueiredo.
3644 They can be contacted by email at lua@tecgraf.puc-rio.br.
3745
3846 Send your comments, bug reports and anything else to lua@tecgraf.puc-rio.br.
39− For reporting bugs, try also the mailing list: lua-l@tecgraf.puc-rio.br
47+ For reporting bugs, try also the mailing list: lua-l@tecgraf.puc-rio.br.
4048 To subscribe to this list, send "subscribe lua-l YOUR-NAME" to
4149 listproc@tecgraf.puc-rio.br in the body of the message (not in the subject).
4250
config+31−17
@@ -1,54 +1,68 @@
11 # configuration file for making Lua
22
3−# == CHANGE THE SETTINGS BELOW TO SUIT YOUR ENVIRONMENT ======================
3+# == CHANGE THE SETTINGS BELOW TO SUIT YOUR ENVIRONMENT =======================
44
5−# you need an ANSI C compiler. gcc is a popular one.
6−CC= gcc
7−WARN= -ansi -Wall
8−
9−# on SGI's, cc is ANSI.
10−#CC= cc
11−#WARN= -ansi -fullwarn
5+# ------------------------------------------------------------------ Lua
126
137 # if you need compatibility with version 2.5 or older, uncomment the line below.
148 #COMPAT= -DLUA_COMPAT2_5
159
1610 # Lua uses double for numbers. To change this, uncomment one of the lines below.
11+#NUMBER= -DLUA_NUM_TYPE=double
1712 #NUMBER= -DLUA_NUM_TYPE=float
1813 #NUMBER= -DLUA_NUM_TYPE=long
1914
2015 # if you want support for pipes, uncomment the following line.
2116 #POPEN= -DPOPEN
2217
18+# ------------------------------------------------------------------ C compiler
19+
20+# you need an ANSI C compiler. gcc is a popular one.
21+CC= gcc
22+WARN= -ansi -Wall
23+
24+# on IRIX, cc is a good ANSI compiler.
25+#CC= cc
26+#WARN= -ansi -fullwarn
27+
28+# on Solaris, cc is optional. you may have to add -Dsparc if you use -Xc.
29+#CC= cc
30+#WARN= -Xc # -Dsparc
31+
32+# ------------------------------------------------------------------ C library
33+
2334 # if your C library is not POSIX compliant, comment the following line.
2435 POSIX= -D_POSIX_SOURCE
2536
2637 # if your C library does not have the newer ANSI functions memmove, strerror,
27−# and locale support (e.g., in SunOs 4.1.x.), uncomment the following line.
38+# and locale support, uncomment the following line. SunOs 4.1.x is one example.
2839 #OLD_ANSI= -DOLD_ANSI
2940
3041 # in SunOs 4.1.x, standard headers in /usr/include are not ANSI,
3142 # so uncomment the following line to avoid prototypes warnings.
3243 #EXTRA_INCS= -I/usr/5include
3344
34−# if your system doesn't have (or need) ranlib, change "ranlib" to "true".
35−# on some systems, "ar s" does it.
36−RANLIB= ranlib
37−#RANLIB= ar s
38−#RANLIB= true
45+# ------------------------------------------------------------------ librarian
3946
4047 # this should work in all unix systems.
4148 AR= ar rcu
4249
43−# == END OF USER SETTINGS. DO NOT CHANGE ANYTHING BELOW THIS LINE ============
50+# if your system doesn't have (or need) ranlib, use RANLIB=true.
51+# on some systems, "ar s" does what ranlib would do.
52+RANLIB= ranlib
53+#RANLIB= ar s
54+#RANLIB= true
55+
56+# == END OF USER SETTINGS. DO NOT CHANGE ANYTHING BELOW THIS LINE =============
4457
45−VERSION= 3.1
58+VERSION= 3.2
4659
4760 INC= $(LUA)/include
4861 LIB= $(LUA)/lib
4962 BIN= $(LUA)/bin
5063
5164 INCS= -I$(INC) $(EXTRA_INCS)
52−DEFS= $(COMPAT) $(NUMBER) $(OLD_ANSI) $(EXTRA_DEFS)
65+DEFS= $(COMPAT) $(NUMBER) $(OLD_ANSI) $(EXTRALIB) $(EXTRA_DEFS)
5366
5467 CFLAGS= -O2 $(WARN) $(INCS) $(DEFS)
68+
doc/idx.html+26−6
@@ -1,9 +1,9 @@
11 <HTML>
22 <HEAD>
3−<TITLE>Lua 3.1 Reference Manual - Word Index</TITLE>
3+<TITLE>Lua 3.2 Reference Manual - Word Index</TITLE>
44 </HEAD>
55
6−<BODY>
6+<BODY BGCOLOR="#FFFFFF">
77
88 <H1>Index</H1>
99
@@ -28,10 +28,10 @@ · 18 unmodified lines
2828 <A HREF="manual.html#Operator precedence">Operator precedence</A><BR>
2929 <A HREF="manual.html#PI">PI</A><BR>
3030 <A HREF="manual.html#Pre-processor">Pre-processor</A><BR>
31−<A HREF="manual.html#Tag Methods">Tag Methods</A><BR>
3231 <A HREF="manual.html#Types and Tags">Types and Tags</A><BR>
3332 <A HREF="manual.html#Upvalues">Upvalues</A><BR>
3433 <A HREF="manual.html#Visibility">Visibility</A><BR>
34+<A HREF="manual.html#_ERRORMESSAGE">_ERRORMESSAGE</A><BR>
3535 <A HREF="manual.html#_INPUT">_INPUT</A><BR>
3636 <A HREF="manual.html#_OUTPUT">_OUTPUT</A><BR>
3737 <A HREF="manual.html#_STDERR">_STDERR</A><BR>
@@ -40,6 +40,7 @@ · 2 unmodified lines
4040 <A HREF="manual.html#abs">abs</A><BR>
4141 <A HREF="manual.html#acos">acos</A><BR>
4242 <A HREF="manual.html#add event">add event</A><BR>
43+<A HREF="manual.html#alert">alert</A><BR>
4344 <A HREF="manual.html#and">and</A><BR>
4445 <A HREF="manual.html#appendto">appendto</A><BR>
4546 <A HREF="manual.html#arguments">arguments</A><BR>
@@ -59,6 +60,7 @@ · 13 unmodified lines
5960 <A HREF="manual.html#character class">character class</A><BR>
6061 <A HREF="manual.html#chunk">chunk</A><BR>
6162 <A HREF="manual.html#clock">clock</A><BR>
63+<A HREF="manual.html#closefile">closefile</A><BR>
6264 <A HREF="manual.html#closing a file">closing a file</A><BR>
6365 <A HREF="manual.html#collectgarbage">collectgarbage</A><BR>
6466 <A HREF="manual.html#concatenation event">concatenation event</A><BR>
@@ -74,7 +76,6 @@ · 9 unmodified lines
7476 <A HREF="manual.html#dofile">dofile</A><BR>
7577 <A HREF="manual.html#dostring">dostring</A><BR>
7678 <A HREF="manual.html#eight-bit clean">eight-bit clean</A><BR>
77−<A HREF="manual.html#error method">error method</A><BR>
7879 <A HREF="manual.html#error">error</A><BR>
7980 <A HREF="manual.html#event">event</A><BR>
8081 <A HREF="manual.html#execute">execute</A><BR>
@@ -82,10 +83,13 @@ · 1 unmodified line
8283 <A HREF="manual.html#exponentiation">exponentiation</A><BR>
8384 <A HREF="manual.html#file handles">file handles</A><BR>
8485 <A HREF="manual.html#floor">floor</A><BR>
86+<A HREF="manual.html#flush">flush</A><BR>
87+<A HREF="manual.html#foreachi">foreachi</A><BR>
8588 <A HREF="manual.html#foreachvar">foreachvar</A><BR>
8689 <A HREF="manual.html#foreach">foreach</A><BR>
8790 <A HREF="manual.html#format">format</A><BR>
8891 <A HREF="manual.html#frexp">frexp</A><BR>
92+<A HREF="manual.html#funcinfo">funcinfo</A><BR>
8993 <A HREF="manual.html#function call">function call</A><BR>
9094 <A HREF="manual.html#function event">function event</A><BR>
9195 <A HREF="manual.html#function">function</A><BR>
@@ -94,6 +98,9 @@ · 2 unmodified lines
9498 <A HREF="manual.html#getenv">getenv</A><BR>
9599 <A HREF="manual.html#getglobal event">getglobal event</A><BR>
96100 <A HREF="manual.html#getglobal">getglobal</A><BR>
101+<A HREF="manual.html#getlocal">getlocal</A><BR>
102+<A HREF="manual.html#getn">getn</A><BR>
103+<A HREF="manual.html#getstack">getstack</A><BR>
97104 <A HREF="manual.html#gettable event">gettable event</A><BR>
98105 <A HREF="manual.html#gettagmethod">gettagmethod</A><BR>
99106 <A HREF="manual.html#gettagmethod">gettagmethod</A><BR>
@@ -158,7 +165,6 @@ · 58 unmodified lines
158165 <A HREF="manual.html#lua_rawsettable">lua_rawsettable</A><BR>
159166 <A HREF="manual.html#lua_ref">lua_ref</A><BR>
160167 <A HREF="manual.html#lua_register">lua_register</A><BR>
161−<A HREF="manual.html#lua_seterrormethod">lua_seterrormethod</A><BR>
162168 <A HREF="manual.html#lua_setglobal">lua_setglobal</A><BR>
163169 <A HREF="manual.html#lua_setstate">lua_setstate</A><BR>
164170 <A HREF="manual.html#lua_settable">lua_settable</A><BR>
@@ -183,6 +189,7 @@ · 18 unmodified lines
183189 <A HREF="manual.html#nil">nil</A><BR>
184190 <A HREF="manual.html#not">not</A><BR>
185191 <A HREF="manual.html#number">number</A><BR>
192+<A HREF="manual.html#openfile">openfile</A><BR>
186193 <A HREF="manual.html#or">or</A><BR>
187194 <A HREF="manual.html#packed results">packed results</A><BR>
188195 <A HREF="manual.html#pattern item">pattern item</A><BR>
@@ -216,10 +223,14 @@ · 27 unmodified lines
216223 <A HREF="manual.html#reserved words">reserved words</A><BR>
217224 <A HREF="manual.html#return statement">return statement</A><BR>
218225 <A HREF="manual.html#return">return</A><BR>
226+<A HREF="manual.html#seek">seek</A><BR>
219227 <A HREF="manual.html#self">self</A><BR>
228+<A HREF="manual.html#setcallhook">setcallhook</A><BR>
220229 <A HREF="manual.html#setglobal event">setglobal event</A><BR>
221230 <A HREF="manual.html#setglobal">setglobal</A><BR>
231+<A HREF="manual.html#setlinehook">setlinehook</A><BR>
222232 <A HREF="manual.html#setlocale">setlocale</A><BR>
233+<A HREF="manual.html#setlocal">setlocal</A><BR>
223234 <A HREF="manual.html#settable event">settable event</A><BR>
224235 <A HREF="manual.html#settagmethod">settagmethod</A><BR>
225236 <A HREF="manual.html#settagmethod">settagmethod</A><BR>
@@ -227,8 +238,10 @@ · 1 unmodified line
227238 <A HREF="manual.html#short-cut evaluation">short-cut evaluation</A><BR>
228239 <A HREF="manual.html#sin">sin</A><BR>
229240 <A HREF="manual.html#skips">skips</A><BR>
241+<A HREF="manual.html#sort">sort</A><BR>
230242 <A HREF="manual.html#sqrt">sqrt</A><BR>
231243 <A HREF="manual.html#statements">statements</A><BR>
244+<A HREF="manual.html#stderr">stderr</A><BR>
232245 <A HREF="manual.html#strbyte">strbyte</A><BR>
233246 <A HREF="manual.html#strchar">strchar</A><BR>
234247 <A HREF="manual.html#strfind">strfind</A><BR>
@@ -240,25 +253,32 @@ · 5 unmodified lines
240253 <A HREF="manual.html#strupper">strupper</A><BR>
241254 <A HREF="manual.html#sub event">sub event</A><BR>
242255 <A HREF="manual.html#table">table</A><BR>
256+<A HREF="manual.html#tag methods">tag methods</A><BR>
243257 <A HREF="manual.html#tag">tag</A><BR>
244258 <A HREF="manual.html#tag">tag</A><BR>
245259 <A HREF="manual.html#tan">tan</A><BR>
260+<A HREF="manual.html#tinsert">tinsert</A><BR>
246261 <A HREF="manual.html#tmpname">tmpname</A><BR>
247262 <A HREF="manual.html#tokens">tokens</A><BR>
248263 <A HREF="manual.html#tonumber">tonumber</A><BR>
249264 <A HREF="manual.html#tostring">tostring</A><BR>
265+<A HREF="manual.html#tremove">tremove</A><BR>
250266 <A HREF="manual.html#type">type</A><BR>
251267 <A HREF="manual.html#unm event">unm event</A><BR>
252268 <A HREF="manual.html#userdata">userdata</A><BR>
253269 <A HREF="manual.html#vararg">vararg</A><BR>
254270 <A HREF="manual.html#version 3.0">version 3.0</A><BR>
271+<A HREF="manual.html#version 3.1">version 3.1</A><BR>
255272 <A HREF="manual.html#while-do">while-do</A><BR>
256273 <A HREF="manual.html#writeto">writeto</A><BR>
257274 <A HREF="manual.html#write">write</A><BR>
258275
259276 <HR>
277+<SMALL>
260278 Last update:
261−Fri Jul 10 15:10:14 EST 1998
279+Wed Jul 7 13:36:24 EST 1999
262280 by <A HREF="http://www.tecgraf.puc-rio.br/~lhf/">lhf</A>.
281+</SMALL>
282+
263283 </BODY>
264284 </HTML>
doc/index.html+15−6
@@ -1,16 +1,17 @@
11 <HTML>
22 <HEAD>
3−<TITLE>Lua 3.1 Reference Manual - Contents</TITLE>
3+<TITLE>Lua 3.2 Reference Manual - Contents</TITLE>
44 </HEAD>
55
6−<BODY>
6+<BODY BGCOLOR="#FFFFFF">
77
8+<HR>
89 <H1>Reference Manual of the Programming Language
910 <A HREF="http://www.tecgraf.puc-rio.br/lua/">Lua</A>
10−3.1</H1>
11+3.2</H1>
1112 <P>
1213 <A HREF="http://www.inf.puc-rio.br/~roberto/">Roberto Ierusalimschy</A>,
13−<A HREF="http://www2.lncc.br/~lhf/">Luiz Henrique de Figueiredo</A>,
14+<A HREF="http://www.tecgraf.puc-rio.br/~lhf/">Luiz Henrique de Figueiredo</A>,
1415 <A HREF="http://www.tecgraf.puc-rio.br/~celes/">Waldemar Celes</A>
1516 <BR>
1617 <A HREF="mailto:lua@tecgraf.puc-rio.br">lua@tecgraf.puc-rio.br</A><BR>
@@ -26,7 +27,11 @@ · 9 unmodified lines
2627 |
2728 <A HREF="idx.html">index</A>
2829 |
29−<A HREF="ftp://ftp.tecgraf.puc-rio.br/pub/lua/lua.ps.gz">ps</A>
30+<A HREF="ftp://ftp.tecgraf.puc-rio.br/pub/lua/refman.ps.gz">ps</A>
31+|
32+<A HREF="ftp://ftp.tecgraf.puc-rio.br/pub/lua/refman.pdf">pdf</A>
33+|
34+<A HREF="old/">old versions</A>
3035 ]
3136 <HR>
3237 <A NAME="contents"></A>
@@ -69,6 +74,7 @@ · 36 unmodified lines
6974 <LI><A HREF="manual.html#7.1">7.1 - Stack and Function Information</A>
7075 <LI><A HREF="manual.html#7.2">7.2 - Manipulating Local Variables</A>
7176 <LI><A HREF="manual.html#7.3">7.3 - Hooks</A>
77+ <LI><A HREF="manual.html#7.4">7.4 - The Reflexive Debugger Interface</A>
7278 </UL>
7379 <LI><A HREF="manual.html#8.">8 - Lua Stand-alone</A>
7480 <LI><A HREF="manual.html#Acknowledgments">Acknowledgments</A>
@@ -77,8 +83,11 @@ · 2 unmodified lines
7783 </UL>
7884
7985 <HR>
86+<SMALL>
8087 Last update:
81−Fri Jul 10 15:10:14 EST 1998
88+Wed Jul 7 13:36:24 EST 1999
8289 by <A HREF="http://www.tecgraf.puc-rio.br/~lhf/">lhf</A>.
90+</SMALL>
91+
8392 </BODY>
8493 </HTML>
doc/luac.html+77−41
@@ -1,35 +1,20 @@
1−<!-- $Id: luac.man,v 1.8 1998/06/13 16:54:15 lhf Exp $ -->
2−<TITLE>LUAC 1 "06 February 1998"</TITLE>
1+<!-- luac.man,v 1.17 1999/07/07 16:02:07 lhf Exp -->
2+<HTML>
3+<HEAD>
4+<TITLE>LUAC man page</TITLE>
5+</HEAD>
6+
7+<BODY BGCOLOR="#FFFFFF">
8+
39 <H1>NAME</H1>
410 luac - Lua compiler
511 <H1>SYNOPSIS</H1>
612 <B>luac</B>
713 [
8−<B>-c</B>
9−|
10−<B>-u</B>
11−] [
12−<B>-D</B>
13−<I>name</I>
14−] [
15−<B>-d</B>
16−] [
17−<B>-l</B>
18−] [
19−<B>-O</B>
20−] [
21−<B>-o</B>
22−<I>filename</I>
14+<I>options</I>
2315 ] [
24−<B>-p</B>
25−] [
26−<B>-q</B>
27−] [
28−<B>-v</B>
29−] [
30−<B>-V</B>
16+<I>filenames</I>
3117 ]
32−<I>sourcefile </I>...
3318 <H1>DESCRIPTION</H1>
3419 <B>luac</B>
3520 is the Lua compiler.
@@ -43,10 +28,16 @@ in Lua. · 7 unmodified lines
4328 The main advantages of pre-compiling chunks are:
4429 faster loading,
4530 protecting source code from user changes,
31+and
4632 off-line syntax error detection.
4733 The binary files created by
4834 <B>luac</B>
49−are portable to all known architectures.
35+are portable to all architectures.
36+<P>
37+Pre-compiling does not imply faster execution
38+because in Lua chunks are always compiled into bytecodes before being executed.
39+<B>luac</B>
40+simply allows those bytecodes to be saved in a file for later execution.
5041 <P>
5142 <B>luac</B>
5243 produces a single output file containing the bytecodes
@@ -71,16 +62,26 @@ option. · 18 unmodified lines
7162 <P>
7263 Binary files produced by differents runs of
7364 <B>luac</B>
65+(even in different machines)
7466 can be combined into one large file,
7567 using
7668 <B>cat</B>(1).
77−The result is still a valid binary file,
69+The result is still a valid binary file
7870 and can be loaded with a single call to
7971 <B>lua_dofile</B>
8072 or
8173 <B>dofile</B>.
8274 <P>
75+The internal format of the binary files produced by
76+<B>luac</B>
77+may change when a new version of Lua is released.
78+We try to maintain compatibility even for binary files,
79+but sometimes it cannot be done.
80+So,
81+save the source files of all Lua programs that you precompile.
82+<P>
8383 <H1>OPTIONS</H1>
84+Options must be separate.
8485 <P>
8586 <B>-c</B>
8687 compile (this is the default).
@@ -89,26 +90,44 @@ compile (this is the default). · 2 unmodified lines
8990 undump, i.e., load and list the given binary files.
9091 If no files are given, then luac undumps
9192 <B>luac.out</B>.
92−<P>
93−<B>-D "</B><I>name"</I>
94−predefine symbol
95−<I>name</I>
96−for conditional compilation.
93+Listing a binary file is useful to learn Lua's virtual machine.
94+Listing is also useful to test the integrity of binary files:
95+corrupted files will probably generate errors when undumped.
96+To test without listing, use
97+<B>-q</B>.
98+For a thourough integrity test,
99+use
100+<B>-t</B>.
97101 <P>
98102 <B>-d</B>
99103 turn debugging on.
100104 Individual chunks may
101105 still control the generation of debug information with
102106 $debug and $nodebug.
107+If debugging is on, then listings show the names of the local variables.
108+<P>
109+<B>-D "</B><I>name"</I>
110+predefine symbol
111+<I>name</I>
112+for conditional compilation.
113+By default,
114+<B>luac</B>
115+does
116+<I>not</I>
117+predefine any symbols,
118+not even the built-in functions.
103119 <P>
104120 <B>-l</B>
105121 produce a listing of the compiled bytecode for Lua's virtual machine.
106122 This is the default when undumping.
107123 <P>
108−<B>-O</B>
109−optimize code.
110−Debug information is removed,
111−duplicate constants are coalesced.
124+<B>-n</B>
125+Save numbers in native format.
126+By default,
127+numbers are saved in text form,
128+for maximum portability.
129+Binary files with numbers in native format are slightly faster to load,
130+but are not completely portable.
112131 <P>
113132 <B>-o "</B><I>filename"</I>
114133 output to
@@ -117,14 +136,33 @@ instead of the default · 2 unmodified lines
117136 <B>luac.out</B>.
118137 The output file cannot be a source file.
119138 <P>
139+<B>-O</B>
140+optimize.
141+Debug information is removed
142+and
143+duplicate constants are coalesced.
144+<P>
120145 <B>-p</B>
121−parse sources files but does not generate any output file.
146+parse sources files but do not generate any output file.
122147 Used mainly for syntax checking.
123148 <P>
124149 <B>-q</B>
125150 quiet; produces no listing.
126151 This is the default when compiling.
127152 <P>
153+<B>-t</B>
154+perform a thourough integrity test when undumping.
155+Code that passes this test is completely safe,
156+in the sense that it will not break the interpreter.
157+However,
158+there is no guarantee that such code does anything sensible.
159+(None can be given, because the halting problem is unsolvable.)
160+<P>
161+<B>-U "</B><I>name"</I>
162+undefine symbol
163+<I>name</I>
164+for conditional compilation.
165+<P>
128166 <B>-v</B>
129167 print version information.
130168 <P>
@@ -135,7 +173,7 @@ print the names of the source files as they are processed. · 4 unmodified lines
135173 <P>
136174 <B>luac.out</B>
137175 default output file
138−<H1>"SEE ALSO"</H1>
176+<H1>SEE ALSO</H1>
139177 <B>lua</B>(1)
140178 <BR>
141179 <I>"Reference Manual of the Programming Language Lua"</I>
@@ -148,11 +186,9 @@ default output file · 6 unmodified lines
148186 #6 (1996) 635-652.
149187 <H1>DIAGNOSTICS</H1>
150188 Error messages should be self explanatory.
151−<H1>BUGS</H1>
152−Inherits any bugs from Lua,
153−but Lua has no bugs...
154189 <H1>AUTHORS</H1>
155190 L. H. de Figueiredo,
156191 R. Ierusalimschy and
157192 W. Celes
158193 <I>(<A HREF="mailto:lua@tecgraf.puc-rio.br">lua@tecgraf.puc-rio.br</A>)</I>
194+<!-- EOF -->
doc/luac.man+65−42
@@ -1,35 +1,14 @@
1−.\" $Id: luac.man,v 1.11 1998/07/01 14:51:45 lhf Exp $
2−.TH LUAC 1 "01 July 1998"
1+.\" luac.man,v 1.17 1999/07/07 16:02:07 lhf Exp
2+.TH LUAC 1 "1999/07/07 16:02:07"
33 .SH NAME
44 luac \- Lua compiler
55 .SH SYNOPSIS
66 .B luac
77 [
8−.B \-c
9−|
10−.B \-u
11−] [
12−.B \-d
13−] [
14−.B \-D
15−.I name
16−] [
17−.B \-l
18−] [
19−.B \-o
20−.I filename
21−] [
22−.B \-O
8+.I options
239 ] [
24−.B \-p
25−] [
26−.B \-q
27−] [
28−.B \-v
29−] [
30−.B \-V
10+.I filenames
3111 ]
32−.IR sourcefile " ..."
3312 .SH DESCRIPTION
3413 .B luac
3514 is the Lua compiler.
@@ -43,10 +22,16 @@ in Lua. · 7 unmodified lines
4322 The main advantages of pre-compiling chunks are:
4423 faster loading,
4524 protecting source code from user changes,
25+and
4626 off-line syntax error detection.
4727 The binary files created by
4828 .B luac
49−are portable to all known architectures.
29+are portable to all architectures.
30+.LP
31+Pre-compiling does not imply faster execution
32+because in Lua chunks are always compiled into bytecodes before being executed.
33+.B luac
34+simply allows those bytecodes to be saved in a file for later execution.
5035 .LP
5136 .B luac
5237 produces a single output file containing the bytecodes
@@ -71,16 +56,26 @@ option. · 18 unmodified lines
7156 .LP
7257 Binary files produced by differents runs of
7358 .B luac
59+(even in different machines)
7460 can be combined into one large file,
7561 using
7662 .BR cat (1).
77−The result is still a valid binary file,
63+The result is still a valid binary file
7864 and can be loaded with a single call to
7965 .B lua_dofile
8066 or
8167 .BR dofile .
8268 .LP
69+The internal format of the binary files produced by
70+.B luac
71+may change when a new version of Lua is released.
72+We try to maintain compatibility even for binary files,
73+but sometimes it cannot be done.
74+So,
75+save the source files of all Lua programs that you precompile.
76+.LP
8377 .SH OPTIONS
78+Options must be separate.
8479 .TP
8580 .B \-c
8681 compile (this is the default).
@@ -89,6 +84,21 @@ compile (this is the default). · 2 unmodified lines
8984 undump, i.e., load and list the given binary files.
9085 If no files are given, then luac undumps
9186 .BR luac.out .
87+Listing a binary file is useful to learn Lua's virtual machine.
88+Listing is also useful to test the integrity of binary files:
89+corrupted files will probably generate errors when undumped.
90+To test without listing, use
91+.BR \-q .
92+For a thourough integrity test,
93+use
94+.BR \-t .
95+.TP
96+.B \-d
97+turn debugging on.
98+Individual chunks may
99+still control the generation of debug information with
100+$debug and $nodebug.
101+If debugging is on, then listings show the names of the local variables.
92102 .TP
93103 .BI \-D " name"
94104 predefine symbol
@@ -101,21 +111,17 @@ does · 6 unmodified lines
101111 predefine any symbols,
102112 not even the built-in functions.
103113 .TP
104−.B \-d
105−turn debugging on.
106−Individual chunks may
107−still control the generation of debug information with
108−$debug and $nodebug.
109−If debugging is on, then listings show the names of the local variables.
110−.TP
111114 .B \-l
112115 produce a listing of the compiled bytecode for Lua's virtual machine.
113116 This is the default when undumping.
114117 .TP
115−.B \-O
116−optimize code.
117−Debug information is removed,
118−duplicate constants are coalesced.
118+.B \-n
119+Save numbers in native format.
120+By default,
121+numbers are saved in text form,
122+for maximum portability.
123+Binary files with numbers in native format are slightly faster to load,
124+but are not completely portable.
119125 .TP
120126 .BI \-o " filename"
121127 output to
@@ -124,14 +130,33 @@ instead of the default · 2 unmodified lines
124130 .BR luac.out .
125131 The output file cannot be a source file.
126132 .TP
133+.B \-O
134+optimize.
135+Debug information is removed
136+and
137+duplicate constants are coalesced.
138+.TP
127139 .B \-p
128−parse sources files but does not generate any output file.
140+parse sources files but do not generate any output file.
129141 Used mainly for syntax checking.
130142 .TP
131143 .B \-q
132144 quiet; produces no listing.
133145 This is the default when compiling.
134146 .TP
147+.B \-t
148+perform a thourough integrity test when undumping.
149+Code that passes this test is completely safe,
150+in the sense that it will not break the interpreter.
151+However,
152+there is no guarantee that such code does anything sensible.
153+(None can be given, because the halting problem is unsolvable.)
154+.TP
155+.BI \-U " name"
156+undefine symbol
157+.I name
158+for conditional compilation.
159+.TP
135160 .B \-v
136161 print version information.
137162 .TP
@@ -155,11 +180,9 @@ http://www.tecgraf.puc-rio.br/lua/ · 17 unmodified lines
155180 #6 (1996) 635-652.
156181 .SH DIAGNOSTICS
157182 Error messages should be self explanatory.
158−.SH BUGS
159−Inherits any bugs from Lua,
160−but Lua has no bugs...
161183 .SH AUTHORS
162184 L. H. de Figueiredo,
163185 R. Ierusalimschy and
164186 W. Celes
165187 .I (lua@tecgraf.puc-rio.br)
188+.\" EOF
doc/manual.html+628−298
@@ -1,9 +1,12 @@
11 <HEAD>
2−<TITLE>Lua 3.1 Reference Manual</TITLE>
2+<TITLE>Lua 3.2 Reference Manual</TITLE>
33 </HEAD>
4−<BODY>
5−<h1>Lua 3.1 Reference Manual</h1>
4+<BODY BGCOLOR="#FFFFFF">
5+<h1>Lua 3.2 Reference Manual</h1>
66
7+<!-- $Id: manual.tex,v 1.33 1999/05/27 20:21:03 roberto Exp $ -->
8+<P>
9+<P>
710 <!-- ====================================================================== -->
811 <HR>
912 <A NAME="1."></A>
@@ -14,10 +17,6 @@ general procedural programming with data description · 4 unmodified lines
1417 facilities.
1518 Lua is intended to be used as a light-weight, but powerful,
1619 configuration language for any program that needs one.
17−Lua has been designed and implemented by
18−W.&nbsp;Celes,
19−R.&nbsp;Ierusalimschy and
20−L.&nbsp;H.&nbsp;de Figueiredo.
2120 <P>
2221 Lua is implemented as a library, written in C.
2322 Being an extension language, Lua has no notion of a ``main'' program:
@@ -48,15 +47,17 @@ at the following URL's: · 24 unmodified lines
4847 <P>
4948 All statements in Lua are executed in a <A NAME="global environment"><EM>global environment</EM></A>.
5049 This environment, which keeps all global variables,
51−is initialized at the beginning of the embedding program and
52−persists until its end.
50+is initialized with a call from the embedding program to
51+<CODE>lua_open</CODE> and
52+persists until a call to <CODE>lua_close</CODE>,
53+or the end of the embedding program.
5354 Optionally, a user can create multiple independent global
5455 environments (see Section&nbsp;<A HREF="#mangstate">5.1</A>).
5556 <P>
5657 The global environment can be manipulated by Lua code or
5758 by the embedding program,
5859 which can read and write global variables
59−using functions from the API library that implements Lua.
60+using API functions from the library that implements Lua.
6061 <P>
6162 <A NAME="Global variables">Global variables</A> do not need declaration.
6263 Any variable is assumed to be global unless explicitly declared local
@@ -79,7 +80,7 @@ A chunk may optionally end with a <CODE>return</CODE> statement (see Section&nbs · 16 unmodified lines
7980 When a chunk is executed, first all its code is pre-compiled,
8081 then the statements are executed in sequential order.
8182 All modifications a chunk effects on the global environment persist
82−after its end.
83+after the chunk end.
8384 <P>
8485 Chunks may also be pre-compiled into binary form;
8586 see program <A NAME="luac"><TT><A HREF="luac.html">luac</A></TT></A> for details.
@@ -104,7 +105,7 @@ There are six <A NAME="basic types">basic types</A> in Lua: <A NAME="nil"><EM>ni · 18 unmodified lines
104105 <A NAME="string"><EM>string</EM></A>, <A NAME="function"><EM>function</EM></A>, <A NAME="userdata"><EM>userdata</EM></A>, and <A NAME="table"><EM>table</EM></A>.
105106 <EM>Nil</EM> is the type of the value <B>nil</B>,
106107 whose main property is to be different from any other value.
107−<EM>Number</EM> represents real (double precision floating point) numbers,
108+<EM>Number</EM> represents real (double-precision floating-point) numbers,
108109 while <EM>string</EM> has the usual meaning.
109110 Lua is <A NAME="eight-bit clean">eight-bit clean</A>,
110111 and so strings may contain any 8-bit character,
@@ -160,7 +161,7 @@ semantics of Lua (see Section&nbsp;<A HREF="#tag-method">4.8</A>). · 49 unmodified lines
160161 Each of the types <EM>nil</EM>, <EM>number</EM> and <EM>string</EM> has a different tag.
161162 All values of each of these types have this same pre-defined tag.
162163 Values of type <EM>function</EM> can have two different tags,
163−depending on whether they are Lua or C functions.
164+depending on whether they are Lua functions or C functions.
164165 Finally,
165166 values of type <EM>userdata</EM> and <EM>table</EM> can have
166167 as many different tags as needed (see Section&nbsp;<A HREF="#tag-method">4.8</A>).
@@ -200,7 +201,7 @@ Lua is a case-sensitive language: · 33 unmodified lines
200201 <TT>and</TT> is a reserved word, but <TT>And</TT> and <TT>\'and</TT>
201202 (if the locale permits) are two other different identifiers.
202203 As a convention, identifiers starting with underscore followed by
203−uppercase letters should not be used in regular programs.
204+uppercase letters are reserved for internal variables.
204205 <P>
205206 The following strings denote other <A NAME="tokens">tokens</A>:
206207 <PRE>
@@ -211,7 +212,7 @@ The following strings denote other <A NAME="tokens">tokens</A>: · 4 unmodified lines
211212 <A NAME="Literal strings">Literal strings</A> can be delimited by matching single or double quotes,
212213 and can contain the C-like escape sequences
213214 <CODE>'\a'</CODE> (bell),
214−<CODE>'\b'</CODE> (back space),
215+<CODE>'\b'</CODE> (backspace),
215216 <CODE>'\f'</CODE> (form feed),
216217 <CODE>'\n'</CODE> (new line),
217218 <CODE>'\r'</CODE> (carriage return),
@@ -251,9 +252,9 @@ in Unix systems (see Section&nbsp;<A HREF="#lua-sa">8</A>). · 33 unmodified lines
251252 <P>
252253 <A NAME="Numerical constants">Numerical constants</A> may be written with an optional decimal part,
253254 and an optional decimal exponent.
254−Examples of valid numerical constants are:
255+Examples of valid numerical constants are
255256 <PRE>
256− 4 4.0 0.4 4.57e-3 0.3e12
257+ 3 3.0 3.1416 314.16e-2 0.31416E1
257258 </PRE>
258259 <P>
259260 <A NAME="pre-processor"></A>
@@ -280,7 +281,7 @@ Directives may be freely nested. · 20 unmodified lines
280281 Particularly, a <CODE>$endinput</CODE> may occur inside a <CODE>$if</CODE>;
281282 in that case, even the matching <CODE>$end</CODE> is not parsed.
282283 <P>
283−A <EM>cond</EM> part may be:
284+A <EM>cond</EM> part may be
284285 <DL>
285286 <DT><B><TT>nil</TT></B><DD> - always false.
286287 <DT><B><TT>1</TT></B><DD> - always true.
@@ -298,11 +299,7 @@ Lua provides some automatic conversions between values at run time. · 11 unmodified lines
298299 Any arithmetic operation applied to a string tries to convert
299300 that string to a number, following the usual rules.
300301 Conversely, whenever a number is used when a string is expected,
301−that number is converted to a string, according to the following rule:
302−if the number is an integer, it is written without exponent or decimal point;
303−otherwise, it is formatted following the <CODE>%g</CODE>
304−conversion specification of the <CODE>printf</CODE> function in the
305−standard C library.
302+that number is converted to a string, in a reasonable format.
306303 For complete control on how numbers are converted to strings,
307304 use the <CODE>format</CODE> function (see Section&nbsp;<A HREF="#format">6.2</A>).
308305 <P>
@@ -313,12 +310,13 @@ use the <CODE>format</CODE> function (see Section&nbsp;<A HREF="#format">6.2</A> · 4 unmodified lines
313310 <P>
314311 Functions in Lua can return many values.
315312 Because there are no type declarations,
313+when a function is called
316314 the system does not know how many values a function will return,
317315 or how many parameters it needs.
318316 Therefore, sometimes, a list of values must be <EM>adjusted</EM>, at run time,
319317 to a given length.
320318 If there are more values than are needed,
321−then the last values are thrown away.
319+then the excess values are thrown away.
322320 If there are more needs than values,
323321 then the list is extended with as many <B>nil</B>'s as needed.
324322 Adjustment occurs in multiple assignment (see Section&nbsp;<A HREF="#assignment">4.5.2</A>)
@@ -376,7 +374,7 @@ The two lists may have different lengths. · 51 unmodified lines
376374 Before the assignment, the list of values is <EM>adjusted</EM> to
377375 the length of the list of variables (see Section&nbsp;<A HREF="#adjust">4.4</A>).
378376 <P>
379−A single name can denote a global or a local variable,
377+A single name can denote a global variable, a local variable,
380378 or a formal parameter:
381379 <PRE>
382380 var ::= name
@@ -414,15 +412,14 @@ only <B>nil</B> is considered false. · 31 unmodified lines
414412 <P>
415413 <A NAME="while-do"></A><A NAME="repeat-until"></A><A NAME="if-then-else"></A>
416414 <PRE>
417−stat ::= <B>while</B> exp1 <B>do</B> block <B>end</B> <BR> | <B>repeat</B> block <B>until</B> exp1 <BR> | <B>if</B> exp1 <B>then</B> block {elseif} [<B>else</B> block] <B>end</B>
418−elseif ::= <B>elseif</B> exp1 <B>then</B> block
415+stat ::= <B>while</B> exp1 <B>do</B> block <B>end</B> <BR> | <B>repeat</B> block <B>until</B> exp1 <BR> | <B>if</B> exp1 <B>then</B> block {<B>elseif</B> exp1 <B>then</B> block} [<B>else</B> block] <B>end</B>
419416 </PRE>
420417 <P>
421418 A <TT>return</TT> is used to return values from a function or from a chunk.
422419 <A NAME="return"></A>
423420
424421 Because they may return more than one value,
425−the syntax for a <A NAME="return statement">return statement</A> is:
422+the syntax for a <A NAME="return statement">return statement</A> is
426423 <PRE>
427424 ret ::= <B>return</B> [explist1] [sc]
428425 </PRE>
@@ -457,7 +454,7 @@ Otherwise, all variables are initialized with <B>nil</B>. · 28 unmodified lines
457454 <H2>4.6 - Expressions</H2>
458455 <P>
459456 <H3>4.6.1 - <A NAME="Basic Expressions</H3>">Basic Expressions</H3></A>
460−Basic expressions are:
457+Basic expressions are
461458 <PRE>
462459 exp ::= '<B>(</B>' exp '<B>)</B>'
463460 exp ::= <B>nil</B>
@@ -477,7 +474,7 @@ string literals are explained in Section&nbsp;<A HREF="#lexical">4.1</A>; · 13 unmodified lines
477474 variables are explained in Section&nbsp;<A HREF="#assignment">4.5.2</A>;
478475 upvalues are explained in Section&nbsp;<A HREF="#upvalue">4.7</A>;
479476 function definitions (<EM>function</EM>) are explained in Section&nbsp;<A HREF="#func-def">4.6.9</A>;
480−function call are explained in Section&nbsp;<A HREF="#functioncall">4.6.8</A>.
477+function calls are explained in Section&nbsp;<A HREF="#functioncall">4.6.8</A>.
481478 <P>
482479 An access to a global variable <CODE>x</CODE> is equivalent to a
483480 call <CODE>getglobal('x')</CODE>;
@@ -535,7 +532,7 @@ then their values are compared using lexicographical order. · 51 unmodified lines
535532 Otherwise, the ``order'' tag method is called (see Section&nbsp;<A HREF="#tag-method">4.8</A>).
536533 <P>
537534 <H3>4.6.4 - Logical Operators</H3>
538−The <A NAME="logical operators">logical operators</A> are:
535+The <A NAME="logical operators">logical operators</A> are
539536 <A NAME="and"></A><A NAME="or"></A><A NAME="not"></A>
540537 <PRE>
541538 and or not
@@ -589,7 +586,7 @@ every time a constructor is evaluated, a new table is created. · 47 unmodified lines
589586 Constructors can be used to create empty tables,
590587 or to create a table and initialize some fields.
591588 <P>
592−The general syntax for constructors is:
589+The general syntax for constructors is
593590 <PRE>
594591 tableconstructor ::= '<B>{</B>' fieldlist '<B>}</B>'
595592 fieldlist ::= lfieldlist | ffieldlist | lfieldlist '<B>;</B>' ffieldlist | ffieldlist '<B>;</B>' lfieldlist
@@ -597,17 +594,17 @@ lfieldlist ::= [lfieldlist1] · 1 unmodified line
597594 ffieldlist ::= [ffieldlist1]
598595 </PRE>
599596 <P>
600−The form <EM>lfieldlist1</EM> is used to initialize lists.
597+The form <EM>lfieldlist1</EM> is used to initialize lists:
601598 <PRE>
602599 lfieldlist1 ::= exp {'<B>,</B>' exp} ['<B>,</B>']
603600 </PRE>
604601 The expressions in the list are assigned to consecutive numerical indices,
605602 starting with 1.
606−For example:
603+For example,
607604 <PRE>
608605 a = {"v1", "v2", 34}
609606 </PRE>
610−is equivalent to:
607+is equivalent to
611608 <PRE>
612609 do
613610 local temp = {}
@@ -623,11 +620,11 @@ The form <EM>ffieldlist1</EM> initializes other fields in a table: · 9 unmodified lines
623620 ffieldlist1 ::= ffield {'<B>,</B>' ffield} ['<B>,</B>']
624621 ffield ::= '<B>[</B>' exp '<B>]</B>' '<B>=</B>' exp | name '<B>=</B>' exp
625622 </PRE>
626−For example:
623+For example,
627624 <PRE>
628625 a = {[f(k)] = g(y), x = 1, y = 3, [0] = b+c}
629626 </PRE>
630−is equivalent to:
627+is equivalent to
631628 <PRE>
632629 do
633630 local temp = {}
@@ -649,7 +646,7 @@ For example, all forms below are correct: · 15 unmodified lines
649646 x = {;}
650647 x = {'a', 'b',}
651648 x = {type='list'; 'a', 'b'}
652− x = {f(0), f(1), f(2),; n=3}
649+ x = {f(0), f(1), f(2),; n=3,}
653650 </PRE>
654651 <P>
655652 <A NAME="functioncall"></A>
@@ -678,6 +675,7 @@ is syntactic sugar for · 22 unmodified lines
678675 </PRE>
679676 except that <CODE>simpleexp</CODE> is evaluated only once.
680677 <P>
678+Arguments have the following syntax:
681679 <PRE>
682680 args ::= '<B>(</B>' [explist1] '<B>)</B>'
683681 args ::= tableconstructor
@@ -707,33 +705,33 @@ If the function is called in a place that can hold many values · 23 unmodified lines
707705 (syntactically denoted by the non-terminal <EM>exp</EM>),
708706 then no adjustment is made.
709707 Note that the only place that can hold many values
710−is the last expression (or the only one) in an assignment
708+is the last (or the only) expression in an assignment
711709 or in a return statement; see examples below.
712710 <PRE>
713− f(); -- adjusted to 0
714− g(x, f()); -- f() is adjusted to 1
715− a,b,c = f(), x; -- f() is adjusted to 1 result (and c gets nil)
716− a,b,c = x, f(); -- f() is adjusted to 2
717− a,b,c = f(); -- f() is adjusted to 3
718− return f(); -- returns all values returned by f()
711+ f(); -- adjusted to 0
712+ g(x, f()); -- f() is adjusted to 1
713+ a,b,c = f(), x; -- f() is adjusted to 1 result (and c gets nil)
714+ a,b,c = x, f(); -- f() is adjusted to 2
715+ a,b,c = f(); -- f() is adjusted to 3
716+ return f(); -- returns all values returned by f()
719717 </PRE>
720718 <P>
721719 <A NAME="func-def"></A>
722720 <H3>4.6.9 - <A NAME="Function Definitions</H3>">Function Definitions</H3></A>
723721 <P>
724−The syntax for function definition is:
722+The syntax for function definition is
725723 <PRE>
726724 function ::= <B>function</B> '<B>(</B>' [parlist1] '<B>)</B>' block <B>end</B>
727725 stat ::= <B>function</B> funcname '<B>(</B>' [parlist1] '<B>)</B>' block <B>end</B>
728726 funcname ::= name | name '<B>.</B>' name
729727 </PRE>
730−The statement:
728+The statement
731729 <PRE>
732730 function f (...)
733731 ...
734732 end
735733 </PRE>
736−is just syntactic sugar for:
734+is just syntactic sugar for
737735 <PRE>
738736 f = function (...)
739737 ...
@@ -769,8 +767,8 @@ A vararg function does not adjust its argument list; · 29 unmodified lines
769767 instead, it collects any extra arguments into an implicit parameter,
770768 called <A NAME="arg"><TT>arg</TT></A>.
771769 This parameter is always initialized as a table,
772−with a field <CODE>n</CODE> with the number of extra arguments,
773−and the extra arguments at positions 1, 2, ...
770+with a field <CODE>n</CODE> whose value is the number of extra arguments,
771+and the extra arguments at positions 1,&nbsp;2,&nbsp;...
774772 <P>
775773 As an example, suppose definitions like:
776774 <PRE>
@@ -795,21 +793,21 @@ If control reaches the end of a function without a return instruction, · 18 unmodified lines
795793 then the function returns with no results.
796794 <P>
797795 There is a special syntax for defining <A NAME="methods">methods</A>,
798−that is, functions that have an implicit extra parameter <A NAME="self"><TT>self</TT></A>.
796+that is, functions that have an implicit extra parameter <A NAME="self"><TT>self</TT></A>:
799797 <PRE>
800798 function ::= <B>function</B> name '<B>:</B>' name '<B>(</B>' [parlist1] '<B>)</B>' block <B>end</B>
801799 </PRE>
802800 Thus, a declaration like
803801 <PRE>
804−function v:f (...)
805− ...
806−end
802+ function v:f (...)
803+ ...
804+ end
807805 </PRE>
808806 is equivalent to
809807 <PRE>
810−v.f = function (self, ...)
811− ...
812−end
808+ v.f = function (self, ...)
809+ ...
810+ end
813811 </PRE>
814812 that is, the function gets an extra formal parameter called <CODE>self</CODE>.
815813 Note that the variable <CODE>v</CODE> must have been
@@ -842,19 +840,19 @@ at the point where the function is defined. · 26 unmodified lines
842840 <P>
843841 Here are some examples:
844842 <PRE>
845−a,b,c = 1,2,3 -- global variables
846−function f (x)
847− local b -- x and b are local to f
848− local g = function (a)
849− local y -- a and y are local to g
850− p = a -- OK, access local 'a'
851− p = c -- OK, access global 'c'
852− p = b -- ERROR: cannot access a variable in outer scope
853− p = %b -- OK, access frozen value of 'b' (local to 'f')
854− p = %c -- OK, access frozen value of global 'c'
855− p = %y -- ERROR: 'y' is not visible where 'g' is defined
856− end -- g
857−end -- f
843+ a,b,c = 1,2,3 -- global variables
844+ function f (x)
845+ local b -- x and b are local to f
846+ local g = function (a)
847+ local y -- a and y are local to g
848+ p = a -- OK, access local 'a'
849+ p = c -- OK, access global 'c'
850+ p = b -- ERROR: cannot access a variable in outer scope
851+ p = %b -- OK, access frozen value of 'b' (local to 'f')
852+ p = %c -- OK, access frozen value of global 'c'
853+ p = %y -- ERROR: 'y' is not visible where 'g' is defined
854+ end -- g
855+ end -- f
858856 </PRE>
859857 <P>
860858 <P>
@@ -863,7 +861,7 @@ end -- f · 2 unmodified lines
863861 <H2>4.8 - Tag Methods</H2>
864862 <P>
865863 Lua provides a powerful mechanism to extend its semantics,
866−called <A NAME="Tag Methods"><EM>Tag Methods</EM></A>.
864+called <A NAME="tag methods"><EM>tag methods</EM></A>.
867865 A tag method is a programmer-defined function
868866 that is called at specific key points during the evaluation of a program,
869867 allowing the programmer to change the standard Lua behavior at these points.
@@ -874,10 +872,10 @@ according to the tag of the values involved · 4 unmodified lines
874872 in the event (see Section&nbsp;<A HREF="#TypesSec">3</A>).
875873 The function <A NAME="settagmethod"><TT>settagmethod</TT></A> changes the tag method
876874 associated with a given pair <EM>(tag, event)</EM>.
877−Its first parameter is the tag, the second is the event name
878−(a string, see below),
875+Its first parameter is the tag, the second parameter is the event name
876+(a string; see below),
879877 and the third parameter is the new method (a function),
880−or <B>nil</B> to restore the default behavior.
878+or <B>nil</B> to restore the default behavior for the pair.
881879 The function returns the previous tag method for that pair.
882880 Another function, <A NAME="gettagmethod"><TT>gettagmethod</TT></A>,
883881 receives a tag and an event name and returns the
@@ -893,7 +891,7 @@ Please notice that the code shown here is only illustrative; · 9 unmodified lines
893891 the real behavior is hard coded in the interpreter,
894892 and it is much more efficient than this simulation.
895893 All functions used in these descriptions
896−(<CODE>rawgetglobal</CODE>, <CODE>tonumber</CODE>, <CODE>call</CODE>, etc)
894+(<CODE>rawgetglobal</CODE>, <CODE>tonumber</CODE>, <CODE>call</CODE>, etc.)
897895 are described in Section&nbsp;<A HREF="#predefined">6.1</A>.
898896 <P>
899897 <DL>
@@ -1137,7 +1135,7 @@ called when Lua tries to call a non function value. · 237 unmodified lines
11371135 </PRE>
11381136 <P>
11391137 <DT><B>``gc'':</B><DD><A NAME="gc event"></A>
1140−called when Lua is garbage collecting an object.
1138+called when Lua is ``garbage collecting'' an object.
11411139 This method cannot be set for strings, numbers, functions,
11421140 and userdata with default tag.
11431141 For each object to be collected,
@@ -1165,29 +1163,27 @@ Because Lua is an extension language, · 21 unmodified lines
11651163 all Lua actions start from C code in the host program
11661164 calling a function from the Lua library.
11671165 Whenever an error occurs during Lua compilation or execution,
1168−the <A NAME="error method"><EM>error method</EM></A> is called,
1166+function <CODE>_ERRORMESSAGE</CODE> is called <A NAME="_ERRORMESSAGE"></A>
1167+(provided it is different from <B>nil</B>),
11691168 and then the corresponding function from the library
11701169 (<CODE>lua_dofile</CODE>, <CODE>lua_dostring</CODE>,
11711170 <CODE>lua_dobuffer</CODE>, or <CODE>lua_callfunction</CODE>)
11721171 is terminated, returning an error condition.
11731172 <P>
1174−The only argument to the error method is a string
1173+The only argument to <CODE>_ERRORMESSAGE</CODE> is a string
11751174 describing the error.
1176−The default method prints this message to <CODE>stderr</CODE>.
1177−If needed, it is possible to change the error method with the
1178−function <CODE>seterrormethod</CODE>,
1179−which gets the new error handler as its only parameter
1180−(see Section&nbsp;<A HREF="#pdf-seterrormethod">6.1</A>).
1181−The standard I/O library uses this facility to redefine the error method,
1182−using the debug facilities (see Section&nbsp;<A HREF="#debugI">7</A>),
1183−in order to print some extra information,
1175+The default definition for this function calls <CODE>_ALERT</CODE>,
1176+which prints the message to <CODE>stderr</CODE> (see Section&nbsp;<A HREF="#alert">6.1</A>).
1177+The standard I/O library redefines <CODE>_ERRORMESSAGE</CODE>,
1178+and uses the debug facilities (see Section&nbsp;<A HREF="#debugI">7</A>)
1179+to print some extra information,
11841180 such as the call stack.
11851181 <P>
11861182 To provide more information about errors,
11871183 Lua programs should include the compilation pragma <CODE>$debug</CODE>.
11881184 <A NAME="pragma"></A>
11891185 <A NAME="debug pragma"></A>
1190−When an error occurs in a program compiled with this option,
1186+When an error occurs in a chunk compiled with this option,
11911187 the I/O error routine is able to print the number of the
11921188 lines where the calls (and the error) were made.
11931189 <P>
@@ -1229,6 +1225,8 @@ is stored in a dynamic structure pointed by<A NAME="lua_state"></A> · 35 unmodified lines
12291225 typedef struct lua_State lua_State;
12301226 extern lua_State *lua_state;
12311227 </PRE>
1228+The variable <CODE>lua_state</CODE> is the only C global variable in
1229+the Lua library.
12321230 <P>
12331231 Before calling any API function,
12341232 this state must be initialized.
@@ -1255,19 +1253,19 @@ For that, you must set <CODE>lua_state</CODE> back to <CODE>NULL</CODE> before · 20 unmodified lines
12551253 calling <CODE>lua_open</CODE>.
12561254 An easy way to do that is defining an auxiliary function:
12571255 <PRE>
1258−lua_State *lua_newstate (void) {
1259− lua_State *old = lua_setstate(NULL);
1260− lua_open();
1261− return lua_setstate(old);
1262−}
1256+ lua_State *lua_newstate (void) {
1257+ lua_State *old = lua_setstate(NULL);
1258+ lua_open();
1259+ return lua_setstate(old);
1260+ }
12631261 </PRE>
12641262 This function creates a new state without changing the current state
12651263 of the interpreter.
1266−Note that any new state is built with all predefined functions,
1264+Note that any new state is created with all predefined functions,
12671265 but any additional library (such as the standard libraries) must be
12681266 explicitly open in the new state, if needed.
12691267 <P>
1270−If necessary, a state may be released:<A NAME="lua_close"></A>
1268+If necessary, a state may be released by calling<A NAME="lua_close"></A>
12711269 <PRE>
12721270 void lua_close (void);
12731271 </PRE>
@@ -1281,14 +1279,14 @@ If <CODE>lua_state</CODE> is already <CODE>NULL</CODE>, · 7 unmodified lines
12811279 <CODE>lua_close</CODE> has no effect.
12821280 <P>
12831281 If you are using multiple states,
1284−you may find useful the following function,
1282+you may find useful to define the following function,
12851283 which releases a given state:
12861284 <PRE>
1287−void lua_freestate (lua_State *st) {
1288− lua_State *old = lua_setstate(st);
1289− lua_close();
1290− if (old != st) lua_setstate(old);
1291−}
1285+ void lua_freestate (lua_State *st) {
1286+ lua_State *old = lua_setstate(st);
1287+ lua_close();
1288+ if (old != st) lua_setstate(old);
1289+ }
12921290 </PRE>
12931291 <P>
12941292 <A NAME="valuesCLua"></A>
@@ -1316,7 +1314,7 @@ int lua_isfunction (lua_Object object); · 21 unmodified lines
13161314 int lua_iscfunction (lua_Object object);
13171315 int lua_isuserdata (lua_Object object);
13181316 </PRE>
1319−All macros return 1 if the object is compatible with the given type,
1317+These functions return 1 if the object is compatible with the given type,
13201318 and 0 otherwise.
13211319 The function <CODE>lua_isnumber</CODE> accepts numbers and numerical strings,
13221320 whereas
@@ -1356,7 +1354,8 @@ but may contain other zeros in their body. · 33 unmodified lines
13561354 If you do not know whether a string may contain zeros,
13571355 you can use <CODE>lua_strlen</CODE> to get the actual length.
13581356 Because Lua has garbage collection,
1359−there is no guarantee that such pointer will be valid after the block ends
1357+there is no guarantee that the pointer returned by <CODE>lua_getstring</CODE>
1358+will be valid after the block ends
13601359 (see Section&nbsp;<A HREF="#GC">5.3</A>).
13611360 <P>
13621361 <CODE>lua_getcfunction</CODE> converts a <CODE>lua_Object</CODE> to a C function.
@@ -1415,7 +1414,7 @@ Note that the structure lua2C cannot be directly modified by C code. · 52 unmodified lines
14151414 <P>
14161415 The second structure, C2lua, is an abstract stack.
14171416 Pushing elements into this stack
1418−is done with the following functions and macros:
1417+is done with the following functions:
14191418 <A NAME="lua_pushnumber"></A><A NAME="lua_pushlstring"></A><A NAME="lua_pushstring"></A>
14201419 <A NAME="lua_pushcfunction"></A><A NAME="lua_pushusertag"></A>
14211420 <A NAME="lua_pushnil"></A><A NAME="lua_pushobject"></A>
@@ -1433,7 +1432,7 @@ void lua_pushcfunction (lua_CFunction f); /* macro */ · 11 unmodified lines
14331432 All of them receive a C value,
14341433 convert it to a corresponding <CODE>lua_Object</CODE>,
14351434 and leave the result on the top of C2lua.
1436−Particularly, functions <CODE>lua_pushlstring</CODE> and <CODE>lua_pushstring</CODE>
1435+In particular, functions <CODE>lua_pushlstring</CODE> and <CODE>lua_pushstring</CODE>
14371436 make an internal copy of the given string.
14381437 Function <CODE>lua_pushstring</CODE> can only be used to push proper C strings
14391438 (that is, strings that do not contain zeros and end with a zero);
@@ -1518,9 +1517,6 @@ is the ``name of the chunk'', · 78 unmodified lines
15181517 used in error messages and debug information.
15191518 If <CODE>name</CODE> is <CODE>NULL</CODE>,
15201519 Lua gives a default name to the chunk.
1521−In files this name is the file name,
1522−and <CODE>lua_dostring</CODE> uses a small prefix
1523−of the string as the chunk name.
15241520 <P>
15251521 These functions return, in structure lua2C,
15261522 any values eventually returned by the chunks.
@@ -1565,7 +1561,7 @@ The function · 38 unmodified lines
15651561 <PRE>
15661562 lua_Object lua_gettable (void);
15671563 </PRE>
1568−pops from the stack C2lua a table and an index,
1564+pops a table and an index from the stack C2lua,
15691565 and returns the contents of the table at that index.
15701566 As in Lua, this operation may trigger a tag method.
15711567 To get the real value of any table index,
@@ -1579,7 +1575,7 @@ lua_Object lua_rawgettable (void); · 7 unmodified lines
15791575 To store a value in an index,
15801576 the program must push the table, the index,
15811577 and the value onto C2lua,
1582−and then call the function:
1578+and then call the function
15831579 <A NAME="lua_settable"></A>
15841580 <PRE>
15851581 void lua_settable (void);
@@ -1636,9 +1632,9 @@ equivalent to the Lua code: · 50 unmodified lines
16361632 lua_pushnumber(4); /* 3rd argument */
16371633 lua_callfunction(lua_getglobal("f")); /* call Lua function */
16381634 lua_pushobject(lua_getresult(1)); /* push first result of the call */
1639− lua_setglobal("a"); /* sets global variable 'a' */
1640− lua_pushobject(lua_getresult(2)); /* push second result of the call */
1641− lua_setglobal("b"); /* sets global variable 'b' */
1635+ lua_setglobal("a"); /* set global variable 'a' */
1636+ lua_pushobject(lua_getresult(2)); /* push second result of the call */
1637+ lua_setglobal("b"); /* set global variable 'b' */
16421638 </PRE>
16431639 <P>
16441640 Some special Lua functions have exclusive interfaces.
@@ -1651,19 +1647,11 @@ This function never returns. · 6 unmodified lines
16511647 If the C function has been called from Lua,
16521648 then the corresponding Lua execution terminates,
16531649 as if an error had occurred inside Lua code.
1654−Otherwise, the whole program terminates with a call to <CODE>exit(1)</CODE>.
1655−The <CODE>message</CODE> is passed to the error handler method.
1650+Otherwise, the whole host program terminates with a call to <CODE>exit(1)</CODE>.
1651+The <CODE>message</CODE> is passed to the error handler function,
1652+<CODE>_ERRORMESSAGE</CODE>.
16561653 If <CODE>message</CODE> is <CODE>NULL</CODE>,
1657−the error handler method is not called.
1658−<P>
1659−The error handler method (see Section&nbsp;<A HREF="#error">4.9</A>) can be
1660−changed with: <A NAME="lua_seterrormethod"></A>
1661−<PRE>
1662−lua_Object lua_seterrormethod (void);
1663−</PRE>
1664−This function sets the object at the top of C2lua
1665−as the new error method,
1666−and returns the old error method value.
1654+then <CODE>_ERRORMESSAGE</CODE> is not called.
16671655 <P>
16681656 Tag methods can be changed with: <A NAME="lua_settagmethod"></A>
16691657 <PRE>
@@ -1722,12 +1710,13 @@ Like a Lua function, a C function called by Lua can also return · 52 unmodified lines
17221710 many results.
17231711 <P>
17241712 When a C function is created,
1725−it is possible to associate some <EM>upvalues</EM> to it;
1713+it is possible to associate some <EM>upvalues</EM> to it,
1714+thus creating a C closure;
17261715 then these values are passed to the function whenever it is called,
17271716 as common arguments.
17281717 To associate upvalues to a function,
17291718 first these values must be pushed on C2lua.
1730−Then the function:
1719+Then the function
17311720 <A NAME="lua_pushcclosure"></A>
17321721 <PRE>
17331722 void lua_pushcclosure (lua_CFunction fn, int n);
@@ -1792,7 +1781,7 @@ The libraries, on the other hand, provide useful routines · 58 unmodified lines
17921781 that are implemented directly through the standard API.
17931782 Therefore, they are not necessary to the language,
17941783 and are provided as separate C modules.
1795−Currently there are three standard libraries:
1784+Currently, there are three standard libraries:
17961785 <UL>
17971786 <LI>string manipulation;
17981787 <LI>mathematical functions (sin, log, etc);
@@ -1809,17 +1798,16 @@ and <CODE>lua_iolibopen</CODE>, declared in <CODE>lualib.h</CODE>. · 10 unmodified lines
18091798 <A NAME="6.1"></A>
18101799 <H2>6.1 - Predefined Functions</H2>
18111800 <P>
1812−<h3> <TT>call (func, arg [, mode [, errmethod]])</TT></h3><A NAME="call"></A>
1801+<h3> <TT>call (func, arg [, mode [, errhandler]])</TT></h3><A NAME="call"></A>
18131802 <A NAME="pdf-call"></A>
18141803
1815−This function calls function <CODE>func</CODE> with
1804+Calls function <CODE>func</CODE> with
18161805 the arguments given by the table <CODE>arg</CODE>.
18171806 The call is equivalent to
18181807 <PRE>
1819− func(arg[1], arg[2], ..., arg[arg.n])
1808+ func(arg[1], arg[2], ..., arg[n])
18201809 </PRE>
1821−If <CODE>arg.n</CODE> is not defined,
1822−then Lua stops getting arguments at the first <B>nil</B> value.
1810+where <CODE>n</CODE> is the result of <CODE>getn(arg)</CODE> (see Section&nbsp;<A HREF="#getn">6.1</A>).
18231811 <P>
18241812 By default,
18251813 all results from <CODE>func</CODE> are just returned by the call.
@@ -1833,6 +1821,7 @@ For instance, the following calls produce the following results: · 7 unmodified lines
18331821 <PRE>
18341822 a = call(sin, {5}) --&gt; a = 0.0871557 = sin(5)
18351823 a = call(max, {1,4,5; n=2}) --&gt; a = 4 (only 1 and 4 are arguments)
1824+a = call(max, {1,4,5; n=2}, "p") --&gt; a = {4; n=1}
18361825 t = {x=1}
18371826 a = call(next, {t,nil;n=2}, "p") --&gt; a={"x", 1; n=2}
18381827 </PRE>
@@ -1842,14 +1831,15 @@ if an error occurs during the function call, · 3 unmodified lines
18421831 the error is propagated.
18431832 If the string <CODE>mode</CODE> contains <CODE>"x"</CODE>,
18441833 then the call is <EM>protected</EM>.<A NAME="protected calls"></A>
1845−In this mode, function <CODE>call</CODE> does not generate an error,
1846−whatever happens during the call.
1834+In this mode, function <CODE>call</CODE> does not propagate an error,
1835+regardless of what happens during the call.
18471836 Instead, it returns <B>nil</B> to signal the error
1848−(besides calling the appropriated error method).
1837+(besides calling the appropriated error handler).
18491838 <P>
1850−If provided, <CODE>errmethod</CODE> is temporarily set as the error method,
1851−while <CODE>func</CODE> runs.
1852−As a particular case, if <CODE>errmethod</CODE> is <B>nil</B>,
1839+If provided,
1840+<CODE>errhandler</CODE> is temporarily set as the error function
1841+<CODE>_ERRORMESSAGE</CODE>, while <CODE>func</CODE> runs.
1842+In particular, if <CODE>errhandler</CODE> is <B>nil</B>,
18531843 no error messages will be issued during the execution of the called function.
18541844 <P>
18551845 <h3> <TT>collectgarbage ([limit])</TT></h3><A NAME="collectgarbage"></A>
@@ -1858,13 +1848,13 @@ Returns the number of objects collected. · 2 unmodified lines
18581848 An optional argument, <CODE>limit</CODE>, is a number that
18591849 makes the next cycle occur only after that number of new
18601850 objects have been created.
1861−If absent, Lua uses an adaptive algorithm to set
1862−this limit.
1851+If <CODE>limit</CODE> is absent or equal to 0,
1852+Lua uses an adaptive algorithm to set this limit.
18631853 <CODE>collectgarbage</CODE> is equivalent to
18641854 the API function <CODE>lua_collectgarbage</CODE>.
18651855 <P>
18661856 <h3> <TT>dofile (filename)</TT></h3><A NAME="dofile"></A>
1867−This function receives a file name,
1857+Receives a file name,
18681858 opens the file, and executes the file contents as a Lua chunk,
18691859 or as pre-compiled chunks.
18701860 When called without arguments,
@@ -1877,7 +1867,7 @@ It issues an error when called with a non string argument. · 6 unmodified lines
18771867 <CODE>dofile</CODE> is equivalent to the API function <CODE>lua_dofile</CODE>.
18781868 <P>
18791869 <h3> <TT>dostring (string [, chunkname])</TT></h3><A NAME="dostring"></A>
1880−This function executes a given string as a Lua chunk.
1870+Executes a given string as a Lua chunk.
18811871 If there is any error executing the string,
18821872 <CODE>dostring</CODE> returns <B>nil</B>.
18831873 Otherwise, it returns the values returned by the chunk,
@@ -1893,7 +1883,7 @@ Returns a new tag. · 9 unmodified lines
18931883 <CODE>newtag</CODE> is equivalent to the API function <CODE>lua_newtag</CODE>.
18941884 <P>
18951885 <h3> <TT>next (table, index)</TT></h3><A NAME="next"></A>
1896−This function allows a program to traverse all fields of a table.
1886+Allows a program to traverse all fields of a table.
18971887 Its first argument is a table and its second argument
18981888 is an index in this table.
18991889 It returns the next index of the table and the
@@ -1911,8 +1901,9 @@ field not present in a table or a field with value <B>nil</B>. · 11 unmodified lines
19111901 Therefore, the function only considers fields with non <B>nil</B> values.
19121902 The order in which the indices are enumerated is not specified,
19131903 <EM>even for numeric indices</EM>
1914−(to traverse a table in numeric order, use a counter).
1915−If the table is modified in any way during a traversal,
1904+(to traverse a table in numeric order,
1905+use a counter or the function <CODE>foreachi</CODE>).
1906+If the table indices are modified in any way during a traversal,
19161907 the semantics of <CODE>next</CODE> is undefined.
19171908 <P>
19181909 This function cannot be written with the standard API.
@@ -1925,67 +1916,35 @@ or <B>nil</B> to get a first name. · 6 unmodified lines
19251916 Similarly to <CODE>next</CODE>, it returns the name of another variable
19261917 and its value,
19271918 or <B>nil</B> if there are no more variables.
1928−There can be no assignments to global variables during the traversal;
1919+There can be no creation of new global variables during the traversal;
19291920 otherwise the semantics of <CODE>nextvar</CODE> is undefined.
19301921 <P>
19311922 This function cannot be written with the standard API.
19321923 <P>
1933−<h3> <TT>foreach (table, function)</TT></h3><A NAME="foreach"></A>
1934−Executes the given <CODE>function</CODE> over all elements of <CODE>table</CODE>.
1935−For each element, the function is called with the index and
1936−respective value as arguments.
1937−If the function returns any non-<B>nil</B> value,
1938−the loop is broken, and the value is returned
1939−as the final value of <CODE>foreach</CODE>.
1940−<P>
1941−This function could be defined in Lua:
1942−<PRE>
1943−function foreach (t, f)
1944− local i, v = next(t, nil)
1945− while i do
1946− local res = f(i, v)
1947− if res then return res end
1948− i, v = next(t, i)
1949− end
1950−end
1951−</PRE>
1952−<P>
1953−<h3> <TT>foreachvar (function)</TT></h3><A NAME="foreachvar"></A>
1954−Executes <CODE>function</CODE> over all global variables.
1955−For each variable,
1956−the function is called with its name and its value as arguments.
1957−If the function returns any non-nil value,
1958−the loop is broken, and the value is returned
1959−as the final value of <CODE>foreachvar</CODE>.
1960−<P>
1961−This function could be defined in Lua:
1962−<PRE>
1963−function foreachvar (f)
1964− local n, v = nextvar(nil)
1965− while n do
1966− local res = f(n, v)
1967− if res then return res end
1968− n, v = nextvar(n)
1969− end
1970−end
1971−</PRE>
1972−<P>
19731924 <h3> <TT>tostring (e)</TT></h3><A NAME="tostring"></A>
1974−This function receives an argument of any type and
1925+Receives an argument of any type and
19751926 converts it to a string in a reasonable format.
19761927 For complete control on how numbers are converted,
19771928 use function <CODE>format</CODE>.
19781929 <P>
19791930 <h3> <TT>print (e1, e2, ...)</TT></h3><A NAME="print"></A>
1980−This function receives any number of arguments,
1931+Receives any number of arguments,
19811932 and prints their values using the strings returned by <CODE>tostring</CODE>.
19821933 This function is not intended for formatted output,
19831934 but only as a quick way to show a value,
1984−for instance for error messages or debugging.
1935+for instance for debugging.
19851936 See Section&nbsp;<A HREF="#libio">6.4</A> for functions for formatted output.
19861937 <P>
1938+<A NAME="alert"></A>
1939+<h3> <TT>_ALERT (message)</TT></h3><A NAME="alert"></A>
1940+Prints its only string argument to <A NAME="stderr"><TT>stderr</TT></A>.
1941+All error messages in Lua are printed through this function.
1942+Therefore, a program may redefine it
1943+to change the way such messages are shown
1944+(for instance, for systems without <CODE>stderr</CODE>).
1945+<P>
19871946 <h3> <TT>tonumber (e [, base])</TT></h3><A NAME="tonumber"></A>
1988−This function receives one argument,
1947+Receives one argument,
19891948 and tries to convert it to a number.
19901949 If the argument is already a number or a string convertible
19911950 to a number, then <CODE>tonumber</CODE> returns that number;
@@ -2002,7 +1961,7 @@ In other bases, only integers are accepted. · 10 unmodified lines
20021961 <P>
20031962 <A NAME="pdf-type"></A>
20041963 <h3> <TT>type (v)</TT></h3><A NAME="type"></A>
2005−This function allows Lua to test the type of a value.
1964+Allows Lua to test the type of a value.
20061965 It receives one argument, and returns its type, coded as a string.
20071966 The possible results of this function are
20081967 <CODE>"nil"</CODE> (a string, not the value <B>nil</B>),
@@ -2013,12 +1972,12 @@ The possible results of this function are · 4 unmodified lines
20131972 and <CODE>"userdata"</CODE>.
20141973 <P>
20151974 <h3> <TT>tag (v)</TT></h3><A NAME="tag"></A>
2016−This function allows Lua to test the tag of a value (see Section&nbsp;<A HREF="#TypesSec">3</A>).
1975+Allows Lua to test the tag of a value (see Section&nbsp;<A HREF="#TypesSec">3</A>).
20171976 It receives one argument, and returns its tag (a number).
20181977 <CODE>tag</CODE> is equivalent to the API function <CODE>lua_tag</CODE>.
20191978 <P>
20201979 <h3> <TT>settag (t, tag)</TT></h3><A NAME="settag"></A>
2021−This function sets the tag of a given table (see Section&nbsp;<A HREF="#TypesSec">3</A>).
1980+Sets the tag of a given table (see Section&nbsp;<A HREF="#TypesSec">3</A>).
20221981 <CODE>tag</CODE> must be a value created with <CODE>newtag</CODE>
20231982 (see Section&nbsp;<A HREF="#pdf-newtag">6.1</A>).
20241983 It returns the value of its first argument (the table).
@@ -2027,21 +1986,21 @@ it is impossible to change the tag of a userdata from Lua. · 2 unmodified lines
20271986 <P>
20281987 <P>
20291988 <h3> <TT>assert (v [, message])</TT></h3><A NAME="assert"></A>
2030−This function issues an <EM>``assertion failed!''</EM> error
1989+Issues an <EM>``assertion failed!''</EM> error
20311990 when its argument is <B>nil</B>.
20321991 This function is equivalent to the following Lua function:
20331992 <PRE>
2034−function assert (v, m)
2035− if not v then
2036− m = m or ""
2037− error("assertion failed! " .. m)
2038− end
2039−end
1993+ function assert (v, m)
1994+ if not v then
1995+ m = m or ""
1996+ error("assertion failed! " .. m)
1997+ end
1998+ end
20401999 </PRE>
20412000 <P>
20422001 <A NAME="pdf-error"></A>
20432002 <h3> <TT>error (message)</TT></h3><A NAME="error"></A>
2044−This function calls the error handler and then terminates
2003+Calls the error handler and then terminates
20452004 the last protected function called
20462005 (in&nbsp;C: <CODE>lua_dofile</CODE>, <CODE>lua_dostring</CODE>,
20472006 <CODE>lua_dobuffer</CODE>, or <CODE>lua_callfunction</CODE>;
@@ -2064,7 +2023,7 @@ without invoking any tag method. · 16 unmodified lines
20642023 and <CODE>value</CODE> is any Lua value.
20652024 <P>
20662025 <h3> <TT>rawsetglobal (name, value)</TT></h3><A NAME="rawsetglobal"></A>
2067−This function assigns the given value to a global variable.
2026+Assigns the given value to a global variable.
20682027 The string <CODE>name</CODE> does not need to be a
20692028 syntactically valid variable name.
20702029 Therefore,
@@ -2073,7 +2032,7 @@ this function can set global variables with strange names like · 2 unmodified lines
20732032 Function <CODE>rawsetglobal</CODE> returns the value of its second argument.
20742033 <P>
20752034 <h3> <TT>setglobal (name, value)</TT></h3><A NAME="setglobal"></A>
2076−This function assigns the given value to a global variable,
2035+Assigns the given value to a global variable,
20772036 or calls a tag method.
20782037 Its full semantics is explained in Section&nbsp;<A HREF="#tag-method">4.8</A>.
20792038 The string <CODE>name</CODE> does not need to be a
@@ -2081,42 +2040,197 @@ syntactically valid variable name. · 1 unmodified line
20812040 Function <CODE>setglobal</CODE> returns the value of its second argument.
20822041 <P>
20832042 <h3> <TT>rawgetglobal (name)</TT></h3><A NAME="rawgetglobal"></A>
2084−This function retrieves the value of a global variable.
2043+Retrieves the value of a global variable.
20852044 The string <CODE>name</CODE> does not need to be a
20862045 syntactically valid variable name.
20872046 <P>
20882047 <h3> <TT>getglobal (name)</TT></h3><A NAME="getglobal"></A>
2089−This function retrieves the value of a global variable,
2048+Retrieves the value of a global variable,
20902049 or calls a tag method.
20912050 Its full semantics is explained in Section&nbsp;<A HREF="#tag-method">4.8</A>.
20922051 The string <CODE>name</CODE> does not need to be a
20932052 syntactically valid variable name.
20942053 <P>
2095−<h3> <TT>seterrormethod (newmethod)</TT></h3>
2096−<A NAME="pdf-seterrormethod"></A>
2097−
2098−Sets the error handler (see Section&nbsp;<A HREF="#error">4.9</A>).
2099−<CODE>newmethod</CODE> must be a function or <B>nil</B>,
2100−in which case the error handler does nothing.
2101−Returns the old error handler.
2102−<P>
21032054 <h3> <TT>settagmethod (tag, event, newmethod)</TT></h3>
21042055 <A NAME="settagmethod"></A>
2105−This function sets a new tag method to the given pair <EM>(tag, event)</EM>.
2056+Sets a new tag method to the given pair <EM>(tag, event)</EM>.
21062057 It returns the old method.
21072058 If <CODE>newmethod</CODE> is <B>nil</B>,
21082059 <CODE>settagmethod</CODE> restores the default behavior for the given event.
21092060 <P>
21102061 <h3> <TT>gettagmethod (tag, event)</TT></h3>
21112062 <A NAME="gettagmethod"></A>
2112−This function returns the current tag method
2063+Returns the current tag method
21132064 for a given pair <EM>(tag, event)</EM>.
21142065 <P>
21152066 <h3> <TT>copytagmethods (tagto, tagfrom)</TT></h3>
21162067 <A NAME="copytagmethods"></A>
2117−This function copies all tag methods from one tag to another;
2068+Copies all tag methods from one tag to another;
21182069 it returns <CODE>tagto</CODE>.
21192070 <P>
2071+<A NAME="getn"></A>
2072+<h3> <TT>getn (table)</TT></h3><A NAME="getn"></A>
2073+Returns the ``size'' of a table, when seen as a list.
2074+If the table has an <CODE>n</CODE> field with a numeric value,
2075+this is its ``size''.
2076+Otherwise, the size is the largest numerical index with a non-nil
2077+value in the table.
2078+This function could be defined in Lua:
2079+<PRE>
2080+ function getn (t)
2081+ if type(t.n) == 'number' then return t.n end
2082+ local max = 0
2083+ local i = next(t, nil)
2084+ while i do
2085+ if type(i) == 'number' and i&gt;max then max=i end
2086+ i = next(t, i)
2087+ end
2088+ return max
2089+ end
2090+</PRE>
2091+<P>
2092+<P>
2093+<h3> <TT>foreach (table, function)</TT></h3><A NAME="foreach"></A>
2094+Executes the given <CODE>function</CODE> over all elements of <CODE>table</CODE>.
2095+For each element, the function is called with the index and
2096+respective value as arguments.
2097+If the function returns any non-<B>nil</B> value,
2098+the loop is broken, and the value is returned
2099+as the final value of <CODE>foreach</CODE>.
2100+<P>
2101+This function could be defined in Lua:
2102+<PRE>
2103+ function foreach (t, f)
2104+ local i, v = next(t, nil)
2105+ while i do
2106+ local res = f(i, v)
2107+ if res then return res end
2108+ i, v = next(t, i)
2109+ end
2110+ end
2111+</PRE>
2112+<P>
2113+<P>
2114+<h3> <TT>foreachi (table, function)</TT></h3><A NAME="foreachi"></A>
2115+Executes the given <CODE>function</CODE> over the
2116+numerical indices of <CODE>table</CODE>.
2117+For each index, the function is called with the index and
2118+respective value as arguments.
2119+Indices are visited in sequential order,
2120+from 1 to <CODE>n</CODE>,
2121+where <CODE>n</CODE> is the result of <CODE>getn(table)</CODE> (see Section&nbsp;<A HREF="#getn">6.1</A>).
2122+If the function returns any non-<B>nil</B> value,
2123+the loop is broken, and the value is returned
2124+as the final value of <CODE>foreachi</CODE>.
2125+<P>
2126+This function could be defined in Lua:
2127+<PRE>
2128+ function foreachi (t, f)
2129+ local i, n = 1, getn(t)
2130+ while i &lt;= n do
2131+ local res = f(i, t[i])
2132+ if res then return res end
2133+ i = i+1
2134+ end
2135+ end
2136+</PRE>
2137+<P>
2138+<h3> <TT>foreachvar (function)</TT></h3><A NAME="foreachvar"></A>
2139+Executes <CODE>function</CODE> over all global variables.
2140+For each variable,
2141+the function is called with its name and its value as arguments.
2142+If the function returns any non-nil value,
2143+the loop is broken, and the value is returned
2144+as the final value of <CODE>foreachvar</CODE>.
2145+<P>
2146+This function could be defined in Lua:
2147+<PRE>
2148+ function foreachvar (f)
2149+ local n, v = nextvar(nil)
2150+ while n do
2151+ local res = f(n, v)
2152+ if res then return res end
2153+ n, v = nextvar(n)
2154+ end
2155+ end
2156+</PRE>
2157+<P>
2158+<h3> <TT>tinsert (table [, pos] , value)</TT></h3><A NAME="tinsert"></A>
2159+<P>
2160+Inserts element <CODE>value</CODE> at table position <CODE>pos</CODE>,
2161+shifting other elements to open space.
2162+The default value for <CODE>pos</CODE> is <CODE>n+1</CODE>
2163+(where <CODE>n</CODE> is the result of <CODE>getn(table)</CODE> (see Section&nbsp;<A HREF="#getn">6.1</A>))
2164+so that a call <CODE>tinsert(t,x)</CODE> inserts <CODE>x</CODE> at the end
2165+of table <CODE>t</CODE>.
2166+<P>
2167+This function also sets or increments the field <CODE>n</CODE> of the table,
2168+to <CODE>n+1</CODE>.
2169+<P>
2170+This function is equivalent to the following Lua function,
2171+except that the table accesses are all raw (that is, without tag methods):
2172+<PRE>
2173+ function tinsert (t, ...)
2174+ local pos, value
2175+ local n = getn(t)
2176+ if arg.n == 1 then
2177+ pos = n+1; value = arg[1]
2178+ else
2179+ pos = arg[1]; value = arg[2]
2180+ end
2181+ t.n = n+1;
2182+ while n &gt;= pos do
2183+ t[n+1] = t[n]
2184+ n = n-1
2185+ end
2186+ t[pos] = value
2187+ end
2188+</PRE>
2189+<P>
2190+<h3> <TT>tremove (table [, pos])</TT></h3><A NAME="tremove"></A>
2191+<P>
2192+Removes from <CODE>table</CODE> the element at position <CODE>pos</CODE>,
2193+shifting other elements to close the space.
2194+Returns the value of the removed element.
2195+The default value for <CODE>pos</CODE> is <CODE>n</CODE>
2196+(where <CODE>n</CODE> is the result of <CODE>getn(table)</CODE> (see Section&nbsp;<A HREF="#getn">6.1</A>)),
2197+so that a call <CODE>tremove(t)</CODE> removes the last element
2198+of table <CODE>t</CODE>.
2199+<P>
2200+This function also sets or decrements the field <CODE>n</CODE> of the table,
2201+to <CODE>n-1</CODE>.
2202+<P>
2203+This function is equivalent to the following Lua function,
2204+except that the table accesses are all raw (that is, without tag methods):
2205+<PRE>
2206+ function tremove (t, pos)
2207+ local n = getn(t)
2208+ pos = pos or n
2209+ local value = t[pos]
2210+ if n&lt;=0 then return end
2211+ while pos &lt; n do
2212+ t[pos] = t[pos+1]
2213+ pos = pos+1
2214+ end
2215+ t[n] = nil
2216+ t.n = n-1
2217+ return value
2218+ end
2219+</PRE>
2220+<P>
2221+<h3> <TT>sort (table [, comp])</TT></h3><A NAME="sort"></A>
2222+Sorts table elements in a given order, <EM>in-place</EM>,
2223+from <CODE>table[1]</CODE> to <CODE>table[n]</CODE>,
2224+where <CODE>n</CODE> is the result of <CODE>getn(table)</CODE> (see Section&nbsp;<A HREF="#getn">6.1</A>).
2225+If <CODE>comp</CODE> is given,
2226+it must be a function that receives two table elements,
2227+and returns true when the first is less than the second
2228+(so that <CODE>not comp(a[i+1], a[i])</CODE> will be true after the sort).
2229+If <CODE>comp</CODE> is not given,
2230+the standard <CODE>&lt;</CODE> Lua operator is used instead.
2231+<P>
2232+Function <CODE>sort</CODE> returns the (sorted) table.
2233+<P>
21202234 <P>
21212235 <A NAME="6.2"></A>
21222236 <H2>6.2 - String Manipulation</H2>
@@ -2127,7 +2241,7 @@ When indexing a string, the first character is at position&nbsp;1 · 4 unmodified lines
21272241 <P>
21282242 <h3> <TT>strfind (str, pattern [, init [, plain]])</TT></h3>
21292243 <A NAME="strfind"></A>
2130−This function looks for the first <EM>match</EM> of
2244+Looks for the first <EM>match</EM> of
21312245 <CODE>pattern</CODE> in <CODE>str</CODE>.
21322246 If it finds one, then it returns the indices on <CODE>str</CODE>
21332247 where this occurrence starts and ends;
@@ -2203,7 +2317,7 @@ Note that numerical codes are not necessarily portable across platforms. · 69 unmodified lines
22032317 <h3> <TT>format (formatstring, e1, e2, ...)</TT></h3><A NAME="format"></A>
22042318 <A NAME="format"></A>
22052319
2206−This function returns a formatted version of its variable number of arguments
2320+Returns a formatted version of its variable number of arguments
22072321 following the description given in its first argument (which must be a string).
22082322 The format string follows the same rules as the <CODE>printf</CODE> family of
22092323 standard C functions.
@@ -2212,9 +2326,8 @@ The only differences are that the options/modifiers · 2 unmodified lines
22122326 and <CODE>h</CODE> are not supported,
22132327 and there is an extra option, <CODE>q</CODE>.
22142328 This option formats a string in a form suitable to be safely read
2215−back by the Lua interpreter;
2216−that is,
2217−the string is written between double quotes,
2329+back by the Lua interpreter:
2330+The string is written between double quotes,
22182331 and all double quotes, returns and backslashes in the string
22192332 are correctly escaped when written.
22202333 For instance, the call
@@ -2241,7 +2354,7 @@ The options <CODE>c</CODE>, <CODE>d</CODE>, <CODE>E</CODE>, <CODE>e</CODE>, <COD · 20 unmodified lines
22412354 <CODE>g</CODE>, <CODE>G</CODE>, <CODE>i</CODE>, <CODE>o</CODE>, <CODE>u</CODE>, <CODE>X</CODE>, and <CODE>x</CODE> all
22422355 expect a number as argument,
22432356 whereas <CODE>q</CODE> and <CODE>s</CODE> expect a string.
2244−Note that the <CODE>*</CODE> modifier can be simulated by building
2357+The <CODE>*</CODE> modifier can be simulated by building
22452358 the appropriate format string.
22462359 For example, <CODE>"%*g"</CODE> can be simulated with
22472360 <CODE>"%"..width.."g"</CODE>.
@@ -2273,30 +2386,29 @@ the maximum number of substitutions to occur. · 25 unmodified lines
22732386 For instance, when <CODE>n</CODE> is 1 only the first occurrence of
22742387 <CODE>pat</CODE> is replaced.
22752388 <P>
2276−See some examples below:
2389+Here are some examples:
22772390 <PRE>
2278− x = gsub("hello world", "(%w%w*)", "%1 %1")
2391+ x = gsub("hello world", "(%w+)", "%1 %1")
22792392 --&gt; x="hello hello world world"
22802393 <P>
2281− x = gsub("hello world", "(%w%w*)", "%1 %1", 1)
2394+ x = gsub("hello world", "(%w+)", "%1 %1", 1)
22822395 --&gt; x="hello hello world"
22832396 <P>
2284− x = gsub("hello world from Lua", "(%w%w*)%s*(%w%w*)", "%2 %1")
2397+ x = gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
22852398 --&gt; x="world hello Lua from"
22862399 <P>
2287− x = gsub("home = $HOME, user = $USER", "$(%w%w*)", getenv)
2400+ x = gsub("home = $HOME, user = $USER", "%$(%w+)", getenv)
22882401 --&gt; x="home = /home/roberto, user = roberto" (for instance)
22892402 <P>
2290− x = gsub("4+5 = $return 4+5$", "$(.-)%$", dostring)
2403+ x = gsub("4+5 = $return 4+5$", "%$(.-)%$", dostring)
22912404 --&gt; x="4+5 = 9"
22922405 <P>
2293− local t = {name="lua", version="3.1"}
2294− x = gsub("$name - $version", "$(%w%w*)", function (v) return %t[v] end)
2295− --&gt; x="lua - 3.1"
2406+ local t = {name="lua", version="3.2"}
2407+ x = gsub("$name - $version", "%$(%w+)", function (v) return %t[v] end)
2408+ --&gt; x="lua - 3.2"
22962409 <P>
22972410 t = {n=0}
2298− gsub("first second word", "(%w%w*)",
2299− function (w) %t.n = %t.n+1; %t[%t.n] = w end)
2411+ gsub("first second word", "(%w+)", function (w) tinsert(%t, w) end)
23002412 --&gt; t={"first", "second", "word"; n=3}
23012413 </PRE>
23022414 <P>
@@ -2308,24 +2420,25 @@ See some examples below: · 5 unmodified lines
23082420 a <A NAME="character class"><EM>character class</EM></A> is used to represent a set of characters.
23092421 The following combinations are allowed in describing a character class:
23102422 <DL>
2311−<DT><B><EM>x</EM></B><DD> (where <EM>x</EM> is any character not in the list <CODE>()%.[*-?</CODE>)
2423+<DT><B><EM>x</EM></B><DD> (where <EM>x</EM> is any character not in the list
2424+<CODE>^$()%.[]*+-?</CODE>)
23122425 - represents the character <EM>x</EM> itself.
23132426 <DT><B><TT>.</TT></B><DD> - (a dot) represents all characters.
23142427 <DT><B><TT>%a</TT></B><DD> - represents all letters.
2315−<DT><B><TT>%A</TT></B><DD> - represents all non letter characters.
2428+<DT><B><TT>%c</TT></B><DD> - represents all control characters.
23162429 <DT><B><TT>%d</TT></B><DD> - represents all digits.
2317−<DT><B><TT>%D</TT></B><DD> - represents all non digits.
23182430 <DT><B><TT>%l</TT></B><DD> - represents all lower case letters.
2319−<DT><B><TT>%L</TT></B><DD> - represents all non lower case letter characters.
2431+<DT><B><TT>%p</TT></B><DD> - represents all punctuation characters.
23202432 <DT><B><TT>%s</TT></B><DD> - represents all space characters.
2321−<DT><B><TT>%S</TT></B><DD> - represents all non space characters.
23222433 <DT><B><TT>%u</TT></B><DD> - represents all upper case letters.
2323−<DT><B><TT>%U</TT></B><DD> - represents all non upper case letter characters.
23242434 <DT><B><TT>%w</TT></B><DD> - represents all alphanumeric characters.
2325−<DT><B><TT>%W</TT></B><DD> - represents all non alphanumeric characters.
2326−<DT><B><TT>%</TT><EM>x</EM></B><DD> (where <EM>x</EM> is any non alphanumeric character) -
2435+<DT><B><TT>%x</TT></B><DD> - represents all hexa-decimal digits.
2436+<DT><B><TT>%z</TT></B><DD> - represents the character with representation 0.
2437+<DT><B><TT>%<EM>x</TT></EM></B><DD> (where <EM>x</EM> is any non alphanumeric character) -
23272438 represents the character <EM>x</EM>.
2328−This is the standard way to escape the magic characters <CODE>()%.[*-?</CODE>.
2439+This is the standard way to escape the magic characters <CODE>()%.[]*-?</CODE>.
2440+It is strongly recommended that any control character (even the non magic),
2441+when used to represent itself in a pattern, should be preceded by a <CODE>%</CODE>.
23292442 <DT><B><TT>[char-set</TT></B>]<DD> -
23302443 Represents the class which is the union of all
23312444 characters in char-set.
@@ -2343,13 +2456,16 @@ E.g., assuming an <EM>ascii</EM> character set, · 11 unmodified lines
23432456 represents the complement of char-set,
23442457 where char-set is interpreted as above.
23452458 </DL>
2459+For all classes represented by single letters (<CODE>%a</CODE>, <CODE>%c</CODE>, ...),
2460+the correspondent upper-case letter represents the complement of the class.
2461+For instance, <CODE>%S</CODE> represents all non-space characters.
23462462 <P>
23472463 The definitions of letter, space, etc. depend on the current locale.
23482464 In particular, the class <CODE>[a-z]</CODE> may not be equivalent to <CODE>%l</CODE>.
23492465 The second form should be preferred for more portable programs.
23502466 <P>
23512467 <H4>Pattern Item:</H4>
2352−a <A NAME="pattern item"><EM>pattern item</EM></A> may be:
2468+a <A NAME="pattern item"><EM>pattern item</EM></A> may be
23532469 <UL>
23542470 <LI>
23552471 a single character class,
@@ -2357,12 +2473,16 @@ which matches any single character in the class; · 1 unmodified line
23572473 <LI>
23582474 a single character class followed by <CODE>*</CODE>,
23592475 which matches 0 or more repetitions of characters in the class.
2360−These repetition items will always match the longest possible sequence.
2476+These repetition items will always match the longest possible sequence;
2477+<LI>
2478+a single character class followed by <CODE>+</CODE>,
2479+which matches 1 or more repetitions of characters in the class.
2480+These repetition items will always match the longest possible sequence;
23612481 <LI>
23622482 a single character class followed by <CODE>-</CODE>,
23632483 which also matches 0 or more repetitions of characters in the class.
23642484 Unlike <CODE>*</CODE>,
2365−these repetition items will always match the shortest possible sequence.
2485+these repetition items will always match the shortest possible sequence;
23662486 <LI>
23672487 a single character class followed by <CODE>?</CODE>,
23682488 which matches 0 or 1 occurrence of a character in the class;
@@ -2441,14 +2561,16 @@ The function <CODE>random</CODE>, when called without arguments, · 72 unmodified lines
24412561 returns a pseudo-random real number in the range <I>[0,1)</I>.
24422562 When called with a number <I>n</I>,
24432563 <CODE>random</CODE> returns a pseudo-random integer in the range <I>[1,n]</I>.
2564+When called with two arguments, <I>l</I> and <I>u</I>,
2565+<CODE>random</CODE> returns a pseudo-random integer in the range <I>[l,u]</I>.
24442566 <P>
24452567 <P>
24462568 <A NAME="libio"></A>
24472569 <A NAME="6.4"></A>
24482570 <H2>6.4 - I/O Facilities</H2>
24492571 <P>
2450−All input and output operations in Lua are done over two
2451−<A NAME="file handles"><EM>file handles</EM></A>, one for reading and one for writing.
2572+All input and output operations in Lua are done, by default,
2573+over two <A NAME="file handles"><EM>file handles</EM></A>, one for reading and one for writing.
24522574 These handles are stored in two Lua global variables,
24532575 called <CODE>_INPUT</CODE> and <CODE>_OUTPUT</CODE>.
24542576 The global variables
@@ -2461,12 +2583,39 @@ Initially, <CODE>_INPUT=_STDIN</CODE> and <CODE>_OUTPUT=_STDOUT</CODE>. · 6 unmodified lines
24612583 <P>
24622584 A file handle is a userdata containing the file stream <CODE>FILE*</CODE>,
24632585 and with a distinctive tag created by the I/O library.
2464−<P>
2586+Whenever a file handle is collected by the garbage collector,
2587+its correspondent stream is automatically closed.
24652588 <P>
24662589 Unless otherwise stated,
24672590 all I/O functions return <B>nil</B> on failure and
24682591 some value different from <B>nil</B> on success.
24692592 <P>
2593+<h3> <TT>openfile (filename, mode)</TT></h3><A NAME="openfile"></A>
2594+<P>
2595+This function opens a file,
2596+in the mode specified in the string <CODE>mode</CODE>.
2597+It returns a new file handle,
2598+or, in case of errors, <B>nil</B> plus a string describing the error.
2599+This function does not modify either <CODE>_INPUT</CODE> or <CODE>_OUTPUT</CODE>.
2600+<P>
2601+The string mode can be any of the following:
2602+<DL>
2603+<DT><B>"r"</B><DD> read mode;
2604+<DT><B>"w"</B><DD> write mode;
2605+<DT><B>"a"</B><DD> append mode;
2606+<DT><B>"r+"</B><DD> update mode, all previous data is preserved;
2607+<DT><B>"w+"</B><DD> update mode, all previous data is erased;
2608+<DT><B>"a+"</B><DD> append update mode, previous data is preserved,
2609+ writing is only allowed at the end of file.
2610+</DL>
2611+The string mode may also have a <CODE>b</CODE> at the end,
2612+which is needed in some systems to open the file in binary mode.
2613+<P>
2614+<h3> <TT>closefile (handle)</TT></h3><A NAME="closefile"></A>
2615+<P>
2616+This function closes the given file.
2617+It does not modify either <CODE>_INPUT</CODE> or <CODE>_OUTPUT</CODE>.
2618+<P>
24702619 <h3> <TT>readfrom (filename)</TT></h3><A NAME="readfrom"></A>
24712620 <P>
24722621 This function may be called in two ways.
@@ -2519,52 +2668,81 @@ usually limited and depends on the system. · 46 unmodified lines
25192668 <P>
25202669 <h3> <TT>appendto (filename)</TT></h3><A NAME="appendto"></A>
25212670 <P>
2522−This function opens a file named <CODE>filename</CODE> and sets it as the
2671+Opens a file named <CODE>filename</CODE> and sets it as the
25232672 value of <CODE>_OUTPUT</CODE>.
25242673 Unlike the <CODE>writeto</CODE> operation,
25252674 this function does not erase any previous content of the file.
25262675 If this function fails, it returns <B>nil</B>,
25272676 plus a string describing the error.
25282677 <P>
2529−Note that function <CODE>writeto</CODE> is
2530−available to close an output file opened by <CODE>appendto</CODE>.
2531−<P>
25322678 <h3> <TT>remove (filename)</TT></h3><A NAME="remove"></A>
25332679 <P>
2534−This function deletes the file with the given name.
2680+Deletes the file with the given name.
25352681 If this function fails, it returns <B>nil</B>,
25362682 plus a string describing the error.
25372683 <P>
25382684 <h3> <TT>rename (name1, name2)</TT></h3><A NAME="rename"></A>
25392685 <P>
2540−This function renames file named <CODE>name1</CODE> to <CODE>name2</CODE>.
2686+Renames file named <CODE>name1</CODE> to <CODE>name2</CODE>.
2687+If this function fails, it returns <B>nil</B>,
2688+plus a string describing the error.
2689+<P>
2690+<h3> <TT>flush ([filehandle])</TT></h3><A NAME="flush"></A>
2691+<P>
2692+Saves any written data to the given file.
2693+If <CODE>filehandle</CODE> is not specified,
2694+flushes all open files.
25412695 If this function fails, it returns <B>nil</B>,
25422696 plus a string describing the error.
25432697 <P>
2698+<h3> <TT>seek (filehandle [, whence] [, offset])</TT></h3><A NAME="seek"></A>
2699+<P>
2700+Sets and gets the file position,
2701+measured in bytes from the beginning of the file,
2702+to the position given by <CODE>offset</CODE> plus a base
2703+specified by the string <CODE>whence</CODE>, as follows:
2704+<DL>
2705+<DT><B>"set"</B><DD> base is position 0 (beginning of the file);
2706+<DT><B>"cur"</B><DD> base is current position;
2707+<DT><B>"end"</B><DD> base is end of file;
2708+</DL>
2709+In case of success, function <CODE>seek</CODE> returns the final file position,
2710+measured in bytes from the beginning of the file.
2711+If the call fails, it returns <B>nil</B>,
2712+plus a string describing the error.
2713+<P>
2714+The default value for <CODE>whence</CODE> is <CODE>"cur"</CODE>,
2715+and for <CODE>offset</CODE> is 0.
2716+Therefore, the call <CODE>seek(file)</CODE> returns the current
2717+file position, without changing it;
2718+the call <CODE>seek(file, "set")</CODE> sets the position to the
2719+beginning of the file (and returns 0);
2720+and the call <CODE>seek(file, "end")</CODE> sets the position to the
2721+end of the file, and returns its size.
2722+<P>
25442723 <h3> <TT>tmpname ()</TT></h3><A NAME="tmpname"></A>
25452724 <P>
2546−This function returns a string with a file name that can safely
2725+Returns a string with a file name that can safely
25472726 be used for a temporary file.
25482727 The file must be explicitly removed when no longer needed.
25492728 <P>
2550−<h3> <TT>read ([filehandle] [readpattern])</TT></h3><A NAME="read"></A>
2729+<h3> <TT>read ([filehandle,] readpattern1, ...)</TT></h3><A NAME="read"></A>
25512730 <P>
2552−This function reads the file <CODE>_INPUT</CODE>,
2553−or from <CODE>filehandle</CODE> if this argument is given,
2554−according to a read pattern, which specifies how much to read;
2555−characters are read from the input file until
2556−the read pattern fails or ends.
2557−The function <CODE>read</CODE> returns a string with the characters read,
2731+Reads file <CODE>_INPUT</CODE>,
2732+or <CODE>filehandle</CODE> if this argument is given,
2733+according to read patterns, which specify how much to read.
2734+For each pattern,
2735+the function returns a string with the characters read,
25582736 even if the pattern succeeds only partially,
25592737 or <B>nil</B> if the read pattern fails <EM>and</EM>
25602738 the result string would be empty.
2561−When called without parameters,
2739+When called without patterns,
25622740 it uses a default pattern that reads the next line
25632741 (see below).
25642742 <P>
25652743 A <A NAME="read pattern"><EM>read pattern</EM></A> is a sequence of read pattern items.
25662744 An item may be a single character class
2567−or a character class followed by <CODE>?</CODE> or by <CODE>*</CODE>.
2745+or a character class followed by <CODE>?</CODE>, by <CODE>*</CODE>, or by <CODE>+</CODE>.
25682746 A single character class reads the next character from the input
25692747 if it belongs to the class, otherwise it fails.
25702748 A character class followed by <CODE>?</CODE> reads the next character
@@ -2573,6 +2751,9 @@ it never fails. · 2 unmodified lines
25732751 A character class followed by <CODE>*</CODE> reads until a character that
25742752 does not belong to the class, or end of file;
25752753 since it can match a sequence of zero characters, it never fails.
2754+A character class followed by <CODE>+</CODE> reads until a character that
2755+does not belong to the class, or end of file;
2756+it fails if it cannot read at least one character.
25762757 Note that the behavior of read patterns is slightly different from
25772758 the regular pattern matching behavior,
25782759 where a <CODE>*</CODE> expands to the maximum length <EM>such that</EM>
@@ -2585,26 +2766,27 @@ that describe <A NAME="skips"><EM>skips</EM></A>. · 6 unmodified lines
25852766 Characters matching a skip are read,
25862767 but are not included in the resulting string.
25872768 <P>
2588−Following are some examples of read patterns and their meanings:
2589−<UL>
2590−<LI><CODE>"."</CODE> returns the next character, or <B>nil</B> on end of file.
2591−<LI><CODE>".*"</CODE> reads the whole file.
2592−<LI><CODE>"[^\n]*{\n}"</CODE> returns the next line
2769+There are some predefined patterns, as follows:
2770+<DL>
2771+<DT><B>``*n''</B><DD> reads a number;
2772+this is the only pattern that returns a number instead of a string.
2773+<DT><B>``*l''</B><DD> returns the next line
25932774 (skipping the end of line), or <B>nil</B> on end of file.
25942775 This is the default pattern.
2595−<LI><CODE>"{%s*}%S%S*"</CODE> returns the next word
2776+It is equivalent to the pattern <CODE>"[^\n]*{\n}"</CODE>.
2777+<DT><B>``*a''</B><DD> reads the whole file.
2778+It is equivalent to the pattern <CODE>".*"</CODE>.
2779+<DT><B>``*w''</B><DD> returns the next word
25962780 (maximal sequence of non white-space characters),
2597−skipping spaces if necessary,
2598−or <B>nil</B> on end of file.
2599−<LI><CODE>"{%s*}[+-]?%d%d*"</CODE> returns the next integer
2600−or <B>nil</B> if the next characters do not conform to an integer format.
2601−</UL>
2781+skipping spaces if necessary, or <B>nil</B> on end of file.
2782+It is equivalent to the pattern <CODE>"{%s*}%S+"</CODE>.
2783+</DL>
26022784 <P>
26032785 <h3> <TT>write ([filehandle, ] value1, ...)</TT></h3><A NAME="write"></A>
26042786 <P>
2605−This function writes the value of each of its arguments to the
2787+Writes the value of each of its arguments to
26062788 file <CODE>_OUTPUT</CODE>,
2607−or to <CODE>filehandle</CODE> if this argument is given,
2789+or to <CODE>filehandle</CODE> if this argument is given.
26082790 The arguments must be strings or numbers.
26092791 To write other values,
26102792 use <CODE>tostring</CODE> or <CODE>format</CODE> before <CODE>write</CODE>.
@@ -2613,21 +2795,21 @@ plus a string describing the error. · 2 unmodified lines
26132795 <P>
26142796 <h3> <TT>date ([format])</TT></h3><A NAME="date"></A>
26152797 <P>
2616−This function returns a string containing date and time
2798+Returns a string containing date and time
26172799 formatted according to the given string <CODE>format</CODE>,
26182800 following the same rules of the ANSI C function <CODE>strftime</CODE>.
26192801 When called without arguments,
26202802 it returns a reasonable date and time representation that depends on
2621−the host system and the locale.
2803+the host system and on the locale.
26222804 <P>
26232805 <h3> <TT>clock ()</TT></h3><A NAME="clock"></A>
26242806 <P>
2625−This function returns an approximation of the amount of CPU time
2807+Returns an approximation of the amount of CPU time
26262808 used by the program, in seconds.
26272809 <P>
26282810 <h3> <TT>exit ([code])</TT></h3><A NAME="exit"></A>
26292811 <P>
2630−This function calls the C function <CODE>exit</CODE>,
2812+Calls the C function <CODE>exit</CODE>,
26312813 with an optional <CODE>code</CODE>,
26322814 to terminate the program.
26332815 The default value for <CODE>code</CODE> is 1.
@@ -2694,12 +2876,16 @@ it accepts only a handle returned by · 60 unmodified lines
26942876 <P>
26952877 Three other functions produce extra information about a function:
26962878 <PRE>
2697−void lua_funcinfo (lua_Object func, char **filename, int *linedefined);
2879+void lua_funcinfo (lua_Object func, char **source, int *linedefined);
26982880 int lua_currentline (lua_Function func);
26992881 char *lua_getobjname (lua_Object o, char **name);
27002882 </PRE>
2701−<CODE>lua_funcinfo</CODE> gives the file name and the line where the
2702−given function has been defined.
2883+<CODE>lua_funcinfo</CODE> gives the source and the line where the
2884+given function has been defined:
2885+If the function was defined in a string,
2886+<CODE>source</CODE> is that string;
2887+If the function was defined in a file,
2888+<CODE>source</CODE> starts with a <CODE>@</CODE> followed by the file name.
27032889 If the ``function'' is in fact the main code of a chunk,
27042890 then <CODE>linedefined</CODE> is 0.
27052891 If the function is a C function,
@@ -2708,21 +2894,30 @@ then <CODE>linedefined</CODE> is <I>-1</I>, and <CODE>filename</CODE> is <CODE>" · 2 unmodified lines
27082894 The function <CODE>lua_currentline</CODE> gives the current line where
27092895 a given function is executing.
27102896 It only works if the function has been compiled with debug
2711−information (see Section&nbsp;<A HREF="#pragma">4.9</A>).
2897+information.
27122898 When no line information is available,
27132899 <CODE>lua_currentline</CODE> returns <I>-1</I>.
27142900 <P>
2901+The generation of debug information is controled by an internal flag,
2902+which can be switched with
2903+<PRE>
2904+int lua_setdebug (int debug);
2905+</PRE>
2906+This function sets the flag and returns its previous value.
2907+This flag can also be set from Lua&nbsp;(see Section&nbsp;<A HREF="#pragma">4.9</A>).
2908+<P>
27152909 Function <CODE>lua_getobjname</CODE> tries to find a reasonable name for
27162910 a given function.
27172911 Because functions in Lua are first class values,
27182912 they do not have a fixed name:
27192913 Some functions may be the value of many global variables,
27202914 while others may be stored only in a table field.
2721−Function <CODE>lua_getobjname</CODE> first checks whether the given
2722−function is a tag method.
2723−If so, it returns the string <CODE>"tag-method"</CODE>,
2915+Function <CODE>lua_getobjname</CODE> checks whether the given
2916+function is a tag method or the value of a global variable.
2917+If the given function is a tag method, then <CODE>lua_getobjname</CODE>
2918+returns the string <CODE>"tag-method"</CODE>,
27242919 and <CODE>name</CODE> is set to point to the event name.
2725−Otherwise, if the given function is the value of a global variable,
2920+If the given function is the value of a global variable,
27262921 then <CODE>lua_getobjname</CODE> returns the string <CODE>"global"</CODE>,
27272922 and <CODE>name</CODE> points to the variable name.
27282923 If the given function is neither a tag method nor a global variable,
@@ -2736,6 +2931,8 @@ The following functions allow the manipulation of the · 7 unmodified lines
27362931 local variables of a given activation record.
27372932 They only work if the function has been compiled with debug
27382933 information (see Section&nbsp;<A HREF="#pragma">4.9</A>).
2934+Moreover, for these functions, a local variable becomes
2935+visible in the line after its definition.
27392936 <PRE>
27402937 lua_Object lua_getlocal (lua_Function func, int local_number, char **name);
27412938 int lua_setlocal (lua_Function func, int local_number);
@@ -2766,17 +2963,17 @@ then this function fails and returns 0. · 24 unmodified lines
27662963 The Lua interpreter offers two hooks for debugging purposes:
27672964 <PRE>
27682965 typedef void (*lua_CHFunction) (lua_Function func, char *file, int line);
2769−extern lua_CHFunction lua_callhook;
2966+lua_CHFunction lua_setcallhook (lua_CHFunction func);
27702967 <P>
27712968 typedef void (*lua_LHFunction) (int line);
2772−extern lua_LHFunction lua_linehook;
2969+lua_LHFunction lua_setlinehook (lua_LHFunction func);
27732970 </PRE>
2774−The first one is called whenever the interpreter enters or leaves a
2971+The first hook is called whenever the interpreter enters or leaves a
27752972 function.
27762973 When entering a function,
27772974 its parameters are a handle to the function activation record,
2778−plus the file and the line where the function is defined (the same
2779−information which is provided by <CODE>lua_funcinfo</CODE>);
2975+plus the file and the line where the function is defined
2976+(the same information which is provided by <CODE>lua_funcinfo</CODE>);
27802977 when leaving a function, <CODE>func</CODE> is <CODE>LUA_NOOBJECT</CODE>,
27812978 <CODE>file</CODE> is <CODE>"(return)"</CODE>, and <CODE>line</CODE> is 0.
27822979 <P>
@@ -2785,12 +2982,131 @@ the line of code it is executing. · 2 unmodified lines
27852982 Its only parameter is the line number
27862983 (the same information which is provided by the call
27872984 <CODE>lua_currentline(lua_stackedfunction(0))</CODE>).
2788−This second hook is only called if the active function
2985+This second hook is called only if the active function
27892986 has been compiled with debug information (see Section&nbsp;<A HREF="#pragma">4.9</A>).
27902987 <P>
27912988 A hook is disabled when its value is <CODE>NULL</CODE>,
27922989 which is the initial value of both hooks.
2990+Both <CODE>lua_setcallhook</CODE> and <CODE>lua_setlinehook</CODE>
2991+set their corresponding hooks and return their previous values.
2992+<P>
2993+<P>
2994+<P>
2995+<A NAME="7.4"></A>
2996+<H2>7.4 - The Reflexive Debugger Interface</H2>
2997+<P>
2998+The library <CODE>ldblib</CODE> provides
2999+the functionallity of the debugger interface to Lua programs.
3000+If you want to use this library,
3001+your host application must open it,
3002+calling <CODE>lua_dblibopen</CODE>.
3003+<P>
3004+You should exert great care when using this library.
3005+The functions provided here should be used exclusively for debugging
3006+and similar tasks (e.g. profiling).
3007+Please resist the temptation to use them as a
3008+usual programming tool.
3009+They are slow and violate some (otherwise) secure aspects of the
3010+language (e.g. privacy of local variables).
3011+As a general rule, if your program does not need this library,
3012+do not open it.
3013+<P>
3014+<P>
3015+<h3> <TT>funcinfo (function)</TT></h3><A NAME="funcinfo"></A>
3016+<P>
3017+This function returns a table with information about the given function.
3018+The table contains the following fields:
3019+<DL>
3020+<DT><B>kind</B><DD>: may be <CODE>"C"</CODE>, if this is a C function,
3021+<CODE>"chunk"</CODE>, if this is the main part of a chunk,
3022+or <CODE>"Lua"</CODE> if this is a Lua function.
3023+<P>
3024+<DT><B>source</B><DD> the source where the function was defined.
3025+If the function was defined in a string,
3026+<CODE>source</CODE> is that string;
3027+If the function was defined in a file,
3028+<CODE>source</CODE> starts with a <CODE>@</CODE> followed by the file name.
3029+<P>
3030+<DT><B>def_line</B><DD> the line where the function was defined in the source
3031+(only valid if this is a Lua function).
3032+<P>
3033+<DT><B>where</B><DD> can be <CODE>"global"</CODE> if this function has a global name,
3034+or <CODE>"tag-method"</CODE> if this function is a tag method handler.
3035+<P>
3036+<DT><B>name</B><DD> if <CODE>where</CODE> = <CODE>global</CODE>,
3037+<CODE>name</CODE> is the global name of the function;
3038+if <CODE>where</CODE> = <CODE>tag-method</CODE>,
3039+<CODE>name</CODE> is the event name of the tag method.
3040+</DL>
3041+<P>
3042+<h3> <TT>getstack (index)</TT></h3><A NAME="getstack"></A>
3043+<P>
3044+This function returns a table with informations about the function
3045+running at level <CODE>index</CODE> of the stack.
3046+Index 0 is the current function (<CODE>getstack</CODE> itself).
3047+If <CODE>index</CODE> is bigger than the number of active functions,
3048+the function returns <B>nil</B>.
3049+The table contains all the fields returned by <CODE>funcinfo</CODE>,
3050+plus the following:
3051+<DL>
3052+<DT><B>func</B><DD> the function at that level.
3053+<DT><B>current</B><DD> the current line on the function execution;
3054+this will be available only when the function is
3055+precompiled with debug information.
3056+</DL>
27933057 <P>
3058+<h3> <TT>getlocal (index [, local])</TT></h3><A NAME="getlocal"></A>
3059+<P>
3060+This function returns information about the local variables of the
3061+function at level <CODE>index</CODE> of the stack.
3062+It can be called in three ways.
3063+When called without a <CODE>local</CODE> argument,
3064+it returns a table, which associates variable names to their values.
3065+When called with a name (a string) as <CODE>local</CODE>,
3066+it returns the value of the local variable with that name.
3067+Finally, when called with an index (a number),
3068+it returns the value and the name of the local variable
3069+with that index.
3070+(The first parameter has index 1, and so on,
3071+until the last active local variable.)
3072+In that case, the function returns <B>nil</B> if there is no local
3073+variable with the given index.
3074+The specification by index is the only way to distinguish
3075+homonym variables in a function.
3076+<P>
3077+<h3> <TT>setlocal (index, local, newvalue)</TT></h3><A NAME="setlocal"></A>
3078+<P>
3079+This function changes the values of the local variables of the
3080+function at level <CODE>index</CODE> of the stack.
3081+The local variable can be specified by name or by index;
3082+see function <CODE>getlocal</CODE>.
3083+<P>
3084+<h3> <TT>setcallhook (hook)</TT></h3><A NAME="setcallhook"></A>
3085+<P>
3086+Sets the function <CODE>hook</CODE> as the call hook;
3087+this hook will be called every time the interpreter starts and
3088+exits the execution of a function.
3089+When Lua enters a function,
3090+the hook is called with the function been called,
3091+plus the source and the line where the function is defined.
3092+When Lua exits a function,
3093+the hook is called with no arguments.
3094+<P>
3095+When called without arguments,
3096+this function turns off call hooks.
3097+<P>
3098+<h3> <TT>setlinehook (hook)</TT></h3><A NAME="setlinehook"></A>
3099+<P>
3100+Sets the function <CODE>hook</CODE> as the line hook;
3101+this hook will be called every time the interpreter changes
3102+the line of code it is executing.
3103+The only argument to the hook is the line number the interpreter
3104+is about to execut.
3105+This hook is called only if the active function
3106+has been compiled with debug information (see Section&nbsp;<A HREF="#pragma">4.9</A>).
3107+<P>
3108+When called without arguments,
3109+this function turns off line hooks.
27943110 <P>
27953111 <P>
27963112 <A NAME="lua-sa"></A>
@@ -2866,6 +3182,18 @@ the previous public versions of Lua, · 69 unmodified lines
28663182 some differences had to be introduced.
28673183 Here is a list of all these incompatibilities.
28683184 <P>
3185+<h2>Incompatibilities with <A NAME="version 3.1</h2>">version 3.1</h2></A>
3186+<UL>
3187+<LI>
3188+In the debug API, the old variables <CODE>lua_debug</CODE>,
3189+<CODE>lua_callhook</CODE> and <CODE>lua_linehook</CODE> now live inside <CODE>lua_state</CODE>.
3190+Therefore, they are no longer directly accessible, and must be
3191+manipulated only through the new functions <CODE>lua_setdebug</CODE>,
3192+<CODE>lua_setcallhook</CODE> and <CODE>lua_setlinehook</CODE>.
3193+<P>
3194+<LI>Old pre-compiled code is obsolete, and must be re-compiled.
3195+</UL>
3196+<P>
28693197 <h2>Incompatibilities with <A NAME="version 3.0</h2>">version 3.0</h2></A>
28703198 <UL>
28713199 <P>
@@ -2877,7 +3205,7 @@ so any existing program that opens at least one standard · 5 unmodified lines
28773205 library before calling Lua does not need to be modified.
28783206 <P>
28793207 <LI>Function <CODE>dostring</CODE> no longer accepts an optional second argument,
2880−with a temporary error method.
3208+with a temporary error handler.
28813209 This facility is now provided by function <CODE>call</CODE>.
28823210 <P>
28833211 <LI>Function <CODE>gsub</CODE> no longer accepts an optional fourth argument
@@ -2898,11 +3226,13 @@ programs should use an explicit assignment instead, such as · 14 unmodified lines
28983226 <P>
28993227 </UL>
29003228 <P>
2901−<P>
29023229
29033230 <HR>
3231+<SMALL>
29043232 Last update:
2905−Fri Jul 10 15:10:14 EST 1998
3233+Wed Jul 7 13:36:24 EST 1999
29063234 by <A HREF="http://www.tecgraf.puc-rio.br/~lhf/">lhf</A>.
3235+</SMALL>
3236+
29073237 </BODY>
29083238 </HTML>
doc/readme.html+31−0
@@ -0,0 +1,31 @@
1+<HTML>
2+<HEAD>
3+<TITLE>Lua documentation</TITLE>
4+</HEAD>
5+
6+<BODY BGCOLOR="#FFFFFF">
7+
8+<HR>
9+<H1><A HREF="http://www.tecgraf.puc-rio.br/lua/">Lua</A> documentation</H1>
10+
11+<UL>
12+<LI><A HREF="index.html">Reference manual</A>
13+<LI><A HREF="luac.html">luac man page</A>
14+<LI><A HREF="../README">README</A>
15+<LI><A HREF="../src/lib/README">src/lib/README</A>
16+<LI><A HREF="../src/lua/README">src/lua/README</A>
17+<LI><A HREF="../src/luac/README">src/luac/README</A>
18+<LI><A HREF="../etc/README">etc/README</A>
19+<LI><A HREF="../test/README">test/README</A>
20+<LI><A HREF="../test/examples/www/README">test/examples/www/README</A>
21+</UL>
22+
23+<HR>
24+<SMALL>
25+Last update:
26+Wed Jul 7 13:24:17 EST 1999
27+by <A HREF="http://www.tecgraf.puc-rio.br/~lhf/">lhf</A>.
28+</SMALL>
29+
30+</BODY>
31+</HTML>
etc/README+4−3
@@ -5,9 +5,9 @@ bin2c.c · 4 unmodified lines
55 run with lua_dobuffer.
66 This allows C programs to include all necessary Lua code, even in
77 precompiled form.
8− Even if code is include in source form, bin2c is useful because it
8+ Even if the code is included in source form, bin2c is useful because it
99 avoids the hassle of having to quote special characters in C strings.
10− Example of usage: run bin2c file1 file2 ... > init.h. The in your C
10+ Example of usage: Run bin2c file1 file2 ... > init.h. Then, in your C
1111 program, just do #include "init.h" anywhere in the *body* of a
1212 function. This will be equivalent to calling
1313 lua_dofile("file1"); lua_dofile("file2"); ...
@@ -17,7 +17,8 @@ min.c · 3 unmodified lines
1717
1818 setfallback.lua
1919 An implementation of fallbacks on top of tag methods.
20− Useful if you have Lua code written for version 2.5 or earlier.
20+ Useful if you have Lua code written for version 2.5 or earlier,
21+ which uses setfallback.
2122 If you have C code that uses lua_setfallback, then define LUA_COMPAT2_5
2223 before building Lua (see config).
2324
etc/bin2c.c+7−2
@@ -2,15 +2,16 @@ · 1 unmodified line
22 * bin2c.c
33 * convert binary files to byte arrays
44 * Luiz Henrique de Figueiredo (lhf@tecgraf.puc-rio.br)
5−* 25 Jun 98 10:55:12
5+* 24 Nov 98 12:15:27
66 */
77
88 #include <ctype.h>
99 #include <stdio.h>
10+#include <stdlib.h>
1011
1112 void dump(FILE* f, int n)
1213 {
13− printf("static unsigned char B%d[]={\n");
14+ printf("static unsigned char B%d[]={\n",n);
1415 for (n=1;;n++)
1516 {
1617 int c=getc(f);
@@ -49,6 +50,7 @@ void emit(char* fn, int n) · 32 unmodified lines
4950
5051 int main(int argc, char* argv[])
5152 {
53+ printf("/* code automatically generated by bin2c -- DO NOT EDIT */\n");
5254 printf("{\n");
5355 if (argc<2)
5456 {
@@ -58,6 +60,9 @@ int main(int argc, char* argv[]) · 3 unmodified lines
5860 else
5961 {
6062 int i;
63+ printf("/* #include'ing this file in a C program is equivalent to calling\n");
64+ for (i=1; i<argc; i++) printf(" lua_dofile(\"%s\");\n",argv[i]);
65+ printf("*/\n");
6166 for (i=1; i<argc; i++) fdump(argv[i],i);
6267 for (i=1; i<argc; i++) emit(argv[i],i);
6368 }
etc/trace.c+14−18
@@ -1,6 +1,6 @@
11 /*
22 * trace.c
3−* a simple execution tracer
3+* a simple execution tracer for Lua
44 */
55
66 #include <stdio.h>
@@ -8,45 +8,41 @@ · 1 unmodified line
88 #include "lua.h"
99 #include "luadebug.h"
1010
11−static FILE* P; /* output file */
11+static FILE* LOG; /* output file */
1212 static int L=0; /* indentation level */
1313
1414 static void linehook(int line)
1515 {
16− fprintf(P,"%*sLINE(%d)\t-- %d\n",L,"",line,L);
16+ fprintf(LOG,"%*sLINE(%d)\t-- %d\n",L,"",line,L);
1717 }
1818
1919 static void callhook(lua_Function func, char* file, int line)
2020 {
21− fprintf(P,"%*sCALL('%s',%d)\t-- %d\n",L,"",file,line,L);
21+ fprintf(LOG,"%*sCALL('%s',%d)\t-- %d\n",L,"",file,line,L);
2222 if (line==0 && strcmp(file,"(return)")==0) --L; else ++L;
2323 }
2424
25−void start_trace(void)
25+void start_trace(FILE* logfile)
2626 {
27− lua_linehook=linehook;
28− lua_callhook=callhook;
29− lua_debug=1;
30−#if 0
31− P=fopen("trace.out","w");
32−#else
33− P=stderr;
34−#endif
27+ lua_setlinehook(linehook);
28+ lua_setcallhook(callhook);
29+ lua_setdebug(1);
30+ LOG=logfile;
3531 }
3632
3733 void stop_trace(void)
3834 {
39− lua_linehook=NULL;
40− lua_callhook=NULL;
41− lua_debug=0;
42− fclose(P);
35+ lua_setlinehook(NULL);
36+ lua_setcallhook(NULL);
37+ lua_setdebug(0);
38+ fclose(LOG);
4339 }
4440
4541 int main(void)
4642 {
4743 int rc;
4844 lua_open();
49− start_trace();
45+ start_trace(stderr);
5046 rc=lua_dofile(0);
5147 stop_trace();
5248 return rc;
include/lauxlib.h+7−1
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lauxlib.h,v 1.9 1998/06/19 16:14:09 roberto Exp $
2+** $Id: lauxlib.h,v 1.12 1999/03/10 14:19:41 roberto Exp $
33 ** Auxiliary functions for building Lua libraries
44 ** See Copyright Notice in lua.h
55 */
@@ -28,7 +28,11 @@ char *luaL_check_lstr (int numArg, long *len); · 22 unmodified lines
2828 #define luaL_opt_string(n, d) (luaL_opt_lstr((n), (d), NULL))
2929 char *luaL_opt_lstr (int numArg, char *def, long *len);
3030 double luaL_check_number (int numArg);
31+#define luaL_check_int(n) ((int)luaL_check_number(n))
32+#define luaL_check_long(n) ((long)luaL_check_number(n))
3133 double luaL_opt_number (int numArg, double def);
34+#define luaL_opt_int(n,d) ((int)luaL_opt_number(n,d))
35+#define luaL_opt_long(n,d) ((long)luaL_opt_number(n,d))
3236 lua_Object luaL_functionarg (int arg);
3337 lua_Object luaL_tablearg (int arg);
3438 lua_Object luaL_nonnullarg (int numArg);
@@ -42,6 +46,8 @@ int luaL_newbuffer (int size); · 7 unmodified lines
4246 void luaL_oldbuffer (int old);
4347 char *luaL_buffer (void);
4448 int luaL_findstring (char *name, char *list[]);
49+void luaL_chunkid (char *out, char *source, int len);
50+void luaL_filesource (char *out, char *filename, int len);
4551
4652
4753 #endif
include/lua.h+13−16
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lua.h,v 1.23 1998/06/18 16:51:53 roberto Exp $
2+** $Id: lua.h,v 1.32 1999/05/11 20:29:19 roberto Exp $
33 ** Lua - An Extensible Extension Language
44 ** TeCGraf: Grupo de Tecnologia em Computacao Grafica, PUC-Rio, Brazil
55 ** e-mail: lua@tecgraf.puc-rio.br
@@ -11,8 +11,8 @@ · 5 unmodified lines
1111 #ifndef lua_h
1212 #define lua_h
1313
14−#define LUA_VERSION "Lua 3.1"
15−#define LUA_COPYRIGHT "Copyright (C) 1994-1998 TeCGraf, PUC-Rio"
14+#define LUA_VERSION "Lua 3.2"
15+#define LUA_COPYRIGHT "Copyright (C) 1994-1999 TeCGraf, PUC-Rio"
1616 #define LUA_AUTHORS "W. Celes, R. Ierusalimschy & L. H. de Figueiredo"
1717
1818
@@ -20,19 +20,18 @@ · 1 unmodified line
2020
2121 #define LUA_ANYTAG (-1)
2222
23−typedef void (*lua_CFunction) (void);
24−typedef unsigned int lua_Object;
25−
2623 typedef struct lua_State lua_State;
2724 extern lua_State *lua_state;
2825
26+typedef void (*lua_CFunction) (void);
27+typedef unsigned int lua_Object;
28+
2929 void lua_open (void);
3030 void lua_close (void);
3131 lua_State *lua_setstate (lua_State *st);
3232
3333 lua_Object lua_settagmethod (int tag, char *event); /* In: new method */
3434 lua_Object lua_gettagmethod (int tag, char *event);
35−lua_Object lua_seterrormethod (void); /* In: new method */
3635
3736 int lua_newtag (void);
3837 int lua_copytagmethods (int tagto, int tagfrom);
@@ -90,6 +89,9 @@ lua_Object lua_rawgettable (void); /* In: table, index */ · 51 unmodified lines
9089
9190 int lua_tag (lua_Object object);
9291
92+char *lua_nextvar (char *varname); /* Out: value */
93+int lua_next (lua_Object o, int i);
94+ /* Out: ref, value */
9395
9496 int lua_ref (int lock); /* In: value */
9597 lua_Object lua_getref (int ref);
@@ -101,29 +103,23 @@ long lua_collectgarbage (long limit); · 5 unmodified lines
101103
102104
103105 /* =============================================================== */
104−/* some useful macros/derived functions */
106+/* some useful macros/functions */
105107
106−int (lua_call) (char *name);
107108 #define lua_call(name) lua_callfunction(lua_getglobal(name))
108109
109−void (lua_pushref) (int ref);
110110 #define lua_pushref(ref) lua_pushobject(lua_getref(ref))
111111
112−int (lua_refobject) (lua_Object o, int l);
113112 #define lua_refobject(o,l) (lua_pushobject(o), lua_ref(l))
114113
115−void (lua_register) (char *n, lua_CFunction f);
116114 #define lua_register(n,f) (lua_pushcfunction(f), lua_setglobal(n))
117115
118−void (lua_pushuserdata) (void *u);
119116 #define lua_pushuserdata(u) lua_pushusertag(u, 0)
120117
121−void (lua_pushcfunction) (lua_CFunction f);
122118 #define lua_pushcfunction(f) lua_pushcclosure(f, 0)
123119
124−int (lua_clonetag) (int t);
125120 #define lua_clonetag(t) lua_copytagmethods(lua_newtag(), (t))
126121
122+lua_Object lua_seterrormethod (void); /* In: new method */
127123
128124 /* ==========================================================================
129125 ** for compatibility with old versions. Avoid using these macros/functions
@@ -162,7 +158,7 @@ lua_Object lua_setfallback (char *event, lua_CFunction fallback); · 32 unmodified lines
162158
163159
164160 /******************************************************************************
165−* Copyright (c) 1994-1998 TeCGraf, PUC-Rio. All rights reserved.
161+* Copyright (c) 1994-1999 TeCGraf, PUC-Rio. All rights reserved.
166162 *
167163 * Permission is hereby granted, without written agreement and without license
168164 * or royalty fees, to use, copy, modify, and distribute this software and its
@@ -192,5 +188,6 @@ lua_Object lua_setfallback (char *event, lua_CFunction fallback); · 23 unmodified lines
192188 * The Lua language and this implementation have been entirely designed and
193189 * written by Waldemar Celes Filho, Roberto Ierusalimschy and
194190 * Luiz Henrique de Figueiredo at TeCGraf, PUC-Rio.
191+*
195192 * This implementation contains no third-party code.
196193 ******************************************************************************/
include/luadebug.h+6−5
@@ -1,5 +1,5 @@
11 /*
2−** $Id: luadebug.h,v 1.2 1998/06/19 16:14:09 roberto Exp $
2+** $Id: luadebug.h,v 1.6 1999/03/04 21:17:26 roberto Exp $
33 ** Debugging API
44 ** See Copyright Notice in lua.h
55 */
@@ -17,17 +17,18 @@ typedef void (*lua_LHFunction) (int line); · 11 unmodified lines
1717 typedef void (*lua_CHFunction) (lua_Function func, char *file, int line);
1818
1919 lua_Function lua_stackedfunction (int level);
20−void lua_funcinfo (lua_Object func, char **filename, int *linedefined);
20+void lua_funcinfo (lua_Object func, char **source, int *linedefined);
2121 int lua_currentline (lua_Function func);
2222 char *lua_getobjname (lua_Object o, char **name);
2323
2424 lua_Object lua_getlocal (lua_Function func, int local_number, char **name);
2525 int lua_setlocal (lua_Function func, int local_number);
2626
27+int lua_nups (lua_Function func);
2728
28−extern lua_LHFunction lua_linehook;
29−extern lua_CHFunction lua_callhook;
30−extern int lua_debug;
29+lua_LHFunction lua_setlinehook (lua_LHFunction func);
30+lua_CHFunction lua_setcallhook (lua_CHFunction func);
31+int lua_setdebug (int debug);
3132
3233
3334 #endif
include/lualib.h+5−3
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lualib.h,v 1.4 1998/06/19 16:14:09 roberto Exp $
2+** $Id: lualib.h,v 1.6 1999/05/05 19:23:11 roberto Exp $
33 ** Lua standard libraries
44 ** See Copyright Notice in lua.h
55 */
@@ -10,12 +10,13 @@ · 4 unmodified lines
1010
1111 #include "lua.h"
1212
13−
1413 void lua_iolibopen (void);
1514 void lua_strlibopen (void);
1615 void lua_mathlibopen (void);
16+void lua_dblibopen (void);
1717
1818
19+void lua_userinit (void);
1920
2021
2122 /* To keep compatibility with old versions */
@@ -28,7 +29,8 @@ void lua_mathlibopen (void); · 6 unmodified lines
2829
2930 /* Auxiliary functions (private) */
3031
31−int luaI_singlematch (int c, char *p, char **ep);
32+char *luaI_classend (char *p);
33+int luaI_singlematch (int c, char *p, char *ep);
3234
3335 #endif
3436
src/lapi.c+165−103
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lapi.c,v 1.25 1998/06/05 22:17:44 roberto Exp $
2+** $Id: lapi.c,v 1.47 1999/06/22 20:37:23 roberto Exp $
33 ** Lua API
44 ** See Copyright Notice in lua.h
55 */
@@ -25,17 +25,16 @@ · 19 unmodified lines
2525
2626
2727 char lua_ident[] = "$Lua: " LUA_VERSION " " LUA_COPYRIGHT " $\n"
28− "$Autores: " LUA_AUTHORS " $";
28+ "$Authors: " LUA_AUTHORS " $";
2929
3030
3131
32−TObject *luaA_Address (lua_Object o)
33−{
34− return Address(o);
32+TObject *luaA_Address (lua_Object o) {
33+ return (o != LUA_NOOBJECT) ? Address(o) : NULL;
3534 }
3635
3736
38−static int normalized_type (TObject *o)
37+static lua_Type normalized_type (TObject *o)
3938 {
4039 int t = ttype(o);
4140 switch (t) {
@@ -71,12 +70,8 @@ void luaA_packresults (void) · 29 unmodified lines
7170 }
7271
7372
74−int luaA_passresults (void)
75−{
76− luaD_checkstack(L->Cstack.num);
77− memcpy(L->stack.top, L->Cstack.lua2C+L->stack.stack,
78− L->Cstack.num*sizeof(TObject));
79− L->stack.top += L->Cstack.num;
73+int luaA_passresults (void) {
74+ L->Cstack.base = L->Cstack.lua2C; /* position of first result */
8075 return L->Cstack.num;
8176 }
8277
@@ -88,24 +83,29 @@ static void checkCparams (int nParams) · 5 unmodified lines
8883 }
8984
9085
91−static lua_Object put_luaObject (TObject *o)
92−{
86+static lua_Object put_luaObject (TObject *o) {
9387 luaD_openstack((L->stack.top-L->stack.stack)-L->Cstack.base);
9488 L->stack.stack[L->Cstack.base++] = *o;
9589 return L->Cstack.base; /* this is +1 real position (see Ref) */
9690 }
9791
9892
99−static lua_Object put_luaObjectonTop (void)
100−{
93+static lua_Object put_luaObjectonTop (void) {
10194 luaD_openstack((L->stack.top-L->stack.stack)-L->Cstack.base);
10295 L->stack.stack[L->Cstack.base++] = *(--L->stack.top);
10396 return L->Cstack.base; /* this is +1 real position (see Ref) */
10497 }
10598
10699
107−lua_Object lua_pop (void)
108−{
100+static void top2LC (int n) {
101+ /* Put the 'n' elements on the top as the Lua2C contents */
102+ L->Cstack.base = (L->stack.top-L->stack.stack); /* new base */
103+ L->Cstack.lua2C = L->Cstack.base-n; /* position of the new results */
104+ L->Cstack.num = n; /* number of results */
105+}
106+
107+
108+lua_Object lua_pop (void) {
109109 checkCparams(1);
110110 return put_luaObjectonTop();
111111 }
@@ -131,7 +131,7 @@ int lua_callfunction (lua_Object function) · 19 unmodified lines
131131 else {
132132 luaD_openstack((L->stack.top-L->stack.stack)-L->Cstack.base);
133133 set_normalized(L->stack.stack+L->Cstack.base, Address(function));
134− return luaD_protectedrun(MULT_RET);
134+ return luaD_protectedrun();
135135 }
136136 }
137137
@@ -150,12 +150,12 @@ lua_Object lua_settagmethod (int tag, char *event) · 12 unmodified lines
150150 }
151151
152152
153−lua_Object lua_seterrormethod (void)
154−{
155− TObject temp = L->errorim;
153+lua_Object lua_seterrormethod (void) {
154+ lua_Object temp;
156155 checkCparams(1);
157− L->errorim = *(--L->stack.top);
158− return put_luaObject(&temp);
156+ temp = lua_getglobal("_ERRORMESSAGE");
157+ lua_setglobal("_ERRORMESSAGE");
158+ return temp;
159159 }
160160
161161
@@ -167,34 +167,26 @@ lua_Object lua_gettable (void) · 5 unmodified lines
167167 }
168168
169169
170−lua_Object lua_rawgettable (void)
171−{
170+lua_Object lua_rawgettable (void) {
172171 checkCparams(2);
173172 if (ttype(L->stack.top-2) != LUA_T_ARRAY)
174173 lua_error("indexed expression not a table in rawgettable");
175− else {
176− TObject *h = luaH_get(avalue(L->stack.top-2), L->stack.top-1);
177− --L->stack.top;
178− if (h != NULL)
179− *(L->stack.top-1) = *h;
180− else
181− ttype(L->stack.top-1) = LUA_T_NIL;
182− }
174+ *(L->stack.top-2) = *luaH_get(avalue(L->stack.top-2), L->stack.top-1);
175+ --L->stack.top;
183176 return put_luaObjectonTop();
184177 }
185178
186179
187−void lua_settable (void)
188−{
180+void lua_settable (void) {
189181 checkCparams(3);
190− luaV_settable(L->stack.top-3, 1);
182+ luaV_settable(L->stack.top-3);
183+ L->stack.top -= 2; /* pop table and index */
191184 }
192185
193186
194−void lua_rawsettable (void)
195−{
187+void lua_rawsettable (void) {
196188 checkCparams(3);
197− luaV_settable(L->stack.top-3, 0);
189+ luaV_rawsettable(L->stack.top-3);
198190 }
199191
200192
@@ -373,14 +365,11 @@ void luaA_pushobject (TObject *o) · 172 unmodified lines
373365 incr_top;
374366 }
375367
376−void lua_pushobject (lua_Object o)
377−{
368+void lua_pushobject (lua_Object o) {
378369 if (o == LUA_NOOBJECT)
379370 lua_error("API error - attempt to push a NOOBJECT");
380− else {
381− set_normalized(L->stack.top, Address(o));
382− incr_top;
383− }
371+ set_normalized(L->stack.top, Address(o));
372+ incr_top;
384373 }
385374
386375
@@ -426,22 +415,108 @@ void lua_settag (int tag) · 39 unmodified lines
426415 break;
427416 default:
428417 luaL_verror("cannot change the tag of a %.20s",
429− luaO_typenames[-ttype((L->stack.top-1))]);
418+ luaO_typename(L->stack.top-1));
430419 }
431420 L->stack.top--;
432421 }
433422
434423
424+TaggedString *luaA_nextvar (TaggedString *g) {
425+ if (g == NULL)
426+ g = (TaggedString *)L->rootglobal.next; /* first variable */
427+ else {
428+ /* check whether name is in global var list */
429+ luaL_arg_check((GCnode *)g != g->head.next, 1, "variable name expected");
430+ g = (TaggedString *)g->head.next; /* get next */
431+ }
432+ while (g && g->u.s.globalval.ttype == LUA_T_NIL) /* skip globals with nil */
433+ g = (TaggedString *)g->head.next;
434+ if (g) {
435+ ttype(L->stack.top) = LUA_T_STRING; tsvalue(L->stack.top) = g;
436+ incr_top;
437+ luaA_pushobject(&g->u.s.globalval);
438+ }
439+ return g;
440+}
441+
442+
443+char *lua_nextvar (char *varname) {
444+ TaggedString *g = (varname == NULL) ? NULL : luaS_new(varname);
445+ g = luaA_nextvar(g);
446+ if (g) {
447+ top2LC(2);
448+ return g->str;
449+ }
450+ else {
451+ top2LC(0);
452+ return NULL;
453+ }
454+}
455+
456+
457+int luaA_next (Hash *t, int i) {
458+ int tsize = nhash(t);
459+ for (; i<tsize; i++) {
460+ Node *n = node(t, i);
461+ if (ttype(val(n)) != LUA_T_NIL) {
462+ luaA_pushobject(ref(n));
463+ luaA_pushobject(val(n));
464+ return i+1; /* index to be used next time */
465+ }
466+ }
467+ return 0; /* no more elements */
468+}
469+
470+
471+int lua_next (lua_Object o, int i) {
472+ TObject *t = Address(o);
473+ if (ttype(t) != LUA_T_ARRAY)
474+ lua_error("API error - object is not a table in `lua_next'");
475+ i = luaA_next(avalue(t), i);
476+ top2LC((i==0) ? 0 : 2);
477+ return i;
478+}
479+
480+
481+
435482 /*
436−** =======================================================
437−** Debug interface
483+** {======================================================
484+** To manipulate some state information
438485 ** =======================================================
439486 */
440487
488+lua_State *lua_setstate (lua_State *st) {
489+ lua_State *old = lua_state;
490+ lua_state = st;
491+ return old;
492+}
493+
494+lua_LHFunction lua_setlinehook (lua_LHFunction func) {
495+ lua_LHFunction old = L->linehook;
496+ L->linehook = func;
497+ return old;
498+}
499+
500+lua_CHFunction lua_setcallhook (lua_CHFunction func) {
501+ lua_CHFunction old = L->callhook;
502+ L->callhook = func;
503+ return old;
504+}
505+
506+int lua_setdebug (int debug) {
507+ int old = L->debug;
508+ L->debug = debug;
509+ return old;
510+}
511+
512+/* }====================================================== */
441513
442−/* Hooks */
443−lua_CHFunction lua_callhook = NULL;
444−lua_LHFunction lua_linehook = NULL;
514+
515+/*
516+** {======================================================
517+** Debug interface
518+** =======================================================
519+*/
445520
446521
447522 lua_Function lua_stackedfunction (int level)
@@ -457,6 +532,12 @@ lua_Function lua_stackedfunction (int level) · 9 unmodified lines
457532 }
458533
459534
535+int lua_nups (lua_Function func) {
536+ TObject *o = luaA_Address(func);
537+ return (!o || normalized_type(o) != LUA_T_CLOSURE) ? 0 : o->value.cl->nelems;
538+}
539+
540+
460541 int lua_currentline (lua_Function func)
461542 {
462543 TObject *f = Address(func);
@@ -465,8 +546,7 @@ int lua_currentline (lua_Function func) · 2 unmodified lines
465546 }
466547
467548
468−lua_Object lua_getlocal (lua_Function func, int local_number, char **name)
469−{
549+lua_Object lua_getlocal (lua_Function func, int local_number, char **name) {
470550 /* check whether func is a Lua function */
471551 if (lua_tag(func) != LUA_T_PROTO)
472552 return LUA_NOOBJECT;
@@ -477,7 +557,7 @@ lua_Object lua_getlocal (lua_Function func, int local_number, char **name) · 4 unmodified lines
477557 if (*name) {
478558 /* if "*name", there must be a LUA_T_LINE */
479559 /* therefore, f+2 points to function base */
480− return Ref((f+2)+(local_number-1));
560+ return put_luaObject((f+2)+(local_number-1));
481561 }
482562 else
483563 return LUA_NOOBJECT;
@@ -508,18 +588,17 @@ int lua_setlocal (lua_Function func, int local_number) · 24 unmodified lines
508588 }
509589
510590
511−void lua_funcinfo (lua_Object func, char **filename, int *linedefined)
512−{
591+void lua_funcinfo (lua_Object func, char **source, int *linedefined) {
513592 if (!lua_isfunction(func))
514− lua_error("API - `funcinfo' called with a non-function value");
593+ lua_error("API error - `funcinfo' called with a non-function value");
515594 else {
516595 TObject *f = luaA_protovalue(Address(func));
517596 if (normalized_type(f) == LUA_T_PROTO) {
518− *filename = tfvalue(f)->fileName->str;
597+ *source = tfvalue(f)->source->str;
519598 *linedefined = tfvalue(f)->lineDefined;
520599 }
521600 else {
522− *filename = "(C)";
601+ *source = "(C)";
523602 *linedefined = -1;
524603 }
525604 }
@@ -534,31 +613,37 @@ static int checkfunc (TObject *o) · 8 unmodified lines
534613
535614 char *lua_getobjname (lua_Object o, char **name)
536615 { /* try to find a name for given function */
537− set_normalized(L->stack.top, Address(o)); /* to be accessed by "checkfunc */
538− if ((*name = luaT_travtagmethods(checkfunc)) != NULL)
539− return "tag-method";
540− else if ((*name = luaS_travsymbol(checkfunc)) != NULL)
616+ set_normalized(L->stack.top, Address(o)); /* to be accessed by "checkfunc" */
617+ if ((*name = luaS_travsymbol(checkfunc)) != NULL)
541618 return "global";
619+ else if ((*name = luaT_travtagmethods(checkfunc)) != NULL)
620+ return "tag-method";
542621 else return "";
543622 }
544623
624+/* }====================================================== */
625+
626+
545627 /*
546−** =======================================================
628+** {======================================================
547629 ** BLOCK mechanism
548630 ** =======================================================
549631 */
550632
551633
552−void lua_beginblock (void)
553−{
554− if (L->numCblocks >= MAX_C_BLOCKS)
555− lua_error("too many nested blocks");
634+#ifndef MAX_C_BLOCKS
635+#define MAX_C_BLOCKS 1000 /* arbitrary limit */
636+#endif
637+
638+
639+void lua_beginblock (void) {
640+ luaM_growvector(L->Cblocks, L->numCblocks, 1, struct C_Lua_Stack,
641+ "too many nested blocks", MAX_C_BLOCKS);
556642 L->Cblocks[L->numCblocks] = L->Cstack;
557643 L->numCblocks++;
558644 }
559645
560−void lua_endblock (void)
561−{
646+void lua_endblock (void) {
562647 --L->numCblocks;
563648 L->Cstack = L->Cblocks[L->numCblocks];
564649 luaD_adjusttop(L->Cstack.base);
@@ -566,8 +651,7 @@ void lua_endblock (void) · 1 unmodified line
566651
567652
568653
569−int lua_ref (int lock)
570−{
654+int lua_ref (int lock) {
571655 int ref;
572656 checkCparams(1);
573657 ref = luaC_ref(L->stack.top-1, lock);
@@ -577,32 +661,12 @@ int lua_ref (int lock) · 3 unmodified lines
577661
578662
579663
580−lua_Object lua_getref (int ref)
581−{
664+lua_Object lua_getref (int ref) {
582665 TObject *o = luaC_getref(ref);
583666 return (o ? put_luaObject(o) : LUA_NOOBJECT);
584667 }
585668
586−
587−/*
588−** =======================================================
589−** Derived functions
590−** =======================================================
591−*/
592−int (lua_call) (char *name) { return lua_call(name); }
593−
594−void (lua_pushref) (int ref) { lua_pushref(ref); }
595−
596−int (lua_refobject) (lua_Object o, int l) { return lua_refobject(o, l); }
597−
598−void (lua_register) (char *n, lua_CFunction f) { lua_register(n, f); }
599−
600−void (lua_pushuserdata) (void *u) { lua_pushuserdata(u); }
601−
602−void (lua_pushcfunction) (lua_CFunction f) { lua_pushcfunction(f); }
603−
604−int (lua_clonetag) (int t) { return lua_clonetag(t); }
605−
669+/* }====================================================== */
606670
607671
608672
@@ -611,17 +675,15 @@ int (lua_clonetag) (int t) { return lua_clonetag(t); } · 2 unmodified lines
611675 ** API: set a function as a fallback
612676 */
613677
614−static void do_unprotectedrun (lua_CFunction f, int nParams, int nResults)
615−{
616− StkId base = (L->stack.top-L->stack.stack)-nParams;
678+static void do_unprotectedrun (lua_CFunction f, int nParams, int nResults) {
617679 luaD_openstack(nParams);
618− L->stack.stack[base].ttype = LUA_T_CPROTO;
619− L->stack.stack[base].value.f = f;
620− luaD_call(base+1, nResults);
680+ (L->stack.top-nParams)->ttype = LUA_T_CPROTO;
681+ (L->stack.top-nParams)->value.f = f;
682+ luaD_calln(nParams, nResults);
621683 }
622684
623−lua_Object lua_setfallback (char *name, lua_CFunction fallback)
624−{
685+
686+lua_Object lua_setfallback (char *name, lua_CFunction fallback) {
625687 lua_pushstring(name);
626688 lua_pushcfunction(fallback);
627689 do_unprotectedrun(luaT_setfallback, 2, 1);
src/lapi.h+3−1
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lapi.h,v 1.2 1998/06/19 16:14:09 roberto Exp $
2+** $Id: lapi.h,v 1.4 1999/02/23 14:57:28 roberto Exp $
33 ** Auxiliary functions from Lua API
44 ** See Copyright Notice in lua.h
55 */
@@ -16,5 +16,7 @@ TObject *luaA_Address (lua_Object o); · 10 unmodified lines
1616 void luaA_pushobject (TObject *o);
1717 void luaA_packresults (void);
1818 int luaA_passresults (void);
19+TaggedString *luaA_nextvar (TaggedString *g);
20+int luaA_next (Hash *t, int i);
1921
2022 #endif
src/lauxlib.c+29−7
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lauxlib.c,v 1.12 1998/06/19 16:14:09 roberto Exp $
2+** $Id: lauxlib.c,v 1.17 1999/03/11 18:59:19 roberto Exp $
33 ** Auxiliary functions for building Lua libraries
44 ** See Copyright Notice in lua.h
55 */
@@ -10,9 +10,10 @@ · 4 unmodified lines
1010 #include <string.h>
1111
1212 /* Please Notice: This file uses only the official API of Lua
13−** Any function declared here could be written as an application
14−** function. With care, these functions can be used by other libraries.
13+** Any function declared here could be written as an application function.
14+** With care, these functions can be used by other libraries.
1515 */
16+
1617 #include "lauxlib.h"
1718 #include "lua.h"
1819 #include "luadebug.h"
@@ -27,12 +28,13 @@ int luaL_findstring (char *name, char *list[]) { · 8 unmodified lines
2728 return -1; /* name not found */
2829 }
2930
30−void luaL_argerror (int numarg, char *extramsg)
31−{
31+void luaL_argerror (int numarg, char *extramsg) {
32+ lua_Function f = lua_stackedfunction(0);
3233 char *funcname;
33− lua_getobjname(lua_stackedfunction(0), &funcname);
34+ lua_getobjname(f, &funcname);
35+ numarg -= lua_nups(f);
3436 if (funcname == NULL)
35− funcname = "???";
37+ funcname = "?";
3638 if (extramsg == NULL)
3739 luaL_verror("bad argument #%d to function `%.50s'", numarg, funcname);
3840 else
@@ -109,3 +111,23 @@ void luaL_verror (char *fmt, ...) · 70 unmodified lines
109111 lua_error(buff);
110112 }
111113
114+
115+void luaL_chunkid (char *out, char *source, int len) {
116+ len -= 13; /* 13 = strlen("string ''...\0") */
117+ if (*source == '@')
118+ sprintf(out, "file `%.*s'", len, source+1);
119+ else if (*source == '(')
120+ strcpy(out, "(C code)");
121+ else {
122+ char *b = strchr(source , '\n'); /* stop string at first new line */
123+ int lim = (b && (b-source)<len) ? b-source : len;
124+ sprintf(out, "string `%.*s'", lim, source);
125+ strcpy(out+lim+(13-5), "...'"); /* 5 = strlen("...'\0") */
126+ }
127+}
128+
129+
130+void luaL_filesource (char *out, char *filename, int len) {
131+ if (filename == NULL) filename = "(stdin)";
132+ sprintf(out, "@%.*s", len-2, filename); /* -2 for '@' and '\0' */
133+}
src/lbuffer.c+25−35
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lbuffer.c,v 1.4 1998/06/19 16:14:09 roberto Exp $
2+** $Id: lbuffer.c,v 1.9 1999/02/26 15:48:55 roberto Exp $
33 ** Auxiliary functions for building Lua libraries
44 ** See Copyright Notice in lua.h
55 */
@@ -16,70 +16,60 @@ · 10 unmodified lines
1616 ** Auxiliary buffer
1717 -------------------------------------------------------*/
1818
19−#define BUFF_STEP 32
19+
20+#define EXTRABUFF 32
21+
2022
2123 #define openspace(size) if (L->Mbuffnext+(size) > L->Mbuffsize) Openspace(size)
2224
23−static void Openspace (int size)
24−{
25+static void Openspace (int size) {
2526 lua_State *l = L; /* to optimize */
26− int base = l->Mbuffbase-l->Mbuffer;
27− l->Mbuffsize *= 2;
28− if (l->Mbuffnext+size > l->Mbuffsize) /* still not big enough? */
29− l->Mbuffsize = l->Mbuffnext+size;
30− l->Mbuffer = luaM_realloc(l->Mbuffer, l->Mbuffsize);
31− l->Mbuffbase = l->Mbuffer+base;
27+ size += EXTRABUFF;
28+ l->Mbuffsize = l->Mbuffnext+size;
29+ luaM_growvector(l->Mbuffer, l->Mbuffnext, size, char, arrEM, MAX_INT);
3230 }
3331
3432
35−char *luaL_openspace (int size)
36−{
33+char *luaL_openspace (int size) {
3734 openspace(size);
3835 return L->Mbuffer+L->Mbuffnext;
3936 }
4037
4138
42−void luaL_addchar (int c)
43−{
44− openspace(BUFF_STEP);
45− L->Mbuffer[L->Mbuffnext++] = c;
39+void luaL_addchar (int c) {
40+ openspace(1);
41+ L->Mbuffer[L->Mbuffnext++] = (char)c;
4642 }
4743
4844
49−void luaL_resetbuffer (void)
50−{
51− L->Mbuffnext = L->Mbuffbase-L->Mbuffer;
45+void luaL_resetbuffer (void) {
46+ L->Mbuffnext = L->Mbuffbase;
5247 }
5348
5449
55−void luaL_addsize (int n)
56−{
50+void luaL_addsize (int n) {
5751 L->Mbuffnext += n;
5852 }
5953
60−int luaL_getsize (void)
61−{
62− return L->Mbuffnext-(L->Mbuffbase-L->Mbuffer);
54+int luaL_getsize (void) {
55+ return L->Mbuffnext-L->Mbuffbase;
6356 }
6457
65−int luaL_newbuffer (int size)
66−{
67− int old = L->Mbuffbase-L->Mbuffer;
58+int luaL_newbuffer (int size) {
59+ int old = L->Mbuffbase;
6860 openspace(size);
69− L->Mbuffbase = L->Mbuffer+L->Mbuffnext;
61+ L->Mbuffbase = L->Mbuffnext;
7062 return old;
7163 }
7264
7365
74−void luaL_oldbuffer (int old)
75−{
76− L->Mbuffnext = L->Mbuffbase-L->Mbuffer;
77− L->Mbuffbase = L->Mbuffer+old;
66+void luaL_oldbuffer (int old) {
67+ L->Mbuffnext = L->Mbuffbase;
68+ L->Mbuffbase = old;
7869 }
7970
8071
81−char *luaL_buffer (void)
82−{
83− return L->Mbuffbase;
72+char *luaL_buffer (void) {
73+ return L->Mbuffer+L->Mbuffbase;
8474 }
8575
src/lbuiltin.c+488−278
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lbuiltin.c,v 1.32 1998/06/29 18:24:06 roberto Exp $
2+** $Id: lbuiltin.c,v 1.59 1999/06/17 17:04:03 roberto Exp $
33 ** Built-in functions
44 ** See Copyright Notice in lua.h
55 */
@@ -23,11 +23,18 @@ · 17 unmodified lines
2323 #include "ltm.h"
2424 #include "lua.h"
2525 #include "lundump.h"
26+#include "lvm.h"
2627
2728
2829
29−static void pushstring (TaggedString *s)
30−{
30+/*
31+** {======================================================
32+** Auxiliary functions
33+** =======================================================
34+*/
35+
36+
37+static void pushtagstring (TaggedString *s) {
3138 TObject o;
3239 o.ttype = LUA_T_STRING;
3340 o.value.ts = s;
@@ -35,209 +42,126 @@ static void pushstring (TaggedString *s) · 1 unmodified line
3542 }
3643
3744
38−static void nextvar (void)
39−{
40− TObject *o = luaA_Address(luaL_nonnullarg(1));
41− TaggedString *g;
42− if (ttype(o) == LUA_T_NIL)
43− g = (TaggedString *)L->rootglobal.next;
44− else {
45− luaL_arg_check(ttype(o) == LUA_T_STRING, 1, "variable name expected");
46− g = tsvalue(o);
47− /* check whether name is in global var list */
48− luaL_arg_check((GCnode *)g != g->head.next, 1, "variable name expected");
49− g = (TaggedString *)g->head.next;
50− }
51− while (g && g->u.s.globalval.ttype == LUA_T_NIL) /* skip globals with nil */
52− g = (TaggedString *)g->head.next;
53− if (g) {
54− pushstring(g);
55− luaA_pushobject(&g->u.s.globalval);
45+static real getsize (Hash *h) {
46+ real max = 0;
47+ int i;
48+ for (i = 0; i<nhash(h); i++) {
49+ Node *n = h->node+i;
50+ if (ttype(ref(n)) == LUA_T_NUMBER &&
51+ ttype(val(n)) != LUA_T_NIL &&
52+ nvalue(ref(n)) > max)
53+ max = nvalue(ref(n));
5654 }
57− else lua_pushnil();
55+ return max;
5856 }
5957
6058
61−static void foreachvar (void)
62−{
63− TObject f = *luaA_Address(luaL_functionarg(1));
64− GCnode *g;
65− StkId name = L->Cstack.base++; /* place to keep var name (to avoid GC) */
66− ttype(L->stack.stack+name) = LUA_T_NIL;
67− L->stack.top++;
68− for (g = L->rootglobal.next; g; g = g->next) {
69− TaggedString *s = (TaggedString *)g;
70− if (s->u.s.globalval.ttype != LUA_T_NIL) {
71− ttype(L->stack.stack+name) = LUA_T_STRING;
72− tsvalue(L->stack.stack+name) = s; /* keep s on stack to avoid GC */
73− luaA_pushobject(&f);
74− pushstring(s);
75− luaA_pushobject(&s->u.s.globalval);
76− luaD_call((L->stack.top-L->stack.stack)-2, 1);
77− if (ttype(L->stack.top-1) != LUA_T_NIL)
78− return;
79− L->stack.top--;
80− }
81− }
59+static real getnarg (Hash *a) {
60+ TObject index;
61+ TObject *value;
62+ /* value = table.n */
63+ ttype(&index) = LUA_T_STRING;
64+ tsvalue(&index) = luaS_new("n");
65+ value = luaH_get(a, &index);
66+ return (ttype(value) == LUA_T_NUMBER) ? nvalue(value) : getsize(a);
8267 }
8368
8469
85−static void next (void)
86−{
87− lua_Object o = luaL_tablearg(1);
88− lua_Object r = luaL_nonnullarg(2);
89− Node *n = luaH_next(luaA_Address(o), luaA_Address(r));
90− if (n) {
91− luaA_pushobject(&n->ref);
92− luaA_pushobject(&n->val);
93− }
94− else lua_pushnil();
70+static Hash *gethash (int arg) {
71+ return avalue(luaA_Address(luaL_tablearg(arg)));
9572 }
9673
97−
98−static void foreach (void)
99−{
100− TObject t = *luaA_Address(luaL_tablearg(1));
101− TObject f = *luaA_Address(luaL_functionarg(2));
102− int i;
103− for (i=0; i<avalue(&t)->nhash; i++) {
104− Node *nd = &(avalue(&t)->node[i]);
105− if (ttype(ref(nd)) != LUA_T_NIL && ttype(val(nd)) != LUA_T_NIL) {
106− luaA_pushobject(&f);
107− luaA_pushobject(ref(nd));
108− luaA_pushobject(val(nd));
109− luaD_call((L->stack.top-L->stack.stack)-2, 1);
110− if (ttype(L->stack.top-1) != LUA_T_NIL)
111− return;
112− L->stack.top--;
113− }
114− }
115−}
74+/* }====================================================== */
11675
11776
118−static void internaldostring (void)
119−{
120− long l;
121− char *s = luaL_check_lstr(1, &l);
122− if (*s == ID_CHUNK)
123− lua_error("`dostring' cannot run pre-compiled code");
124− if (lua_dobuffer(s, l, luaL_opt_string(2, NULL)) == 0)
125− if (luaA_passresults() == 0)
126− lua_pushuserdata(NULL); /* at least one result to signal no errors */
127−}
77+/*
78+** {======================================================
79+** Functions that use only the official API
80+** =======================================================
81+*/
12882
12983
130−static void internaldofile (void)
131−{
132− char *fname = luaL_opt_string(1, NULL);
133− if (lua_dofile(fname) == 0)
134− if (luaA_passresults() == 0)
135− lua_pushuserdata(NULL); /* at least one result to signal no errors */
84+/*
85+** If your system does not support "stderr", redefine this function, or
86+** redefine _ERRORMESSAGE so that it won't need _ALERT.
87+*/
88+static void luaB_alert (void) {
89+ fputs(luaL_check_string(1), stderr);
13690 }
13791
13892
139−static void to_string (void) {
140− lua_Object obj = lua_getparam(1);
141− char *buff = luaL_openspace(30);
142− TObject *o = luaA_Address(obj);
143− switch (ttype(o)) {
144− case LUA_T_NUMBER:
145− lua_pushstring(lua_getstring(obj));
146− return;
147− case LUA_T_STRING:
148− lua_pushobject(obj);
149− return;
150− case LUA_T_ARRAY: {
151− sprintf(buff, "table: %p", (void *)o->value.a);
152− break;
153− }
154− case LUA_T_CLOSURE: {
155− sprintf(buff, "function: %p", (void *)o->value.cl);
156− break;
157− }
158− case LUA_T_PROTO: {
159− sprintf(buff, "function: %p", (void *)o->value.tf);
160− break;
161− }
162− case LUA_T_CPROTO: {
163− sprintf(buff, "function: %p", (void *)o->value.f);
164− break;
165− }
166− case LUA_T_USERDATA: {
167− sprintf(buff, "userdata: %p", o->value.ts->u.d.v);
168− break;
169− }
170− case LUA_T_NIL:
171− lua_pushstring("nil");
172− return;
173− default:
174− LUA_INTERNALERROR("invalid type");
93+/*
94+** Standard implementation of _ERRORMESSAGE.
95+** The library "iolib" redefines _ERRORMESSAGE for better error information.
96+*/
97+static void error_message (void) {
98+ lua_Object al = lua_rawgetglobal("_ALERT");
99+ if (lua_isfunction(al)) { /* avoid error loop if _ALERT is not defined */
100+ char buff[600];
101+ sprintf(buff, "lua error: %.500s\n", luaL_check_string(1));
102+ lua_pushstring(buff);
103+ lua_callfunction(al);
175104 }
176− lua_pushstring(buff);
177105 }
178106
179107
180−static void luaI_print (void) {
181− TaggedString *ts = luaS_new("tostring");
108+/*
109+** If your system does not support "stdout", just remove this function.
110+** If you need, you can define your own "print" function, following this
111+** model but changing "fputs" to put the strings at a proper place
112+** (a console window or a log file, for instance).
113+*/
114+#ifndef MAXPRINT
115+#define MAXPRINT 40 /* arbitrary limit */
116+#endif
117+
118+static void luaB_print (void) {
119+ lua_Object args[MAXPRINT];
182120 lua_Object obj;
183− int i = 1;
184− while ((obj = lua_getparam(i++)) != LUA_NOOBJECT) {
185− luaA_pushobject(&ts->u.s.globalval);
186− lua_pushobject(obj);
187− luaD_call((L->stack.top-L->stack.stack)-1, 1);
188− if (ttype(L->stack.top-1) != LUA_T_STRING)
121+ int n = 0;
122+ int i;
123+ while ((obj = lua_getparam(n+1)) != LUA_NOOBJECT) {
124+ luaL_arg_check(n < MAXPRINT, n+1, "too many arguments");
125+ args[n++] = obj;
126+ }
127+ for (i=0; i<n; i++) {
128+ lua_pushobject(args[i]);
129+ if (lua_call("tostring"))
130+ lua_error("error in `tostring' called by `print'");
131+ obj = lua_getresult(1);
132+ if (!lua_isstring(obj))
189133 lua_error("`tostring' must return a string to `print'");
190− printf("%s\t", svalue(L->stack.top-1));
191− L->stack.top--;
134+ if (i>0) fputs("\t", stdout);
135+ fputs(lua_getstring(obj), stdout);
192136 }
193− printf("\n");
194−}
195−
196−
197−static void luaI_type (void)
198−{
199− lua_Object o = luaL_nonnullarg(1);
200− lua_pushstring(luaO_typenames[-ttype(luaA_Address(o))]);
201− lua_pushnumber(lua_tag(o));
137+ fputs("\n", stdout);
202138 }
203139
204140
205−static void tonumber (void)
206−{
207− int base = luaL_opt_number(2, 10);
141+static void luaB_tonumber (void) {
142+ int base = luaL_opt_int(2, 10);
208143 if (base == 10) { /* standard conversion */
209144 lua_Object o = lua_getparam(1);
210− if (lua_isnumber(o))
211− lua_pushnumber(lua_getnumber(o));
145+ if (lua_isnumber(o)) lua_pushnumber(lua_getnumber(o));
146+ else lua_pushnil(); /* not a number */
212147 }
213148 else {
214149 char *s = luaL_check_string(1);
215− unsigned long n;
150+ long n;
216151 luaL_arg_check(0 <= base && base <= 36, 2, "base out of range");
217152 n = strtol(s, &s, base);
218− while (isspace(*s)) s++; /* skip trailing spaces */
153+ while (isspace((unsigned char)*s)) s++; /* skip trailing spaces */
219154 if (*s) lua_pushnil(); /* invalid format: return nil */
220155 else lua_pushnumber(n);
221156 }
222157 }
223158
224159
225−static void luaI_error (void)
226−{
160+static void luaB_error (void) {
227161 lua_error(lua_getstring(lua_getparam(1)));
228162 }
229163
230−
231−static void luaI_assert (void)
232−{
233− lua_Object p = lua_getparam(1);
234− if (p == LUA_NOOBJECT || lua_isnil(p))
235− luaL_verror("assertion failed! %.100s", luaL_opt_string(2, ""));
236−}
237−
238−
239−static void setglobal (void)
240−{
164+static void luaB_setglobal (void) {
241165 char *n = luaL_check_string(1);
242166 lua_Object value = luaL_nonnullarg(2);
243167 lua_pushobject(value);
@@ -245,8 +169,7 @@ static void setglobal (void) · 1 unmodified line
245169 lua_pushobject(value); /* return given value */
246170 }
247171
248−static void rawsetglobal (void)
249−{
172+static void luaB_rawsetglobal (void) {
250173 char *n = luaL_check_string(1);
251174 lua_Object value = luaL_nonnullarg(2);
252175 lua_pushobject(value);
@@ -254,51 +177,111 @@ static void rawsetglobal (void) · 1 unmodified line
254177 lua_pushobject(value); /* return given value */
255178 }
256179
257−static void getglobal (void)
258−{
180+static void luaB_getglobal (void) {
259181 lua_pushobject(lua_getglobal(luaL_check_string(1)));
260182 }
261183
262−static void rawgetglobal (void)
263−{
184+static void luaB_rawgetglobal (void) {
264185 lua_pushobject(lua_rawgetglobal(luaL_check_string(1)));
265186 }
266187
267−static void luatag (void)
268−{
188+static void luaB_luatag (void) {
269189 lua_pushnumber(lua_tag(lua_getparam(1)));
270190 }
271191
192+static void luaB_settag (void) {
193+ lua_Object o = luaL_tablearg(1);
194+ lua_pushobject(o);
195+ lua_settag(luaL_check_int(2));
196+ lua_pushobject(o); /* return first argument */
197+}
198+
199+static void luaB_newtag (void) {
200+ lua_pushnumber(lua_newtag());
201+}
202+
203+static void luaB_copytagmethods (void) {
204+ lua_pushnumber(lua_copytagmethods(luaL_check_int(1),
205+ luaL_check_int(2)));
206+}
207+
208+static void luaB_rawgettable (void) {
209+ lua_pushobject(luaL_nonnullarg(1));
210+ lua_pushobject(luaL_nonnullarg(2));
211+ lua_pushobject(lua_rawgettable());
212+}
213+
214+static void luaB_rawsettable (void) {
215+ lua_pushobject(luaL_nonnullarg(1));
216+ lua_pushobject(luaL_nonnullarg(2));
217+ lua_pushobject(luaL_nonnullarg(3));
218+ lua_rawsettable();
219+}
220+
221+static void luaB_settagmethod (void) {
222+ lua_Object nf = luaL_nonnullarg(3);
223+ lua_pushobject(nf);
224+ lua_pushobject(lua_settagmethod(luaL_check_int(1), luaL_check_string(2)));
225+}
226+
227+static void luaB_gettagmethod (void) {
228+ lua_pushobject(lua_gettagmethod(luaL_check_int(1), luaL_check_string(2)));
229+}
272230
273−static int getnarg (lua_Object table)
274−{
275− lua_Object temp;
276− /* temp = table.n */
277− lua_pushobject(table); lua_pushstring("n"); temp = lua_rawgettable();
278− return (lua_isnumber(temp) ? lua_getnumber(temp) : MAX_INT);
231+static void luaB_seterrormethod (void) {
232+ lua_Object nf = luaL_functionarg(1);
233+ lua_pushobject(nf);
234+ lua_pushobject(lua_seterrormethod());
235+}
236+
237+static void luaB_collectgarbage (void) {
238+ lua_pushnumber(lua_collectgarbage(luaL_opt_int(1, 0)));
279239 }
280240
281−static void luaI_call (void)
282−{
241+/* }====================================================== */
242+
243+
244+/*
245+** {======================================================
246+** Functions that could use only the official API but
247+** do not, for efficiency.
248+** =======================================================
249+*/
250+
251+static void luaB_dostring (void) {
252+ long l;
253+ char *s = luaL_check_lstr(1, &l);
254+ if (*s == ID_CHUNK)
255+ lua_error("`dostring' cannot run pre-compiled code");
256+ if (lua_dobuffer(s, l, luaL_opt_string(2, s)) == 0)
257+ if (luaA_passresults() == 0)
258+ lua_pushuserdata(NULL); /* at least one result to signal no errors */
259+}
260+
261+
262+static void luaB_dofile (void) {
263+ char *fname = luaL_opt_string(1, NULL);
264+ if (lua_dofile(fname) == 0)
265+ if (luaA_passresults() == 0)
266+ lua_pushuserdata(NULL); /* at least one result to signal no errors */
267+}
268+
269+
270+static void luaB_call (void) {
283271 lua_Object f = luaL_nonnullarg(1);
284− lua_Object arg = luaL_tablearg(2);
272+ Hash *arg = gethash(2);
285273 char *options = luaL_opt_string(3, "");
286274 lua_Object err = lua_getparam(4);
287− int narg = getnarg(arg);
275+ int narg = (int)getnarg(arg);
288276 int i, status;
289277 if (err != LUA_NOOBJECT) { /* set new error method */
290278 lua_pushobject(err);
291279 err = lua_seterrormethod();
292280 }
293281 /* push arg[1...n] */
294− for (i=0; i<narg; i++) {
295− lua_Object temp;
296− /* temp = arg[i+1] */
297− lua_pushobject(arg); lua_pushnumber(i+1); temp = lua_rawgettable();
298− if (narg == MAX_INT && lua_isnil(temp))
299− break;
300− lua_pushobject(temp);
301− }
282+ luaD_checkstack(narg);
283+ for (i=0; i<narg; i++)
284+ *(L->stack.top++) = *luaH_getint(arg, i+1);
302285 status = lua_callfunction(f);
303286 if (err != LUA_NOOBJECT) { /* restore old error method */
304287 lua_pushobject(err);
@@ -312,7 +295,7 @@ static void luaI_call (void) · 7 unmodified lines
312295 else
313296 lua_error(NULL);
314297 }
315− else { /* no errors */
298+ else { /* no errors */
316299 if (strchr(options, 'p'))
317300 luaA_packresults();
318301 else
@@ -321,91 +304,306 @@ static void luaI_call (void) · 2 unmodified lines
321304 }
322305
323306
324−static void settag (void)
325−{
326− lua_Object o = luaL_tablearg(1);
327− lua_pushobject(o);
328− lua_settag(luaL_check_number(2));
329− lua_pushobject(o); /* returns first argument */
307+static void luaB_nextvar (void) {
308+ TObject *o = luaA_Address(luaL_nonnullarg(1));
309+ TaggedString *g;
310+ if (ttype(o) == LUA_T_NIL)
311+ g = NULL;
312+ else {
313+ luaL_arg_check(ttype(o) == LUA_T_STRING, 1, "variable name expected");
314+ g = tsvalue(o);
315+ }
316+ if (!luaA_nextvar(g))
317+ lua_pushnil();
330318 }
331319
332320
333−static void newtag (void)
334−{
335− lua_pushnumber(lua_newtag());
321+static void luaB_next (void) {
322+ Hash *a = gethash(1);
323+ TObject *k = luaA_Address(luaL_nonnullarg(2));
324+ int i = (ttype(k) == LUA_T_NIL) ? 0 : luaH_pos(a, k)+1;
325+ if (luaA_next(a, i) == 0)
326+ lua_pushnil();
336327 }
337328
338329
339−static void copytagmethods (void)
340−{
341− lua_pushnumber(lua_copytagmethods(luaL_check_number(1),
342− luaL_check_number(2)));
330+static void luaB_tostring (void) {
331+ lua_Object obj = lua_getparam(1);
332+ TObject *o = luaA_Address(obj);
333+ char buff[64];
334+ switch (ttype(o)) {
335+ case LUA_T_NUMBER:
336+ lua_pushstring(lua_getstring(obj));
337+ return;
338+ case LUA_T_STRING:
339+ lua_pushobject(obj);
340+ return;
341+ case LUA_T_ARRAY:
342+ sprintf(buff, "table: %p", (void *)o->value.a);
343+ break;
344+ case LUA_T_CLOSURE:
345+ sprintf(buff, "function: %p", (void *)o->value.cl);
346+ break;
347+ case LUA_T_PROTO:
348+ sprintf(buff, "function: %p", (void *)o->value.tf);
349+ break;
350+ case LUA_T_CPROTO:
351+ sprintf(buff, "function: %p", (void *)o->value.f);
352+ break;
353+ case LUA_T_USERDATA:
354+ sprintf(buff, "userdata: %p", o->value.ts->u.d.v);
355+ break;
356+ case LUA_T_NIL:
357+ lua_pushstring("nil");
358+ return;
359+ default:
360+ LUA_INTERNALERROR("invalid type");
361+ }
362+ lua_pushstring(buff);
343363 }
344364
345365
346−static void rawgettable (void)
347−{
348− lua_pushobject(luaL_nonnullarg(1));
349− lua_pushobject(luaL_nonnullarg(2));
350− lua_pushobject(lua_rawgettable());
366+static void luaB_type (void) {
367+ lua_Object o = luaL_nonnullarg(1);
368+ lua_pushstring(luaO_typename(luaA_Address(o)));
369+ lua_pushnumber(lua_tag(o));
351370 }
352371
372+/* }====================================================== */
353373
354−static void rawsettable (void)
355−{
356− lua_pushobject(luaL_nonnullarg(1));
357− lua_pushobject(luaL_nonnullarg(2));
358− lua_pushobject(luaL_nonnullarg(3));
359− lua_rawsettable();
374+
375+
376+/*
377+** {======================================================
378+** "Extra" functions
379+** These functions can be written in Lua, so you can
380+** delete them if you need a tiny Lua implementation.
381+** If you delete them, remove their entries in array
382+** "builtin_funcs".
383+** =======================================================
384+*/
385+
386+static void luaB_assert (void) {
387+ lua_Object p = lua_getparam(1);
388+ if (p == LUA_NOOBJECT || lua_isnil(p))
389+ luaL_verror("assertion failed! %.100s", luaL_opt_string(2, ""));
360390 }
361391
362392
363−static void settagmethod (void)
364−{
365− lua_Object nf = luaL_nonnullarg(3);
366− lua_pushobject(nf);
367− lua_pushobject(lua_settagmethod((int)luaL_check_number(1),
368− luaL_check_string(2)));
393+static void luaB_foreachi (void) {
394+ Hash *t = gethash(1);
395+ int i;
396+ int n = (int)getnarg(t);
397+ TObject f;
398+ /* 'f' cannot be a pointer to TObject, because it is on the stack, and the
399+ stack may be reallocated by the call. Moreover, some C compilers do not
400+ initialize structs, so we must do the assignment after the declaration */
401+ f = *luaA_Address(luaL_functionarg(2));
402+ luaD_checkstack(3); /* for f, ref, and val */
403+ for (i=1; i<=n; i++) {
404+ *(L->stack.top++) = f;
405+ ttype(L->stack.top) = LUA_T_NUMBER; nvalue(L->stack.top++) = i;
406+ *(L->stack.top++) = *luaH_getint(t, i);
407+ luaD_calln(2, 1);
408+ if (ttype(L->stack.top-1) != LUA_T_NIL)
409+ return;
410+ L->stack.top--;
411+ }
369412 }
370413
371414
372−static void gettagmethod (void)
373−{
374− lua_pushobject(lua_gettagmethod((int)luaL_check_number(1),
375− luaL_check_string(2)));
415+static void luaB_foreach (void) {
416+ Hash *a = gethash(1);
417+ int i;
418+ TObject f; /* see comment in 'foreachi' */
419+ f = *luaA_Address(luaL_functionarg(2));
420+ luaD_checkstack(3); /* for f, ref, and val */
421+ for (i=0; i<a->nhash; i++) {
422+ Node *nd = &(a->node[i]);
423+ if (ttype(val(nd)) != LUA_T_NIL) {
424+ *(L->stack.top++) = f;
425+ *(L->stack.top++) = *ref(nd);
426+ *(L->stack.top++) = *val(nd);
427+ luaD_calln(2, 1);
428+ if (ttype(L->stack.top-1) != LUA_T_NIL)
429+ return;
430+ L->stack.top--; /* remove result */
431+ }
432+ }
376433 }
377434
378435
379−static void seterrormethod (void)
380−{
381− lua_Object nf = luaL_functionarg(1);
382− lua_pushobject(nf);
383− lua_pushobject(lua_seterrormethod());
436+static void luaB_foreachvar (void) {
437+ GCnode *g;
438+ TObject f; /* see comment in 'foreachi' */
439+ f = *luaA_Address(luaL_functionarg(1));
440+ luaD_checkstack(4); /* for extra var name, f, var name, and globalval */
441+ for (g = L->rootglobal.next; g; g = g->next) {
442+ TaggedString *s = (TaggedString *)g;
443+ if (s->u.s.globalval.ttype != LUA_T_NIL) {
444+ pushtagstring(s); /* keep (extra) s on stack to avoid GC */
445+ *(L->stack.top++) = f;
446+ pushtagstring(s);
447+ *(L->stack.top++) = s->u.s.globalval;
448+ luaD_calln(2, 1);
449+ if (ttype(L->stack.top-1) != LUA_T_NIL) {
450+ L->stack.top--;
451+ *(L->stack.top-1) = *L->stack.top; /* remove extra s */
452+ return;
453+ }
454+ L->stack.top-=2; /* remove result and extra s */
455+ }
456+ }
457+}
458+
459+
460+static void luaB_getn (void) {
461+ lua_pushnumber(getnarg(gethash(1)));
462+}
463+
464+
465+static void luaB_tinsert (void) {
466+ Hash *a = gethash(1);
467+ lua_Object v = lua_getparam(3);
468+ int n = (int)getnarg(a);
469+ int pos;
470+ if (v != LUA_NOOBJECT)
471+ pos = luaL_check_int(2);
472+ else { /* called with only 2 arguments */
473+ v = luaL_nonnullarg(2);
474+ pos = n+1;
475+ }
476+ luaV_setn(a, n+1); /* a.n = n+1 */
477+ for ( ;n>=pos; n--)
478+ luaH_move(a, n, n+1); /* a[n+1] = a[n] */
479+ luaH_setint(a, pos, luaA_Address(v)); /* a[pos] = v */
480+}
481+
482+
483+static void luaB_tremove (void) {
484+ Hash *a = gethash(1);
485+ int n = (int)getnarg(a);
486+ int pos = luaL_opt_int(2, n);
487+ if (n <= 0) return; /* table is "empty" */
488+ luaA_pushobject(luaH_getint(a, pos)); /* result = a[pos] */
489+ for ( ;pos<n; pos++)
490+ luaH_move(a, pos+1, pos); /* a[pos] = a[pos+1] */
491+ luaV_setn(a, n-1); /* a.n = n-1 */
492+ luaH_setint(a, n, &luaO_nilobject); /* a[n] = nil */
384493 }
385494
386495
387−static void luaI_collectgarbage (void)
388−{
389− lua_pushnumber(lua_collectgarbage(luaL_opt_number(1, 0)));
496+/* {
497+** Quicksort
498+*/
499+
500+static void swap (Hash *a, int i, int j) {
501+ TObject temp;
502+ temp = *luaH_getint(a, i);
503+ luaH_move(a, j, i);
504+ luaH_setint(a, j, &temp);
505+}
506+
507+static int sort_comp (lua_Object f, TObject *a, TObject *b) {
508+ /* notice: the caller (auxsort) must check stack space */
509+ if (f != LUA_NOOBJECT) {
510+ *(L->stack.top) = *luaA_Address(f);
511+ *(L->stack.top+1) = *a;
512+ *(L->stack.top+2) = *b;
513+ L->stack.top += 3;
514+ luaD_calln(2, 1);
515+ }
516+ else { /* a < b? */
517+ *(L->stack.top) = *a;
518+ *(L->stack.top+1) = *b;
519+ L->stack.top += 2;
520+ luaV_comparison(LUA_T_NUMBER, LUA_T_NIL, LUA_T_NIL, IM_LT);
521+ }
522+ return ttype(--(L->stack.top)) != LUA_T_NIL;
523+}
524+
525+static void auxsort (Hash *a, int l, int u, lua_Object f) {
526+ while (l < u) { /* for tail recursion */
527+ TObject *P;
528+ int i, j;
529+ /* sort elements a[l], a[(l+u)/2] and a[u] */
530+ if (sort_comp(f, luaH_getint(a, u), luaH_getint(a, l))) /* a[l]>a[u]? */
531+ swap(a, l, u);
532+ if (u-l == 1) break; /* only 2 elements */
533+ i = (l+u)/2;
534+ P = luaH_getint(a, i);
535+ if (sort_comp(f, P, luaH_getint(a, l))) /* a[l]>a[i]? */
536+ swap(a, l, i);
537+ else if (sort_comp(f, luaH_getint(a, u), P)) /* a[i]>a[u]? */
538+ swap(a, i, u);
539+ if (u-l == 2) break; /* only 3 elements */
540+ P = L->stack.top++;
541+ *P = *luaH_getint(a, i); /* save pivot on stack (for GC) */
542+ swap(a, i, u-1); /* put median element as pivot (a[u-1]) */
543+ /* a[l] <= P == a[u-1] <= a[u], only needs to sort from l+1 to u-2 */
544+ i = l; j = u-1;
545+ for (;;) {
546+ /* invariant: a[l..i] <= P <= a[j..u] */
547+ while (sort_comp(f, luaH_getint(a, ++i), P)) /* stop when a[i] >= P */
548+ if (i>u) lua_error("invalid order function for sorting");
549+ while (sort_comp(f, P, luaH_getint(a, --j))) /* stop when a[j] <= P */
550+ if (j<l) lua_error("invalid order function for sorting");
551+ if (j<i) break;
552+ swap(a, i, j);
553+ }
554+ swap(a, u-1, i); /* swap pivot (a[u-1]) with a[i] */
555+ L->stack.top--; /* remove pivot from stack */
556+ /* a[l..i-1] <= a[i] == P <= a[i+1..u] */
557+ /* adjust so that smaller "half" is in [j..i] and larger one in [l..u] */
558+ if (i-l < u-i) {
559+ j=l; i=i-1; l=i+2;
560+ }
561+ else {
562+ j=i+1; i=u; u=j-2;
563+ }
564+ auxsort(a, j, i, f); /* call recursively the smaller one */
565+ } /* repeat the routine for the larger one */
566+}
567+
568+static void luaB_sort (void) {
569+ lua_Object t = lua_getparam(1);
570+ Hash *a = gethash(1);
571+ int n = (int)getnarg(a);
572+ lua_Object func = lua_getparam(2);
573+ luaL_arg_check(func == LUA_NOOBJECT || lua_isfunction(func), 2,
574+ "function expected");
575+ luaD_checkstack(4); /* for Pivot, f, a, b (sort_comp) */
576+ auxsort(a, 1, n, func);
577+ lua_pushobject(t);
390578 }
391579
580+/* }}===================================================== */
581+
392582
393583 /*
394−** =======================================================
584+** ====================================================== */
585+
586+
587+
588+#ifdef DEBUG
589+/*
590+** {======================================================
395591 ** some DEBUG functions
396592 ** =======================================================
397593 */
398−#ifdef DEBUG
399594
400−static void mem_query (void)
401−{
595+static void mem_query (void) {
402596 lua_pushnumber(totalmem);
403597 lua_pushnumber(numblocks);
404598 }
405599
406600
407−static void countlist (void)
408−{
601+static void query_strings (void) {
602+ lua_pushnumber(L->string_root[luaL_check_int(1)].nuse);
603+}
604+
605+
606+static void countlist (void) {
409607 char *s = luaL_check_string(1);
410608 GCnode *l = (s[0]=='t') ? L->roottable.next : (s[0]=='c') ? L->rootcl.next :
411609 (s[0]=='p') ? L->rootproto.next : L->rootglobal.next;
@@ -418,8 +616,7 @@ static void countlist (void) · 6 unmodified lines
418616 }
419617
420618
421−static void testC (void)
422−{
619+static void testC (void) {
423620 #define getnum(s) ((*s++) - '0')
424621 #define getname(s) (nome[0] = *s++, nome)
425622
@@ -428,7 +625,7 @@ static void testC (void) · 2 unmodified lines
428625 char nome[2];
429626 char *s = luaL_check_string(1);
430627 nome[1] = 0;
431− while (1) {
628+ for (;;) {
432629 switch (*s++) {
433630 case '0': case '1': case '2': case '3': case '4':
434631 case '5': case '6': case '7': case '8': case '9':
@@ -454,11 +651,17 @@ static void testC (void) · 19 unmodified lines
454651 case '=': lua_setglobal(getname(s)); break;
455652 case 's': lua_pushstring(getname(s)); break;
456653 case 'o': lua_pushobject(reg[getnum(s)]); break;
457− case 'f': (lua_call)(getname(s)); break;
654+ case 'f': lua_call(getname(s)); break;
458655 case 'i': reg[getnum(s)] = lua_gettable(); break;
459656 case 'I': reg[getnum(s)] = lua_rawgettable(); break;
460657 case 't': lua_settable(); break;
461658 case 'T': lua_rawsettable(); break;
659+ case 'N' : lua_pushstring(lua_nextvar(lua_getstring(reg[getnum(s)])));
660+ break;
661+ case 'n' : { int n=getnum(s);
662+ n=lua_next(reg[n], (int)lua_getnumber(reg[getnum(s)]));
663+ lua_pushnumber(n); break;
664+ }
462665 default: luaL_verror("unknown command in `testC': %c", *(s-1));
463666 }
464667 if (*s == 0) return;
@@ -466,13 +669,12 @@ static void testC (void) · 1 unmodified line
466669 }
467670 }
468671
672+/* }====================================================== */
469673 #endif
470674
471675
472−/*
473−** Internal functions
474−*/
475−static struct luaL_reg int_funcs[] = {
676+
677+static struct luaL_reg builtin_funcs[] = {
476678 #ifdef LUA_COMPAT2_5
477679 {"setfallback", luaT_setfallback},
478680 #endif
@@ -480,46 +682,54 @@ static struct luaL_reg int_funcs[] = { · 1 unmodified line
480682 {"testC", testC},
481683 {"totalmem", mem_query},
482684 {"count", countlist},
685+ {"querystr", query_strings},
483686 #endif
484− {"assert", luaI_assert},
485− {"call", luaI_call},
486− {"collectgarbage", luaI_collectgarbage},
487− {"dofile", internaldofile},
488− {"copytagmethods", copytagmethods},
489− {"dostring", internaldostring},
490− {"error", luaI_error},
491− {"foreach", foreach},
492− {"foreachvar", foreachvar},
493− {"getglobal", getglobal},
494− {"newtag", newtag},
495− {"next", next},
496− {"nextvar", nextvar},
497− {"print", luaI_print},
498− {"rawgetglobal", rawgetglobal},
499− {"rawgettable", rawgettable},
500− {"rawsetglobal", rawsetglobal},
501− {"rawsettable", rawsettable},
502− {"seterrormethod", seterrormethod},
503− {"setglobal", setglobal},
504− {"settagmethod", settagmethod},
505− {"gettagmethod", gettagmethod},
506− {"settag", settag},
507− {"tonumber", tonumber},
508− {"tostring", to_string},
509− {"tag", luatag},
510− {"type", luaI_type}
687+ {"_ALERT", luaB_alert},
688+ {"_ERRORMESSAGE", error_message},
689+ {"call", luaB_call},
690+ {"collectgarbage", luaB_collectgarbage},
691+ {"copytagmethods", luaB_copytagmethods},
692+ {"dofile", luaB_dofile},
693+ {"dostring", luaB_dostring},
694+ {"error", luaB_error},
695+ {"getglobal", luaB_getglobal},
696+ {"gettagmethod", luaB_gettagmethod},
697+ {"newtag", luaB_newtag},
698+ {"next", luaB_next},
699+ {"nextvar", luaB_nextvar},
700+ {"print", luaB_print},
701+ {"rawgetglobal", luaB_rawgetglobal},
702+ {"rawgettable", luaB_rawgettable},
703+ {"rawsetglobal", luaB_rawsetglobal},
704+ {"rawsettable", luaB_rawsettable},
705+ {"seterrormethod", luaB_seterrormethod},
706+ {"setglobal", luaB_setglobal},
707+ {"settag", luaB_settag},
708+ {"settagmethod", luaB_settagmethod},
709+ {"tag", luaB_luatag},
710+ {"tonumber", luaB_tonumber},
711+ {"tostring", luaB_tostring},
712+ {"type", luaB_type},
713+ /* "Extra" functions */
714+ {"assert", luaB_assert},
715+ {"foreach", luaB_foreach},
716+ {"foreachi", luaB_foreachi},
717+ {"foreachvar", luaB_foreachvar},
718+ {"getn", luaB_getn},
719+ {"sort", luaB_sort},
720+ {"tinsert", luaB_tinsert},
721+ {"tremove", luaB_tremove}
511722 };
512723
513724
514−#define INTFUNCSIZE (sizeof(int_funcs)/sizeof(int_funcs[0]))
725+#define INTFUNCSIZE (sizeof(builtin_funcs)/sizeof(builtin_funcs[0]))
515726
516727
517−void luaB_predefine (void)
518−{
728+void luaB_predefine (void) {
519729 /* pre-register mem error messages, to avoid loop when error arises */
520730 luaS_newfixedstring(tableEM);
521731 luaS_newfixedstring(memEM);
522− luaL_openlib(int_funcs, (sizeof(int_funcs)/sizeof(int_funcs[0])));
732+ luaL_openlib(builtin_funcs, (sizeof(builtin_funcs)/sizeof(builtin_funcs[0])));
523733 lua_pushstring(LUA_VERSION);
524734 lua_setglobal("_VERSION");
525735 }
src/ldo.c+90−132
@@ -1,5 +1,5 @@
11 /*
2−** $Id: ldo.c,v 1.27 1998/06/19 18:47:06 roberto Exp $
2+** $Id: ldo.c,v 1.45 1999/06/22 20:37:23 roberto Exp $
33 ** Stack and Call structure of Lua
44 ** See Copyright Notice in lua.h
55 */
@@ -10,6 +10,7 @@ · 4 unmodified lines
1010 #include <stdlib.h>
1111 #include <string.h>
1212
13+#include "lauxlib.h"
1314 #include "ldo.h"
1415 #include "lfunc.h"
1516 #include "lgc.h"
@@ -17,6 +18,7 @@ · 1 unmodified line
1718 #include "lobject.h"
1819 #include "lparser.h"
1920 #include "lstate.h"
21+#include "lstring.h"
2022 #include "ltm.h"
2123 #include "lua.h"
2224 #include "luadebug.h"
@@ -27,42 +29,33 @@ · 4 unmodified lines
2729
2830
2931 #ifndef STACK_LIMIT
30−#define STACK_LIMIT 6000
32+#define STACK_LIMIT 6000 /* arbitrary limit */
3133 #endif
3234
3335
3436
35−/*
36−** Error messages
37−*/
38−
39−static void stderrorim (void)
40−{
41− fprintf(stderr, "lua error: %s\n", lua_getstring(lua_getparam(1)));
42−}
43−
37+#define STACK_UNIT 128
4438
4539
46−#define STACK_UNIT 128
40+#ifdef DEBUG
41+#undef STACK_UNIT
42+#define STACK_UNIT 2
43+#endif
4744
4845
49−void luaD_init (void)
50−{
46+void luaD_init (void) {
5147 L->stack.stack = luaM_newvector(STACK_UNIT, TObject);
5248 L->stack.top = L->stack.stack;
5349 L->stack.last = L->stack.stack+(STACK_UNIT-1);
54− ttype(&L->errorim) = LUA_T_CPROTO;
55− fvalue(&L->errorim) = stderrorim;
5650 }
5751
5852
59−void luaD_checkstack (int n)
60−{
53+void luaD_checkstack (int n) {
6154 struct Stack *S = &L->stack;
6255 if (S->last-S->top <= n) {
6356 StkId top = S->top-S->stack;
64− int stacksize = (S->last-S->stack)+1+STACK_UNIT+n;
65− S->stack = luaM_reallocvector(S->stack, stacksize, TObject);
57+ int stacksize = (S->last-S->stack)+STACK_UNIT+n;
58+ luaM_reallocvector(S->stack, stacksize, TObject);
6659 S->last = S->stack+(stacksize-1);
6760 S->top = S->stack + top;
6861 if (stacksize >= STACK_LIMIT) { /* stack overflow? */
@@ -78,8 +71,7 @@ void luaD_checkstack (int n) · 9 unmodified lines
7871 /*
7972 ** Adjust stack. Set top to the given value, pushing NILs if needed.
8073 */
81−void luaD_adjusttop (StkId newtop)
82−{
74+void luaD_adjusttop (StkId newtop) {
8375 int diff = newtop-(L->stack.top-L->stack.stack);
8476 if (diff <= 0)
8577 L->stack.top += diff;
@@ -94,38 +86,35 @@ void luaD_adjusttop (StkId newtop) · 8 unmodified lines
9486 /*
9587 ** Open a hole below "nelems" from the L->stack.top.
9688 */
97−void luaD_openstack (int nelems)
98−{
89+void luaD_openstack (int nelems) {
9990 luaO_memup(L->stack.top-nelems+1, L->stack.top-nelems,
10091 nelems*sizeof(TObject));
10192 incr_top;
10293 }
10394
10495
105−void luaD_lineHook (int line)
106−{
96+void luaD_lineHook (int line) {
10797 struct C_Lua_Stack oldCLS = L->Cstack;
10898 StkId old_top = L->Cstack.lua2C = L->Cstack.base = L->stack.top-L->stack.stack;
10999 L->Cstack.num = 0;
110− (*lua_linehook)(line);
100+ (*L->linehook)(line);
111101 L->stack.top = L->stack.stack+old_top;
112102 L->Cstack = oldCLS;
113103 }
114104
115105
116−void luaD_callHook (StkId base, TProtoFunc *tf, int isreturn)
117−{
106+void luaD_callHook (StkId base, TProtoFunc *tf, int isreturn) {
118107 struct C_Lua_Stack oldCLS = L->Cstack;
119108 StkId old_top = L->Cstack.lua2C = L->Cstack.base = L->stack.top-L->stack.stack;
120109 L->Cstack.num = 0;
121110 if (isreturn)
122− (*lua_callhook)(LUA_NOOBJECT, "(return)", 0);
111+ (*L->callhook)(LUA_NOOBJECT, "(return)", 0);
123112 else {
124113 TObject *f = L->stack.stack+base-1;
125114 if (tf)
126− (*lua_callhook)(Ref(f), tf->fileName->str, tf->lineDefined);
115+ (*L->callhook)(Ref(f), tf->source->str, tf->lineDefined);
127116 else
128− (*lua_callhook)(Ref(f), "(C)", -1);
117+ (*L->callhook)(Ref(f), "(C)", -1);
129118 }
130119 L->stack.top = L->stack.stack+old_top;
131120 L->Cstack = oldCLS;
@@ -137,28 +126,26 @@ void luaD_callHook (StkId base, TProtoFunc *tf, int isreturn) · 5 unmodified lines
137126 ** Cstack.num is the number of arguments; Cstack.lua2C points to the
138127 ** first argument. Returns an index to the first result from C.
139128 */
140−static StkId callC (lua_CFunction f, StkId base)
141−{
142− struct C_Lua_Stack *CS = &L->Cstack;
143− struct C_Lua_Stack oldCLS = *CS;
129+static StkId callC (lua_CFunction f, StkId base) {
130+ struct C_Lua_Stack *cls = &L->Cstack;
131+ struct C_Lua_Stack oldCLS = *cls;
144132 StkId firstResult;
145133 int numarg = (L->stack.top-L->stack.stack) - base;
146− CS->num = numarg;
147− CS->lua2C = base;
148− CS->base = base+numarg; /* == top-stack */
149− if (lua_callhook)
134+ cls->num = numarg;
135+ cls->lua2C = base;
136+ cls->base = base+numarg; /* == top-stack */
137+ if (L->callhook)
150138 luaD_callHook(base, NULL, 0);
151139 (*f)(); /* do the actual call */
152− if (lua_callhook) /* func may have changed lua_callhook */
140+ if (L->callhook) /* func may have changed callhook */
153141 luaD_callHook(base, NULL, 1);
154− firstResult = CS->base;
155− *CS = oldCLS;
142+ firstResult = cls->base;
143+ *cls = oldCLS;
156144 return firstResult;
157145 }
158146
159147
160−static StkId callCclosure (struct Closure *cl, lua_CFunction f, StkId base)
161−{
148+static StkId callCclosure (struct Closure *cl, lua_CFunction f, StkId base) {
162149 TObject *pbase;
163150 int nup = cl->nelems; /* number of upvalues */
164151 luaD_checkstack(nup);
@@ -172,24 +159,25 @@ static StkId callCclosure (struct Closure *cl, lua_CFunction f, StkId base) · 7 unmodified lines
172159 }
173160
174161
175−void luaD_callTM (TObject *f, int nParams, int nResults)
176−{
162+void luaD_callTM (TObject *f, int nParams, int nResults) {
177163 luaD_openstack(nParams);
178164 *(L->stack.top-nParams-1) = *f;
179− luaD_call((L->stack.top-L->stack.stack)-nParams, nResults);
165+ luaD_calln(nParams, nResults);
180166 }
181167
182168
183169 /*
184−** Call a function (C or Lua). The parameters must be on the L->stack.stack,
185−** between [L->stack.stack+base,L->stack.top). The function to be called is at L->stack.stack+base-1.
186−** When returns, the results are on the L->stack.stack, between [L->stack.stack+base-1,L->stack.top).
170+** Call a function (C or Lua). The parameters must be on the stack,
171+** between [top-nArgs,top). The function to be called is right below the
172+** arguments.
173+** When returns, the results are on the stack, between [top-nArgs-1,top).
187174 ** The number of results is nResults, unless nResults=MULT_RET.
188175 */
189−void luaD_call (StkId base, int nResults)
190−{
176+void luaD_calln (int nArgs, int nResults) {
177+ struct Stack *S = &L->stack; /* to optimize */
178+ StkId base = (S->top-S->stack)-nArgs;
179+ TObject *func = S->stack+base-1;
191180 StkId firstResult;
192− TObject *func = L->stack.stack+base-1;
193181 int i;
194182 switch (ttype(func)) {
195183 case LUA_T_CPROTO:
@@ -214,23 +202,23 @@ void luaD_call (StkId base, int nResults) · 18 unmodified lines
214202 TObject *im = luaT_getimbyObj(func, IM_FUNCTION);
215203 if (ttype(im) == LUA_T_NIL)
216204 lua_error("call expression not a function");
217− luaD_callTM(im, (L->stack.top-L->stack.stack)-(base-1), nResults);
205+ luaD_callTM(im, (S->top-S->stack)-(base-1), nResults);
218206 return;
219207 }
220208 }
221209 /* adjust the number of results */
222− if (nResults != MULT_RET)
210+ if (nResults == MULT_RET)
211+ nResults = (S->top-S->stack)-firstResult;
212+ else
223213 luaD_adjusttop(firstResult+nResults);
224214 /* move results to base-1 (to erase parameters and function) */
225215 base--;
226− nResults = L->stack.top - (L->stack.stack+firstResult); /* actual number of results */
227216 for (i=0; i<nResults; i++)
228− *(L->stack.stack+base+i) = *(L->stack.stack+firstResult+i);
229− L->stack.top -= firstResult-base;
217+ *(S->stack+base+i) = *(S->stack+firstResult+i);
218+ S->top -= firstResult-base;
230219 }
231220
232221
233−
234222 /*
235223 ** Traverse all objects on L->stack.stack
236224 */
@@ -243,59 +231,50 @@ void luaD_travstack (int (*fn)(TObject *)) · 6 unmodified lines
243231
244232
245233
246−static void message (char *s)
247−{
248− TObject im = L->errorim;
249− if (ttype(&im) != LUA_T_NIL) {
234+static void message (char *s) {
235+ TObject *em = &(luaS_new("_ERRORMESSAGE")->u.s.globalval);
236+ if (ttype(em) == LUA_T_PROTO || ttype(em) == LUA_T_CPROTO ||
237+ ttype(em) == LUA_T_CLOSURE) {
238+ *L->stack.top = *em;
239+ incr_top;
250240 lua_pushstring(s);
251− luaD_callTM(&im, 1, 0);
241+ luaD_calln(1, 0);
252242 }
253243 }
254244
255245 /*
256246 ** Reports an error, and jumps up to the available recover label
257247 */
258−void lua_error (char *s)
259−{
248+void lua_error (char *s) {
260249 if (s) message(s);
261250 if (L->errorJmp)
262− longjmp(*((jmp_buf *)L->errorJmp), 1);
251+ longjmp(L->errorJmp->b, 1);
263252 else {
264− fprintf (stderr, "lua: exit(1). Unable to recover\n");
253+ message("exit(1). Unable to recover.\n");
265254 exit(1);
266255 }
267256 }
268257
269−/*
270−** Call the function at L->Cstack.base, and incorporate results on
271−** the Lua2C structure.
272−*/
273−static void do_callinc (int nResults)
274−{
275− StkId base = L->Cstack.base;
276− luaD_call(base+1, nResults);
277− L->Cstack.lua2C = base; /* position of the luaM_new results */
278− L->Cstack.num = (L->stack.top-L->stack.stack) - base; /* number of results */
279− L->Cstack.base = base + L->Cstack.num; /* incorporate results on L->stack.stack */
280−}
281−
282258
283259 /*
284260 ** Execute a protected call. Assumes that function is at L->Cstack.base and
285261 ** parameters are on top of it. Leave nResults on the stack.
286262 */
287−int luaD_protectedrun (int nResults)
288−{
289− jmp_buf myErrorJmp;
290− int status;
263+int luaD_protectedrun (void) {
291264 volatile struct C_Lua_Stack oldCLS = L->Cstack;
292− jmp_buf *volatile oldErr = L->errorJmp;
265+ struct lua_longjmp myErrorJmp;
266+ volatile int status;
267+ struct lua_longjmp *volatile oldErr = L->errorJmp;
293268 L->errorJmp = &myErrorJmp;
294− if (setjmp(myErrorJmp) == 0) {
295− do_callinc(nResults);
269+ if (setjmp(myErrorJmp.b) == 0) {
270+ StkId base = L->Cstack.base;
271+ luaD_calln((L->stack.top-L->stack.stack)-base-1, MULT_RET);
272+ L->Cstack.lua2C = base; /* position of the new results */
273+ L->Cstack.num = (L->stack.top-L->stack.stack) - base;
274+ L->Cstack.base = base + L->Cstack.num; /* incorporate results on stack */
296275 status = 0;
297276 }
298− else { /* an error occurred: restore L->Cstack and L->stack.top */
277+ else { /* an error occurred: restore L->Cstack and L->stack.top */
299278 L->Cstack = oldCLS;
300279 L->stack.top = L->stack.stack+L->Cstack.base;
301280 status = 1;
@@ -308,18 +287,20 @@ int luaD_protectedrun (int nResults) · 6 unmodified lines
308287 /*
309288 ** returns 0 = chunk loaded; 1 = error; 2 = no more chunks to load
310289 */
311−static int protectedparser (ZIO *z, int bin)
312−{
290+static int protectedparser (ZIO *z, int bin) {
291+ volatile struct C_Lua_Stack oldCLS = L->Cstack;
292+ struct lua_longjmp myErrorJmp;
313293 volatile int status;
314294 TProtoFunc *volatile tf;
315− jmp_buf myErrorJmp;
316− jmp_buf *volatile oldErr = L->errorJmp;
295+ struct lua_longjmp *volatile oldErr = L->errorJmp;
317296 L->errorJmp = &myErrorJmp;
318− if (setjmp(myErrorJmp) == 0) {
297+ if (setjmp(myErrorJmp.b) == 0) {
319298 tf = bin ? luaU_undump1(z) : luaY_parser(z);
320299 status = 0;
321300 }
322− else {
301+ else { /* an error occurred: restore L->Cstack and L->stack.top */
302+ L->Cstack = oldCLS;
303+ L->stack.top = L->stack.stack+L->Cstack.base;
323304 tf = NULL;
324305 status = 1;
325306 }
@@ -334,9 +315,9 @@ static int protectedparser (ZIO *z, int bin) · 8 unmodified lines
334315 }
335316
336317
337−static int do_main (ZIO *z, int bin)
338−{
318+static int do_main (ZIO *z, int bin) {
339319 int status;
320+ int debug = L->debug; /* save debug status */
340321 do {
341322 long old_blocks = (luaC_checkGC(), L->nblocks);
342323 status = protectedparser(z, bin);
@@ -345,10 +326,11 @@ static int do_main (ZIO *z, int bin) · 2 unmodified lines
345326 else {
346327 unsigned long newelems2 = 2*(L->nblocks-old_blocks);
347328 L->GCthreshold += newelems2;
348− status = luaD_protectedrun(MULT_RET);
329+ status = luaD_protectedrun();
349330 L->GCthreshold -= newelems2;
350331 }
351332 } while (bin && status == 0);
333+ L->debug = debug; /* restore debug status */
352334 return status;
353335 }
354336
@@ -364,23 +346,24 @@ void luaD_gcIM (TObject *o) · 9 unmodified lines
364346 }
365347
366348
367−int lua_dofile (char *filename)
368−{
349+#define MAXFILENAME 260 /* maximum part of a file name kept */
350+
351+int lua_dofile (char *filename) {
369352 ZIO z;
370353 int status;
371354 int c;
372355 int bin;
356+ char source[MAXFILENAME];
373357 FILE *f = (filename == NULL) ? stdin : fopen(filename, "r");
374358 if (f == NULL)
375359 return 2;
376− if (filename == NULL)
377− filename = "(stdin)";
378360 c = fgetc(f);
379361 ungetc(c, f);
380362 bin = (c == ID_CHUNK);
381363 if (bin)
382364 f = freopen(filename, "rb", f); /* set binary mode */
383− luaZ_Fopen(&z, f, filename);
365+ luaL_filesource(source, filename, sizeof(source));
366+ luaZ_Fopen(&z, f, source);
384367 status = do_main(&z, bin);
385368 if (f != stdin)
386369 fclose(f);
@@ -388,40 +371,15 @@ int lua_dofile (char *filename) · 1 unmodified line
388371 }
389372
390373
391−#define SIZE_PREF 20 /* size of string prefix to appear in error messages */
392−#define SSIZE_PREF "20"
393−
394−
395−static void build_name (char *str, char *name) {
396− if (str == NULL || *str == ID_CHUNK)
397− strcpy(name, "(buffer)");
398− else {
399− char *temp;
400− sprintf(name, "(dostring) >> \"%." SSIZE_PREF "s\"", str);
401− temp = strchr(name, '\n');
402− if (temp) { /* end string after first line */
403− *temp = '"';
404− *(temp+1) = 0;
405− }
406− }
407−}
408−
409−
410374 int lua_dostring (char *str) {
411− return lua_dobuffer(str, strlen(str), NULL);
375+ return lua_dobuffer(str, strlen(str), str);
412376 }
413377
414378
415379 int lua_dobuffer (char *buff, int size, char *name) {
416− char newname[SIZE_PREF+25];
417380 ZIO z;
418− int status;
419− if (name==NULL) {
420− build_name(buff, newname);
421− name = newname;
422− }
381+ if (!name) name = "?";
423382 luaZ_mopen(&z, buff, size, name);
424− status = do_main(&z, buff[0]==ID_CHUNK);
425− return status;
383+ return do_main(&z, buff[0]==ID_CHUNK);
426384 }
427385
src/ldo.h+3−3
@@ -1,5 +1,5 @@
11 /*
2−** $Id: ldo.h,v 1.4 1997/12/15 16:17:20 roberto Exp $
2+** $Id: ldo.h,v 1.6 1999/06/22 20:37:23 roberto Exp $
33 ** Stack and Call structure of Lua
44 ** See Copyright Notice in lua.h
55 */
@@ -35,9 +35,9 @@ void luaD_adjusttop (StkId newtop); · 29 unmodified lines
3535 void luaD_openstack (int nelems);
3636 void luaD_lineHook (int line);
3737 void luaD_callHook (StkId base, TProtoFunc *tf, int isreturn);
38−void luaD_call (StkId base, int nResults);
38+void luaD_calln (int nArgs, int nResults);
3939 void luaD_callTM (TObject *f, int nParams, int nResults);
40−int luaD_protectedrun (int nResults);
40+int luaD_protectedrun (void);
4141 void luaD_gcIM (TObject *o);
4242 void luaD_travstack (int (*fn)(TObject *));
4343 void luaD_checkstack (int n);
src/lfunc.c+2−2
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lfunc.c,v 1.9 1998/06/19 16:14:09 roberto Exp $
2+** $Id: lfunc.c,v 1.10 1999/03/04 21:17:26 roberto Exp $
33 ** Auxiliary functions to manipulate prototypes and closures
44 ** See Copyright Notice in lua.h
55 */
@@ -31,7 +31,7 @@ TProtoFunc *luaF_newproto (void) · 25 unmodified lines
3131 TProtoFunc *f = luaM_new(TProtoFunc);
3232 f->code = NULL;
3333 f->lineDefined = 0;
34− f->fileName = NULL;
34+ f->source = NULL;
3535 f->consts = NULL;
3636 f->nconsts = 0;
3737 f->locvars = NULL;
src/lgc.c+9−22
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lgc.c,v 1.18 1998/03/09 21:49:52 roberto Exp $
2+** $Id: lgc.c,v 1.23 1999/03/04 21:17:26 roberto Exp $
33 ** Garbage Collector
44 ** See Copyright Notice in lua.h
55 */
@@ -29,23 +29,18 @@ static int markobject (TObject *o); · 23 unmodified lines
2929 */
3030
3131
32−int luaC_ref (TObject *o, int lock)
33−{
32+int luaC_ref (TObject *o, int lock) {
3433 int ref;
3534 if (ttype(o) == LUA_T_NIL)
3635 ref = -1; /* special ref for nil */
3736 else {
3837 for (ref=0; ref<L->refSize; ref++)
3938 if (L->refArray[ref].status == FREE)
40− goto found;
41− /* no more empty spaces */ {
42− int oldSize = L->refSize;
43− L->refSize = luaM_growvector(&L->refArray, L->refSize, struct ref,
44− refEM, MAX_INT);
45− for (ref=oldSize; ref<L->refSize; ref++)
46− L->refArray[ref].status = FREE;
47− ref = oldSize;
48− } found:
39+ break;
40+ if (ref == L->refSize) { /* no more empty spaces? */
41+ luaM_growvector(L->refArray, L->refSize, 1, struct ref, refEM, MAX_INT);
42+ L->refSize++;
43+ }
4944 L->refArray[ref].o = *o;
5045 L->refArray[ref].status = lock ? LOCK : HOLD;
5146 }
@@ -163,21 +158,13 @@ static void strmark (TaggedString *s) · 111 unmodified lines
163158 }
164159
165160
166−static void protomark (TProtoFunc *f)
167−{
161+static void protomark (TProtoFunc *f) {
168162 if (!f->head.marked) {
169− LocVar *v = f->locvars;
170163 int i;
171164 f->head.marked = 1;
172− if (f->fileName)
173− strmark(f->fileName);
165+ strmark(f->source);
174166 for (i=0; i<f->nconsts; i++)
175167 markobject(&f->consts[i]);
176− if (v) {
177− for (; v->line != -1; v++)
178− if (v->varname)
179− strmark(v->varname);
180− }
181168 }
182169 }
183170
src/lib/Makefile+2−2
@@ -7,8 +7,8 @@ include $(LUA)/config · 6 unmodified lines
77 # actually only used in liolib.c
88 EXTRA_DEFS= $(POPEN)
99
10−OBJS= liolib.o lmathlib.o lstrlib.o
11−SRCS= liolib.c lmathlib.c lstrlib.c
10+OBJS= linit.o ldblib.o liolib.o lmathlib.o lstrlib.o
11+SRCS= linit.c ldblib.c liolib.c lmathlib.c lstrlib.c
1212
1313 T= $(LIB)/liblualib.a
1414
src/lib/ldblib.c+217−0
@@ -0,0 +1,217 @@
1+/*
2+** $Id: ldblib.c,v 1.5 1999/03/04 21:17:26 roberto Exp $
3+** Interface from Lua to its debug API
4+** See Copyright Notice in lua.h
5+*/
6+
7+
8+#include <stdlib.h>
9+#include <string.h>
10+
11+#include "lauxlib.h"
12+#include "lua.h"
13+#include "luadebug.h"
14+#include "lualib.h"
15+
16+
17+
18+static void settabss (lua_Object t, char *i, char *v) {
19+ lua_pushobject(t);
20+ lua_pushstring(i);
21+ lua_pushstring(v);
22+ lua_settable();
23+}
24+
25+
26+static void settabsi (lua_Object t, char *i, int v) {
27+ lua_pushobject(t);
28+ lua_pushstring(i);
29+ lua_pushnumber(v);
30+ lua_settable();
31+}
32+
33+
34+static lua_Object getfuncinfo (lua_Object func) {
35+ lua_Object result = lua_createtable();
36+ char *str;
37+ int line;
38+ lua_funcinfo(func, &str, &line);
39+ if (line == -1) /* C function? */
40+ settabss(result, "kind", "C");
41+ else if (line == 0) { /* "main"? */
42+ settabss(result, "kind", "chunk");
43+ settabss(result, "source", str);
44+ }
45+ else { /* Lua function */
46+ settabss(result, "kind", "Lua");
47+ settabsi(result, "def_line", line);
48+ settabss(result, "source", str);
49+ }
50+ if (line != 0) { /* is it not a "main"? */
51+ char *kind = lua_getobjname(func, &str);
52+ if (*kind) {
53+ settabss(result, "name", str);
54+ settabss(result, "where", kind);
55+ }
56+ }
57+ return result;
58+}
59+
60+
61+static void getstack (void) {
62+ lua_Object func = lua_stackedfunction(luaL_check_int(1));
63+ if (func == LUA_NOOBJECT) /* level out of range? */
64+ return;
65+ else {
66+ lua_Object result = getfuncinfo(func);
67+ int currline = lua_currentline(func);
68+ if (currline > 0)
69+ settabsi(result, "current", currline);
70+ lua_pushobject(result);
71+ lua_pushstring("func");
72+ lua_pushobject(func);
73+ lua_settable(); /* result.func = func */
74+ lua_pushobject(result);
75+ }
76+}
77+
78+
79+static void funcinfo (void) {
80+ lua_pushobject(getfuncinfo(luaL_functionarg(1)));
81+}
82+
83+
84+static int findlocal (lua_Object func, int arg) {
85+ lua_Object v = lua_getparam(arg);
86+ if (lua_isnumber(v))
87+ return (int)lua_getnumber(v);
88+ else {
89+ char *name = luaL_check_string(arg);
90+ int i = 0;
91+ int result = -1;
92+ char *vname;
93+ while (lua_getlocal(func, ++i, &vname) != LUA_NOOBJECT) {
94+ if (strcmp(name, vname) == 0)
95+ result = i; /* keep looping to get the last var with this name */
96+ }
97+ if (result == -1)
98+ luaL_verror("no local variable `%.50s' at given level", name);
99+ return result;
100+ }
101+}
102+
103+
104+static void getlocal (void) {
105+ lua_Object func = lua_stackedfunction(luaL_check_int(1));
106+ lua_Object val;
107+ char *name;
108+ if (func == LUA_NOOBJECT) /* level out of range? */
109+ return; /* return nil */
110+ else if (lua_getparam(2) != LUA_NOOBJECT) { /* 2nd argument? */
111+ if ((val = lua_getlocal(func, findlocal(func, 2), &name)) != LUA_NOOBJECT) {
112+ lua_pushobject(val);
113+ lua_pushstring(name);
114+ }
115+ /* else return nil */
116+ }
117+ else { /* collect all locals in a table */
118+ lua_Object result = lua_createtable();
119+ int i;
120+ for (i=1; ;i++) {
121+ if ((val = lua_getlocal(func, i, &name)) == LUA_NOOBJECT)
122+ break;
123+ lua_pushobject(result);
124+ lua_pushstring(name);
125+ lua_pushobject(val);
126+ lua_settable(); /* result[name] = value */
127+ }
128+ lua_pushobject(result);
129+ }
130+}
131+
132+
133+static void setlocal (void) {
134+ lua_Object func = lua_stackedfunction(luaL_check_int(1));
135+ int numvar;
136+ luaL_arg_check(func != LUA_NOOBJECT, 1, "level out of range");
137+ numvar = findlocal(func, 2);
138+ lua_pushobject(luaL_nonnullarg(3));
139+ if (!lua_setlocal(func, numvar))
140+ lua_error("no such local variable");
141+}
142+
143+
144+
145+static int linehook = -1; /* Lua reference to line hook function */
146+static int callhook = -1; /* Lua reference to call hook function */
147+
148+
149+static void dohook (int ref) {
150+ lua_LHFunction oldlinehook = lua_setlinehook(NULL);
151+ lua_CHFunction oldcallhook = lua_setcallhook(NULL);
152+ lua_callfunction(lua_getref(ref));
153+ lua_setlinehook(oldlinehook);
154+ lua_setcallhook(oldcallhook);
155+}
156+
157+
158+static void linef (int line) {
159+ lua_pushnumber(line);
160+ dohook(linehook);
161+}
162+
163+
164+static void callf (lua_Function func, char *file, int line) {
165+ if (func != LUA_NOOBJECT) {
166+ lua_pushobject(func);
167+ lua_pushstring(file);
168+ lua_pushnumber(line);
169+ }
170+ dohook(callhook);
171+}
172+
173+
174+static void setcallhook (void) {
175+ lua_Object f = lua_getparam(1);
176+ lua_unref(callhook);
177+ if (f == LUA_NOOBJECT) {
178+ callhook = -1;
179+ lua_setcallhook(NULL);
180+ }
181+ else {
182+ lua_pushobject(f);
183+ callhook = lua_ref(1);
184+ lua_setcallhook(callf);
185+ }
186+}
187+
188+
189+static void setlinehook (void) {
190+ lua_Object f = lua_getparam(1);
191+ lua_unref(linehook);
192+ if (f == LUA_NOOBJECT) {
193+ linehook = -1;
194+ lua_setlinehook(NULL);
195+ }
196+ else {
197+ lua_pushobject(f);
198+ linehook = lua_ref(1);
199+ lua_setlinehook(linef);
200+ }
201+}
202+
203+
204+static struct luaL_reg dblib[] = {
205+ {"funcinfo", funcinfo},
206+ {"getlocal", getlocal},
207+ {"getstack", getstack},
208+ {"setcallhook", setcallhook},
209+ {"setlinehook", setlinehook},
210+ {"setlocal", setlocal}
211+};
212+
213+
214+void lua_dblibopen (void) {
215+ luaL_openlib(dblib, (sizeof(dblib)/sizeof(dblib[0])));
216+}
217+
src/lib/linit.c+17−0
@@ -0,0 +1,17 @@
1+/*
2+** $Id: linit.c,v 1.1 1999/01/08 16:49:32 roberto Exp $
3+** Initialization of libraries for lua.c
4+** See Copyright Notice in lua.h
5+*/
6+
7+#include "lua.h"
8+#include "lualib.h"
9+
10+
11+void lua_userinit (void) {
12+ lua_iolibopen();
13+ lua_strlibopen();
14+ lua_mathlibopen();
15+ lua_dblibopen();
16+}
17+
src/lib/liolib.c+344−209
@@ -1,5 +1,5 @@
11 /*
2−** $Id: liolib.c,v 1.21 1998/06/18 17:04:28 roberto Exp $
2+** $Id: liolib.c,v 1.41 1999/06/23 13:48:39 roberto Exp $
33 ** Standard I/O (and system) library
44 ** See Copyright Notice in lua.h
55 */
@@ -20,6 +20,7 @@ · 14 unmodified lines
2020 #ifndef OLD_ANSI
2121 #include <locale.h>
2222 #else
23+/* no support for locale and for strerror: fake them */
2324 #define setlocale(a,b) 0
2425 #define LC_ALL 0
2526 #define LC_COLLATE 0
@@ -31,10 +32,12 @@ · 5 unmodified lines
3132 #endif
3233
3334
34−#define CLOSEDTAG 2
35−#define IOTAG 1
35+#define IOTAG 1
36+
37+#define FIRSTARG 2 /* 1st is upvalue */
38+
39+#define CLOSEDTAG(tag) ((tag)-1) /* assume that CLOSEDTAG = iotag-1 */
3640
37−#define FIRSTARG 3 /* 1st and 2nd are upvalues */
3841
3942 #define FINPUT "_INPUT"
4043 #define FOUTPUT "_OUTPUT"
@@ -43,262 +46,371 @@ · 2 unmodified lines
4346 #ifdef POPEN
4447 FILE *popen();
4548 int pclose();
49+#define CLOSEFILE(f) {if (pclose(f) == -1) fclose(f);}
4650 #else
51+/* no support for popen */
4752 #define popen(x,y) NULL /* that is, popen always fails */
48−#define pclose(x) (-1)
53+#define CLOSEFILE(f) {fclose(f);}
4954 #endif
5055
5156
52−static int gettag (int i)
53−{
54− return lua_getnumber(lua_getparam(i));
55−}
56−
5757
58−static void pushresult (int i)
59−{
58+static void pushresult (int i) {
6059 if (i)
6160 lua_pushuserdata(NULL);
6261 else {
6362 lua_pushnil();
6463 lua_pushstring(strerror(errno));
64+ lua_pushnumber(errno);
6565 }
6666 }
6767
6868
69−static int ishandler (lua_Object f)
70−{
69+/*
70+** {======================================================
71+** FILE Operations
72+** =======================================================
73+*/
74+
75+static int gettag (void) {
76+ return (int)lua_getnumber(lua_getparam(IOTAG));
77+}
78+
79+
80+static int ishandle (lua_Object f) {
7181 if (lua_isuserdata(f)) {
72− if (lua_tag(f) == gettag(CLOSEDTAG))
82+ int tag = gettag();
83+ if (lua_tag(f) == CLOSEDTAG(tag))
7384 lua_error("cannot access a closed file");
74− return lua_tag(f) == gettag(IOTAG);
85+ return lua_tag(f) == tag;
7586 }
7687 else return 0;
7788 }
7889
79−static FILE *getfile (char *name)
80−{
90+
91+static FILE *getfilebyname (char *name) {
8192 lua_Object f = lua_getglobal(name);
82− if (!ishandler(f))
93+ if (!ishandle(f))
8394 luaL_verror("global variable `%.50s' is not a file handle", name);
8495 return lua_getuserdata(f);
8596 }
8697
8798
88−static FILE *getfileparam (char *name, int *arg)
89−{
90− lua_Object f = lua_getparam(*arg);
91− if (ishandler(f)) {
99+static FILE *getfile (int arg) {
100+ lua_Object f = lua_getparam(arg);
101+ return (ishandle(f)) ? lua_getuserdata(f) : NULL;
102+}
103+
104+
105+static FILE *getnonullfile (int arg) {
106+ FILE *f = getfile(arg);
107+ luaL_arg_check(f, arg, "invalid file handle");
108+ return f;
109+}
110+
111+
112+static FILE *getfileparam (char *name, int *arg) {
113+ FILE *f = getfile(*arg);
114+ if (f) {
92115 (*arg)++;
93− return lua_getuserdata(f);
116+ return f;
94117 }
95118 else
96− return getfile(name);
119+ return getfilebyname(name);
120+}
121+
122+
123+static void closefile (FILE *f) {
124+ if (f != stdin && f != stdout) {
125+ int tag = gettag();
126+ CLOSEFILE(f);
127+ lua_pushusertag(f, tag);
128+ lua_settag(CLOSEDTAG(tag));
129+ }
130+}
131+
132+
133+static void io_close (void) {
134+ closefile(getnonullfile(FIRSTARG));
135+}
136+
137+
138+static void gc_close (void) {
139+ FILE *f = getnonullfile(FIRSTARG);
140+ if (f != stdin && f != stdout && f != stderr) {
141+ CLOSEFILE(f);
142+ }
97143 }
98144
99145
100−static void closefile (char *name)
101−{
102− FILE *f = getfile(name);
103− if (f == stdin || f == stdout) return;
104− if (pclose(f) == -1)
105− fclose(f);
106− lua_pushobject(lua_getglobal(name));
107− lua_settag(gettag(CLOSEDTAG));
146+static void io_open (void) {
147+ FILE *f = fopen(luaL_check_string(FIRSTARG), luaL_check_string(FIRSTARG+1));
148+ if (f) lua_pushusertag(f, gettag());
149+ else pushresult(0);
108150 }
109151
110152
111−static void setfile (FILE *f, char *name, int tag)
112−{
153+static void setfile (FILE *f, char *name, int tag) {
113154 lua_pushusertag(f, tag);
114155 lua_setglobal(name);
115156 }
116157
117158
118−static void setreturn (FILE *f, char *name)
119−{
120− int tag = gettag(IOTAG);
121− setfile(f, name, tag);
122− lua_pushusertag(f, tag);
159+static void setreturn (FILE *f, char *name) {
160+ if (f == NULL)
161+ pushresult(0);
162+ else {
163+ int tag = gettag();
164+ setfile(f, name, tag);
165+ lua_pushusertag(f, tag);
166+ }
123167 }
124168
125169
126−static void io_readfrom (void)
127−{
170+static void io_readfrom (void) {
128171 FILE *current;
129172 lua_Object f = lua_getparam(FIRSTARG);
130173 if (f == LUA_NOOBJECT) {
131− closefile(FINPUT);
174+ closefile(getfilebyname(FINPUT));
132175 current = stdin;
133176 }
134− else if (lua_tag(f) == gettag(IOTAG))
177+ else if (lua_tag(f) == gettag()) /* deprecated option */
135178 current = lua_getuserdata(f);
136179 else {
137180 char *s = luaL_check_string(FIRSTARG);
138181 current = (*s == '|') ? popen(s+1, "r") : fopen(s, "r");
139− if (current == NULL) {
140− pushresult(0);
141− return;
142− }
143182 }
144183 setreturn(current, FINPUT);
145184 }
146185
147186
148−static void io_writeto (void)
149−{
187+static void io_writeto (void) {
150188 FILE *current;
151189 lua_Object f = lua_getparam(FIRSTARG);
152190 if (f == LUA_NOOBJECT) {
153− closefile(FOUTPUT);
191+ closefile(getfilebyname(FOUTPUT));
154192 current = stdout;
155193 }
156− else if (lua_tag(f) == gettag(IOTAG))
194+ else if (lua_tag(f) == gettag()) /* deprecated option */
157195 current = lua_getuserdata(f);
158196 else {
159197 char *s = luaL_check_string(FIRSTARG);
160− current = (*s == '|') ? popen(s+1,"w") : fopen(s,"w");
161− if (current == NULL) {
162− pushresult(0);
163− return;
164− }
198+ current = (*s == '|') ? popen(s+1,"w") : fopen(s, "w");
165199 }
166200 setreturn(current, FOUTPUT);
167201 }
168202
169203
170−static void io_appendto (void)
171−{
172− char *s = luaL_check_string(FIRSTARG);
173− FILE *fp = fopen (s, "a");
174− if (fp != NULL)
175− setreturn(fp, FOUTPUT);
176− else
177− pushresult(0);
204+static void io_appendto (void) {
205+ FILE *current = fopen(luaL_check_string(FIRSTARG), "a");
206+ setreturn(current, FOUTPUT);
178207 }
179208
180209
210+
211+/*
212+** {======================================================
213+** READ
214+** =======================================================
215+*/
216+
217+
218+/*
219+** We cannot lookahead without need, because this can lock stdin.
220+** This flag signals when we need to read a next char.
221+*/
181222 #define NEED_OTHER (EOF-1) /* just some flag different from EOF */
182223
183224
184−static void read_until (FILE *f, int lim) {
185− int l = 0;
186− int c;
187− for (c = getc(f); c != EOF && c != lim; c = getc(f)) {
188− luaL_addchar(c);
189− l++;
225+static int read_pattern (FILE *f, char *p) {
226+ int inskip = 0; /* {skip} level */
227+ int c = NEED_OTHER;
228+ while (*p != '\0') {
229+ switch (*p) {
230+ case '{':
231+ inskip++;
232+ p++;
233+ continue;
234+ case '}':
235+ if (!inskip) lua_error("unbalanced braces in read pattern");
236+ inskip--;
237+ p++;
238+ continue;
239+ default: {
240+ char *ep = luaI_classend(p); /* get what is next */
241+ int m; /* match result */
242+ if (c == NEED_OTHER) c = getc(f);
243+ m = (c==EOF) ? 0 : luaI_singlematch(c, p, ep);
244+ if (m) {
245+ if (!inskip) luaL_addchar(c);
246+ c = NEED_OTHER;
247+ }
248+ switch (*ep) {
249+ case '+': /* repetition (1 or more) */
250+ if (!m) goto break_while; /* pattern fails? */
251+ /* else go through */
252+ case '*': /* repetition (0 or more) */
253+ while (m) { /* reads the same item until it fails */
254+ c = getc(f);
255+ m = (c==EOF) ? 0 : luaI_singlematch(c, p, ep);
256+ if (m && !inskip) luaL_addchar(c);
257+ }
258+ /* go through to continue reading the pattern */
259+ case '?': /* optional */
260+ p = ep+1; /* continues reading the pattern */
261+ continue;
262+ default:
263+ if (!m) goto break_while; /* pattern fails? */
264+ p = ep; /* else continues reading the pattern */
265+ }
266+ }
267+ }
268+ } break_while:
269+ if (c != NEED_OTHER) ungetc(c, f);
270+ return (*p == '\0');
271+}
272+
273+
274+static int read_number (FILE *f) {
275+ double d;
276+ if (fscanf(f, "%lf", &d) == 1) {
277+ lua_pushnumber(d);
278+ return 1;
190279 }
191− if (l > 0 || c == lim) /* read anything? */
192− lua_pushlstring(luaL_buffer(), l);
280+ else return 0; /* read fails */
281+}
282+
283+
284+#define HUNK_LINE 1024
285+#define HUNK_FILE BUFSIZ
286+
287+static int read_line (FILE *f) {
288+ /* equivalent to: return read_pattern(f, "[^\n]*{\n}"); */
289+ int n;
290+ char *b;
291+ do {
292+ b = luaL_openspace(HUNK_LINE);
293+ if (!fgets(b, HUNK_LINE, f)) return 0; /* read fails */
294+ n = strlen(b);
295+ luaL_addsize(n);
296+ } while (b[n-1] != '\n');
297+ luaL_addsize(-1); /* remove '\n' */
298+ return 1;
299+}
300+
301+
302+static void read_file (FILE *f) {
303+ /* equivalent to: return read_pattern(f, ".*"); */
304+ int n;
305+ do {
306+ char *b = luaL_openspace(HUNK_FILE);
307+ n = fread(b, sizeof(char), HUNK_FILE, f);
308+ luaL_addsize(n);
309+ } while (n==HUNK_FILE);
193310 }
194311
312+
195313 static void io_read (void) {
314+ static char *options[] = {"*n", "*l", "*a", ".*", "*w", NULL};
196315 int arg = FIRSTARG;
197316 FILE *f = getfileparam(FINPUT, &arg);
198− char *p = luaL_opt_string(arg, NULL);
199− luaL_resetbuffer();
200− if (p == NULL) /* default: read a line */
201− read_until(f, '\n');
202− else if (p[0] == '.' && p[1] == '*' && p[2] == 0) /* p = ".*" */
203− read_until(f, EOF);
204− else {
205− int l = 0; /* number of chars read in buffer */
206− int inskip = 0; /* to control {skips} */
207− int c = NEED_OTHER;
208− while (*p) {
209− switch (*p) {
210− case '{':
211− inskip++;
212− p++;
213− continue;
214− case '}':
215− if (inskip == 0)
216− lua_error("unbalanced braces in read pattern");
217− inskip--;
218− p++;
219− continue;
220− default: {
221− char *ep; /* get what is next */
222− int m; /* match result */
223− if (c == NEED_OTHER) c = getc(f);
224− if (c == EOF) {
225− luaI_singlematch(0, p, &ep); /* to set "ep" */
226− m = 0;
227− }
228− else {
229− m = luaI_singlematch(c, p, &ep);
230− if (m) {
231− if (inskip == 0) {
232− luaL_addchar(c);
233− l++;
234− }
235− c = NEED_OTHER;
236− }
237− }
238− switch (*ep) {
239− case '*': /* repetition */
240− if (!m) p = ep+1; /* else stay in (repeat) the same item */
241− continue;
242− case '?': /* optional */
243− p = ep+1; /* continues reading the pattern */
244− continue;
245− default:
246− if (m) p = ep; /* continues reading the pattern */
247− else
248− goto break_while; /* pattern fails */
249− }
250− }
251− }
252− } break_while:
253− if (c >= 0) /* not EOF nor NEED_OTHER? */
254− ungetc(c, f);
255− if (l > 0 || *p == 0) /* read something or did not fail? */
256− lua_pushlstring(luaL_buffer(), l);
257− }
317+ char *p = luaL_opt_string(arg++, "*l");
318+ do { /* repeat for each part */
319+ long l;
320+ int success;
321+ luaL_resetbuffer();
322+ switch (luaL_findstring(p, options)) {
323+ case 0: /* number */
324+ if (!read_number(f)) return; /* read fails */
325+ continue; /* number is already pushed; avoid the "pushstring" */
326+ case 1: /* line */
327+ success = read_line(f);
328+ break;
329+ case 2: case 3: /* file */
330+ read_file(f);
331+ success = 1; /* always success */
332+ break;
333+ case 4: /* word */
334+ success = read_pattern(f, "{%s*}%S+");
335+ break;
336+ default:
337+ success = read_pattern(f, p);
338+ }
339+ l = luaL_getsize();
340+ if (!success && l==0) return; /* read fails */
341+ lua_pushlstring(luaL_buffer(), l);
342+ } while ((p = luaL_opt_string(arg++, NULL)) != NULL);
258343 }
259344
345+/* }====================================================== */
346+
260347
261−static void io_write (void)
262−{
348+static void io_write (void) {
263349 int arg = FIRSTARG;
264350 FILE *f = getfileparam(FOUTPUT, &arg);
265351 int status = 1;
266352 char *s;
267353 long l;
268354 while ((s = luaL_opt_lstr(arg++, NULL, &l)) != NULL)
269− status = status && (fwrite(s, 1, l, f) == l);
355+ status = status && ((long)fwrite(s, 1, l, f) == l);
270356 pushresult(status);
271357 }
272358
273359
274−static void io_execute (void)
275−{
360+static void io_seek (void) {
361+ static int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
362+ static char *modenames[] = {"set", "cur", "end", NULL};
363+ FILE *f = getnonullfile(FIRSTARG);
364+ int op = luaL_findstring(luaL_opt_string(FIRSTARG+1, "cur"), modenames);
365+ long offset = luaL_opt_long(FIRSTARG+2, 0);
366+ luaL_arg_check(op != -1, FIRSTARG+1, "invalid mode");
367+ op = fseek(f, offset, mode[op]);
368+ if (op)
369+ pushresult(0); /* error */
370+ else
371+ lua_pushnumber(ftell(f));
372+}
373+
374+
375+static void io_flush (void) {
376+ FILE *f = getfile(FIRSTARG);
377+ luaL_arg_check(f || lua_getparam(FIRSTARG) == LUA_NOOBJECT, FIRSTARG,
378+ "invalid file handle");
379+ pushresult(fflush(f) == 0);
380+}
381+
382+/* }====================================================== */
383+
384+
385+/*
386+** {======================================================
387+** Other O.S. Operations
388+** =======================================================
389+*/
390+
391+static void io_execute (void) {
276392 lua_pushnumber(system(luaL_check_string(1)));
277393 }
278394
279395
280−static void io_remove (void)
281−{
396+static void io_remove (void) {
282397 pushresult(remove(luaL_check_string(1)) == 0);
283398 }
284399
285400
286−static void io_rename (void)
287−{
401+static void io_rename (void) {
288402 pushresult(rename(luaL_check_string(1),
289403 luaL_check_string(2)) == 0);
290404 }
291405
292406
293−static void io_tmpname (void)
294−{
407+static void io_tmpname (void) {
295408 lua_pushstring(tmpnam(NULL));
296409 }
297410
298411
299412
300−static void io_getenv (void)
301−{
413+static void io_getenv (void) {
302414 lua_pushstring(getenv(luaL_check_string(1))); /* if NULL push nil */
303415 }
304416
@@ -308,12 +420,11 @@ static void io_clock (void) { · 3 unmodified lines
308420 }
309421
310422
311−static void io_date (void)
312−{
313− time_t t;
314− struct tm *tm;
423+static void io_date (void) {
424+ char b[256];
315425 char *s = luaL_opt_string(1, "%c");
316− char b[BUFSIZ];
426+ struct tm *tm;
427+ time_t t;
317428 time(&t); tm = localtime(&t);
318429 if (strftime(b,sizeof(b),s,tm))
319430 lua_pushstring(b);
@@ -322,8 +433,7 @@ static void io_date (void) · 2 unmodified lines
322433 }
323434
324435
325−static void setloc (void)
326−{
436+static void setloc (void) {
327437 static int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY, LC_NUMERIC,
328438 LC_TIME};
329439 static char *catnames[] = {"all", "collate", "ctype", "monetary",
@@ -334,115 +444,140 @@ static void setloc (void) · 4 unmodified lines
334444 }
335445
336446
337−static void io_exit (void)
338−{
447+static void io_exit (void) {
339448 lua_Object o = lua_getparam(1);
340449 exit(lua_isnumber(o) ? (int)lua_getnumber(o) : 1);
341450 }
342451
452+/* }====================================================== */
453+
454+
343455
344−static void io_debug (void)
345−{
346− while (1) {
456+static void io_debug (void) {
457+ for (;;) {
347458 char buffer[250];
348459 fprintf(stderr, "lua_debug> ");
349− if (fgets(buffer, sizeof(buffer), stdin) == 0) return;
350− if (strcmp(buffer, "cont\n") == 0) return;
460+ if (fgets(buffer, sizeof(buffer), stdin) == 0 ||
461+ strcmp(buffer, "cont\n") == 0)
462+ return;
351463 lua_dostring(buffer);
352464 }
353465 }
354466
355467
356−static void lua_printstack (FILE *f)
357−{
468+
469+#define MESSAGESIZE 150
470+#define MAXMESSAGE (MESSAGESIZE*10)
471+
472+
473+#define MAXSRC 60
474+
475+
476+static void errorfb (void) {
477+ char buff[MAXMESSAGE];
358478 int level = 1; /* skip level 0 (it's this function) */
359479 lua_Object func;
480+ sprintf(buff, "lua error: %.200s\n", lua_getstring(lua_getparam(1)));
360481 while ((func = lua_stackedfunction(level++)) != LUA_NOOBJECT) {
361482 char *name;
362483 int currentline;
363− char *filename;
484+ char *chunkname;
485+ char buffchunk[MAXSRC];
364486 int linedefined;
365− lua_funcinfo(func, &filename, &linedefined);
366− fprintf(f, (level==2) ? "Active Stack:\n\t" : "\t");
487+ lua_funcinfo(func, &chunkname, &linedefined);
488+ luaL_chunkid(buffchunk, chunkname, sizeof(buffchunk));
489+ if (level == 2) strcat(buff, "Active Stack:\n");
490+ strcat(buff, " ");
491+ if (strlen(buff) > MAXMESSAGE-MESSAGESIZE) {
492+ strcat(buff, "...\n");
493+ break; /* buffer is full */
494+ }
367495 switch (*lua_getobjname(func, &name)) {
368496 case 'g':
369− fprintf(f, "function %s", name);
497+ sprintf(buff+strlen(buff), "function `%.50s'", name);
370498 break;
371499 case 't':
372− fprintf(f, "`%s' tag method", name);
500+ sprintf(buff+strlen(buff), "`%.50s' tag method", name);
373501 break;
374502 default: {
375503 if (linedefined == 0)
376− fprintf(f, "main of %s", filename);
504+ sprintf(buff+strlen(buff), "main of %.70s", buffchunk);
377505 else if (linedefined < 0)
378− fprintf(f, "%s", filename);
506+ sprintf(buff+strlen(buff), "%.70s", buffchunk);
379507 else
380− fprintf(f, "function (%s:%d)", filename, linedefined);
381− filename = NULL;
508+ sprintf(buff+strlen(buff), "function <%d:%.70s>",
509+ linedefined, buffchunk);
510+ chunkname = NULL;
382511 }
383512 }
384513 if ((currentline = lua_currentline(func)) > 0)
385− fprintf(f, " at line %d", currentline);
386− if (filename)
387− fprintf(f, " [in file %s]", filename);
388− fprintf(f, "\n");
514+ sprintf(buff+strlen(buff), " at line %d", currentline);
515+ if (chunkname)
516+ sprintf(buff+strlen(buff), " [%.70s]", buffchunk);
517+ strcat(buff, "\n");
518+ }
519+ func = lua_rawgetglobal("_ALERT");
520+ if (lua_isfunction(func)) { /* avoid error loop if _ALERT is not defined */
521+ lua_pushstring(buff);
522+ lua_callfunction(func);
389523 }
390−}
391−
392−
393−static void errorfb (void)
394−{
395− fprintf(stderr, "lua: %s\n", lua_getstring(lua_getparam(1)));
396− lua_printstack(stderr);
397524 }
398525
399526
400527
401528 static struct luaL_reg iolib[] = {
402−{"setlocale", setloc},
403−{"execute", io_execute},
404−{"remove", io_remove},
405−{"rename", io_rename},
406−{"tmpname", io_tmpname},
407−{"getenv", io_getenv},
408−{"date", io_date},
409−{"clock", io_clock},
410−{"exit", io_exit},
411−{"debug", io_debug},
412−{"print_stack", errorfb}
529+ {"_ERRORMESSAGE", errorfb},
530+ {"clock", io_clock},
531+ {"date", io_date},
532+ {"debug", io_debug},
533+ {"execute", io_execute},
534+ {"exit", io_exit},
535+ {"getenv", io_getenv},
536+ {"remove", io_remove},
537+ {"rename", io_rename},
538+ {"setlocale", setloc},
539+ {"tmpname", io_tmpname}
413540 };
414541
542+
415543 static struct luaL_reg iolibtag[] = {
416−{"readfrom", io_readfrom},
417−{"writeto", io_writeto},
418−{"appendto", io_appendto},
419−{"read", io_read},
420−{"write", io_write}
544+ {"appendto", io_appendto},
545+ {"closefile", io_close},
546+ {"flush", io_flush},
547+ {"openfile", io_open},
548+ {"read", io_read},
549+ {"readfrom", io_readfrom},
550+ {"seek", io_seek},
551+ {"write", io_write},
552+ {"writeto", io_writeto}
421553 };
422554
423−static void openwithtags (void)
424−{
425− int iotag = lua_newtag();
426− int closedtag = lua_newtag();
555+
556+static void openwithtags (void) {
427557 int i;
558+ int iotag = lua_newtag();
559+ lua_newtag(); /* alloc CLOSEDTAG: assume that CLOSEDTAG = iotag-1 */
428560 for (i=0; i<sizeof(iolibtag)/sizeof(iolibtag[0]); i++) {
429− /* put both tags as upvalues for these functions */
561+ /* put iotag as upvalue for these functions */
430562 lua_pushnumber(iotag);
431− lua_pushnumber(closedtag);
432− lua_pushcclosure(iolibtag[i].func, 2);
563+ lua_pushcclosure(iolibtag[i].func, 1);
433564 lua_setglobal(iolibtag[i].name);
434565 }
566+ /* predefined file handles */
435567 setfile(stdin, FINPUT, iotag);
436568 setfile(stdout, FOUTPUT, iotag);
437569 setfile(stdin, "_STDIN", iotag);
438570 setfile(stdout, "_STDOUT", iotag);
439571 setfile(stderr, "_STDERR", iotag);
572+ /* close file when collected */
573+ lua_pushnumber(iotag);
574+ lua_pushcclosure(gc_close, 1);
575+ lua_settagmethod(iotag, "gc");
440576 }
441577
442−void lua_iolibopen (void)
443−{
578+void lua_iolibopen (void) {
579+ /* register lib functions */
444580 luaL_openlib(iolib, (sizeof(iolib)/sizeof(iolib[0])));
445581 openwithtags();
446− lua_pushcfunction(errorfb);
447− lua_seterrormethod();
448582 }
583+
src/lib/lmathlib.c+57−67
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lmathlib.c,v 1.10 1998/06/19 16:14:09 roberto Exp $
2+** $Id: lmathlib.c,v 1.17 1999/07/07 17:54:08 roberto Exp $
33 ** Lua standard mathematical library
44 ** See Copyright Notice in lua.h
55 */
@@ -12,107 +12,96 @@ · 6 unmodified lines
1212 #include "lua.h"
1313 #include "lualib.h"
1414
15−#ifdef M_PI
16−#define PI M_PI
17−#else
18−#define PI ((double)3.14159265358979323846)
19−#endif
2015
16+#undef PI
17+#define PI (3.14159265358979323846)
18+#define RADIANS_PER_DEGREE (PI/180.0)
2119
22−#define FROMRAD(a) ((a)*(180.0/PI))
23−#define TORAD(a) ((a)*(PI/180.0))
2420
2521
26−static void math_abs (void)
27−{
28− double d = luaL_check_number(1);
29− if (d < 0) d = -d;
30− lua_pushnumber(d);
22+/*
23+** If you want Lua to operate in radians (instead of degrees),
24+** define RADIANS
25+*/
26+#ifdef RADIANS
27+#define FROMRAD(a) (a)
28+#define TORAD(a) (a)
29+#else
30+#define FROMRAD(a) ((a)/RADIANS_PER_DEGREE)
31+#define TORAD(a) ((a)*RADIANS_PER_DEGREE)
32+#endif
33+
34+
35+static void math_abs (void) {
36+ lua_pushnumber(fabs(luaL_check_number(1)));
3137 }
3238
33−static void math_sin (void)
34−{
39+static void math_sin (void) {
3540 lua_pushnumber(sin(TORAD(luaL_check_number(1))));
3641 }
3742
38−static void math_cos (void)
39−{
43+static void math_cos (void) {
4044 lua_pushnumber(cos(TORAD(luaL_check_number(1))));
4145 }
4246
43−static void math_tan (void)
44−{
47+static void math_tan (void) {
4548 lua_pushnumber(tan(TORAD(luaL_check_number(1))));
4649 }
4750
48−static void math_asin (void)
49−{
51+static void math_asin (void) {
5052 lua_pushnumber(FROMRAD(asin(luaL_check_number(1))));
5153 }
5254
53−static void math_acos (void)
54−{
55+static void math_acos (void) {
5556 lua_pushnumber(FROMRAD(acos(luaL_check_number(1))));
5657 }
5758
58−static void math_atan (void)
59−{
59+static void math_atan (void) {
6060 lua_pushnumber(FROMRAD(atan(luaL_check_number(1))));
6161 }
6262
63−static void math_atan2 (void)
64−{
63+static void math_atan2 (void) {
6564 lua_pushnumber(FROMRAD(atan2(luaL_check_number(1), luaL_check_number(2))));
6665 }
6766
68−static void math_ceil (void)
69−{
67+static void math_ceil (void) {
7068 lua_pushnumber(ceil(luaL_check_number(1)));
7169 }
7270
73−static void math_floor (void)
74−{
71+static void math_floor (void) {
7572 lua_pushnumber(floor(luaL_check_number(1)));
7673 }
7774
78−static void math_mod (void)
79−{
75+static void math_mod (void) {
8076 lua_pushnumber(fmod(luaL_check_number(1), luaL_check_number(2)));
8177 }
8278
83−static void math_sqrt (void)
84−{
79+static void math_sqrt (void) {
8580 lua_pushnumber(sqrt(luaL_check_number(1)));
8681 }
8782
88−static void math_pow (void)
89−{
83+static void math_pow (void) {
9084 lua_pushnumber(pow(luaL_check_number(1), luaL_check_number(2)));
9185 }
9286
93−static void math_log (void)
94−{
87+static void math_log (void) {
9588 lua_pushnumber(log(luaL_check_number(1)));
9689 }
9790
98−static void math_log10 (void)
99−{
91+static void math_log10 (void) {
10092 lua_pushnumber(log10(luaL_check_number(1)));
10193 }
10294
103−static void math_exp (void)
104−{
95+static void math_exp (void) {
10596 lua_pushnumber(exp(luaL_check_number(1)));
10697 }
10798
108−static void math_deg (void)
109−{
110− lua_pushnumber(luaL_check_number(1)*(180.0/PI));
99+static void math_deg (void) {
100+ lua_pushnumber(luaL_check_number(1)/RADIANS_PER_DEGREE);
111101 }
112102
113−static void math_rad (void)
114−{
115− lua_pushnumber(luaL_check_number(1)*(PI/180.0));
103+static void math_rad (void) {
104+ lua_pushnumber(luaL_check_number(1)*RADIANS_PER_DEGREE);
116105 }
117106
118107 static void math_frexp (void) {
@@ -122,13 +111,12 @@ static void math_frexp (void) { · 3 unmodified lines
122111 }
123112
124113 static void math_ldexp (void) {
125− lua_pushnumber(ldexp(luaL_check_number(1), luaL_check_number(2)));
114+ lua_pushnumber(ldexp(luaL_check_number(1), luaL_check_int(2)));
126115 }
127116
128117
129118
130−static void math_min (void)
131−{
119+static void math_min (void) {
132120 int i = 1;
133121 double dmin = luaL_check_number(i);
134122 while (lua_getparam(++i) != LUA_NOOBJECT) {
@@ -140,8 +128,7 @@ static void math_min (void) · 5 unmodified lines
140128 }
141129
142130
143−static void math_max (void)
144−{
131+static void math_max (void) {
145132 int i = 1;
146133 double dmax = luaL_check_number(i);
147134 while (lua_getparam(++i) != LUA_NOOBJECT) {
@@ -153,22 +140,27 @@ static void math_max (void) · 5 unmodified lines
153140 }
154141
155142
156−static void math_random (void)
157−{
158− /* the '%' is needed because on some systems (SunOS!) "rand()" may */
159− /* return a value bigger than RAND_MAX... */
143+static void math_random (void) {
144+ /* the '%' avoids the (rare) case of r==1, and is needed also because on
145+ some systems (SunOS!) "rand()" may return a value bigger than RAND_MAX */
160146 double r = (double)(rand()%RAND_MAX) / (double)RAND_MAX;
161− double l = luaL_opt_number(1, 0);
147+ int l = luaL_opt_int(1, 0);
162148 if (l == 0)
163149 lua_pushnumber(r);
164− else
165− lua_pushnumber((int)(r*l)+1);
150+ else {
151+ int u = luaL_opt_int(2, 0);
152+ if (u == 0) {
153+ u = l;
154+ l = 1;
155+ }
156+ luaL_arg_check(l<=u, 1, "interval is empty");
157+ lua_pushnumber((int)(r*(u-l+1))+l);
158+ }
166159 }
167160
168161
169−static void math_randomseed (void)
170−{
171− srand(luaL_check_number(1));
162+static void math_randomseed (void) {
163+ srand(luaL_check_int(1));
172164 }
173165
174166
@@ -201,10 +193,8 @@ static struct luaL_reg mathlib[] = { · 26 unmodified lines
201193 /*
202194 ** Open math library
203195 */
204−void lua_mathlibopen (void)
205−{
196+void lua_mathlibopen (void) {
206197 luaL_openlib(mathlib, (sizeof(mathlib)/sizeof(mathlib[0])));
207− lua_pushstring("deg"); lua_setglobal("_TRIGMODE");
208198 lua_pushcfunction(math_pow);
209199 lua_pushnumber(0); /* to get its tag */
210200 lua_settagmethod(lua_tag(lua_pop()), "pow");
src/lib/lstrlib.c+230−177
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lstrlib.c,v 1.18 1998/07/01 14:21:57 roberto Exp $
2+** $Id: lstrlib.c,v 1.32 1999/06/17 17:04:03 roberto Exp $
33 ** Standard library for strings and pattern-matching
44 ** See Copyright Notice in lua.h
55 */
@@ -32,33 +32,31 @@ static void str_len (void) · 26 unmodified lines
3232 }
3333
3434
35−static void closeandpush (void)
36−{
35+static void closeandpush (void) {
3736 lua_pushlstring(luaL_buffer(), luaL_getsize());
3837 }
3938
4039
41−static long posrelat (long pos, long len)
42−{
40+static long posrelat (long pos, long len) {
4341 /* relative string position: negative means back from end */
4442 return (pos>=0) ? pos : len+pos+1;
4543 }
4644
4745
48−static void str_sub (void)
49−{
46+static void str_sub (void) {
5047 long l;
5148 char *s = luaL_check_lstr(1, &l);
52− long start = posrelat(luaL_check_number(2), l);
53− long end = posrelat(luaL_opt_number(3, -1), l);
54− if (1 <= start && start <= end && end <= l)
49+ long start = posrelat(luaL_check_long(2), l);
50+ long end = posrelat(luaL_opt_long(3, -1), l);
51+ if (start < 1) start = 1;
52+ if (end > l) end = l;
53+ if (start <= end)
5554 lua_pushlstring(s+start-1, end-start+1);
5655 else lua_pushstring("");
5756 }
5857
5958
60−static void str_lower (void)
61−{
59+static void str_lower (void) {
6260 long l;
6361 int i;
6462 char *s = luaL_check_lstr(1, &l);
@@ -69,8 +67,7 @@ static void str_lower (void) · 4 unmodified lines
6967 }
7068
7169
72−static void str_upper (void)
73−{
70+static void str_upper (void) {
7471 long l;
7572 int i;
7673 char *s = luaL_check_lstr(1, &l);
@@ -84,7 +81,7 @@ static void str_rep (void) · 7 unmodified lines
8481 {
8582 long l;
8683 char *s = luaL_check_lstr(1, &l);
87− int n = (int)luaL_check_number(2);
84+ int n = luaL_check_int(2);
8885 luaL_resetbuffer();
8986 while (n-- > 0)
9087 addnchar(s, l);
@@ -92,38 +89,42 @@ static void str_rep (void) · 1 unmodified line
9289 }
9390
9491
95−static void str_byte (void)
96−{
92+static void str_byte (void) {
9793 long l;
9894 char *s = luaL_check_lstr(1, &l);
99− long pos = posrelat(luaL_opt_number(2, 1), l);
95+ long pos = posrelat(luaL_opt_long(2, 1), l);
10096 luaL_arg_check(0<pos && pos<=l, 2, "out of range");
10197 lua_pushnumber((unsigned char)s[pos-1]);
10298 }
10399
100+
104101 static void str_char (void) {
105102 int i = 0;
106103 luaL_resetbuffer();
107104 while (lua_getparam(++i) != LUA_NOOBJECT) {
108105 double c = luaL_check_number(i);
109106 luaL_arg_check((unsigned char)c == c, i, "invalid value");
110− luaL_addchar((int)c);
107+ luaL_addchar((unsigned char)c);
111108 }
112109 closeandpush();
113110 }
114111
115112
113+
116114 /*
117−** =======================================================
115+** {======================================================
118116 ** PATTERN MATCHING
119117 ** =======================================================
120118 */
121119
122−#define MAX_CAPT 9
120+#ifndef MAX_CAPT
121+#define MAX_CAPT 32 /* arbitrary limit */
122+#endif
123+
123124
124125 struct Capture {
125− int level; /* total number of captures (finished or unfinished) */
126126 char *src_end; /* end ('\0') of source string */
127+ int level; /* total number of captures (finished or unfinished) */
127128 struct {
128129 char *init;
129130 int len; /* -1 signals unfinished capture */
@@ -132,19 +133,20 @@ struct Capture { · 2 unmodified lines
132133
133134
134135 #define ESC '%'
135−#define SPECIALS "^$*?.([%-"
136+#define SPECIALS "^$*+?.([%-"
136137
137138
138−static void push_captures (struct Capture *cap)
139−{
139+static void push_captures (struct Capture *cap) {
140140 int i;
141− for (i=0; i<cap->level; i++)
142− lua_pushlstring(cap->capture[i].init, cap->capture[i].len);
141+ for (i=0; i<cap->level; i++) {
142+ int l = cap->capture[i].len;
143+ if (l == -1) lua_error("unfinished capture");
144+ lua_pushlstring(cap->capture[i].init, l);
145+ }
143146 }
144147
145148
146−static int check_cap (int l, struct Capture *cap)
147−{
149+static int check_cap (int l, struct Capture *cap) {
148150 l -= '1';
149151 if (!(0 <= l && l < cap->level && cap->capture[l].len != -1))
150152 lua_error("invalid capture index");
@@ -152,8 +154,7 @@ static int check_cap (int l, struct Capture *cap) · 1 unmodified line
152154 }
153155
154156
155−static int capture_to_close (struct Capture *cap)
156−{
157+static int capture_to_close (struct Capture *cap) {
157158 int level = cap->level;
158159 for (level--; level>=0; level--)
159160 if (cap->capture[level].len == -1) return level;
@@ -162,14 +163,25 @@ static int capture_to_close (struct Capture *cap) · 2 unmodified lines
162163 }
163164
164165
165−static char *bracket_end (char *p)
166−{
167− return (*p == 0) ? NULL : strchr((*p=='^') ? p+2 : p+1, ']');
166+char *luaI_classend (char *p) {
167+ switch (*p++) {
168+ case ESC:
169+ if (*p == '\0')
170+ luaL_verror("incorrect pattern (ends with `%c')", ESC);
171+ return p+1;
172+ case '[':
173+ if (*p == '^') p++;
174+ if (*p == ']') p++;
175+ p = strchr(p, ']');
176+ if (!p) lua_error("incorrect pattern (missing `]')");
177+ return p+1;
178+ default:
179+ return p;
180+ }
168181 }
169182
170183
171−static int matchclass (int c, int cl)
172−{
184+static int matchclass (int c, int cl) {
173185 int res;
174186 switch (tolower(cl)) {
175187 case 'a' : res = isalpha(c); break;
@@ -180,57 +192,63 @@ static int matchclass (int c, int cl) · 4 unmodified lines
180192 case 's' : res = isspace(c); break;
181193 case 'u' : res = isupper(c); break;
182194 case 'w' : res = isalnum(c); break;
195+ case 'x' : res = isxdigit(c); break;
183196 case 'z' : res = (c == '\0'); break;
184197 default: return (cl == c);
185198 }
186− return (islower((unsigned char)cl) ? res : !res);
199+ return (islower(cl) ? res : !res);
187200 }
188201
189202
190−int luaI_singlematch (int c, char *p, char **ep)
191−{
203+
204+static int matchbracketclass (int c, char *p, char *end) {
205+ int sig = 1;
206+ if (*(p+1) == '^') {
207+ sig = 0;
208+ p++; /* skip the '^' */
209+ }
210+ while (++p < end) {
211+ if (*p == ESC) {
212+ p++;
213+ if ((p < end) && matchclass(c, (unsigned char)*p))
214+ return sig;
215+ }
216+ else if ((*(p+1) == '-') && (p+2 < end)) {
217+ p+=2;
218+ if ((int)(unsigned char)*(p-2) <= c && c <= (int)(unsigned char)*p)
219+ return sig;
220+ }
221+ else if ((unsigned char)*p == c) return sig;
222+ }
223+ return !sig;
224+}
225+
226+
227+
228+int luaI_singlematch (int c, char *p, char *ep) {
192229 switch (*p) {
193230 case '.': /* matches any char */
194− *ep = p+1;
195231 return 1;
196− case '\0': /* end of pattern; matches nothing */
197− *ep = p;
198− return 0;
199232 case ESC:
200− if (*(++p) == '\0')
201− luaL_verror("incorrect pattern (ends with `%c')", ESC);
202− *ep = p+1;
203− return matchclass(c, (unsigned char)*p);
204− case '[': {
205− char *end = bracket_end(p+1);
206− int sig = *(p+1) == '^' ? (p++, 0) : 1;
207− if (end == NULL) lua_error("incorrect pattern (missing `]')");
208− *ep = end+1;
209− while (++p < end) {
210− if (*p == ESC) {
211− if (((p+1) < end) && matchclass(c, (unsigned char)*++p))
212− return sig;
213− }
214− else if ((*(p+1) == '-') && (p+2 < end)) {
215− p+=2;
216− if ((unsigned char)*(p-2) <= c && c <= (unsigned char)*p)
217− return sig;
218− }
219− else if ((unsigned char)*p == c) return sig;
220− }
221− return !sig;
222− }
233+ return matchclass(c, (unsigned char)*(p+1));
234+ case '[':
235+ return matchbracketclass(c, p, ep-1);
223236 default:
224− *ep = p+1;
225237 return ((unsigned char)*p == c);
226238 }
227239 }
228240
229241
230−static char *matchbalance (char *s, int b, int e, struct Capture *cap)
231−{
232− if (*s != b) return NULL;
242+static char *match (char *s, char *p, struct Capture *cap);
243+
244+
245+static char *matchbalance (char *s, char *p, struct Capture *cap) {
246+ if (*p == 0 || *(p+1) == 0)
247+ lua_error("unbalanced pattern");
248+ if (*s != *p) return NULL;
233249 else {
250+ int b = *p;
251+ int e = *(p+1);
234252 int cont = 1;
235253 while (++s < cap->src_end) {
236254 if (*s == e) {
@@ -243,101 +261,120 @@ static char *matchbalance (char *s, int b, int e, struct Capture *cap) · 6 unmodified lines
243261 }
244262
245263
246−static char *matchitem (char *s, char *p, struct Capture *cap, char **ep)
247−{
248− if (*p == ESC) {
249− p++;
250− if (isdigit((unsigned char)*p)) { /* capture */
251− int l = check_cap(*p, cap);
252− int len = cap->capture[l].len;
253− *ep = p+1;
254− if (cap->src_end-s >= len && memcmp(cap->capture[l].init, s, len) == 0)
255− return s+len;
256− else return NULL;
257− }
258− else if (*p == 'b') { /* balanced string */
259− p++;
260− if (*p == 0 || *(p+1) == 0)
261− lua_error("unbalanced pattern");
262− *ep = p+2;
263− return matchbalance(s, *p, *(p+1), cap);
264− }
265− else p--; /* and go through */
264+static char *max_expand (char *s, char *p, char *ep, struct Capture *cap) {
265+ int i = 0; /* counts maximum expand for item */
266+ while ((s+i)<cap->src_end && luaI_singlematch((unsigned char)*(s+i), p, ep))
267+ i++;
268+ /* keeps trying to match mith the maximum repetitions */
269+ while (i>=0) {
270+ char *res = match((s+i), ep+1, cap);
271+ if (res) return res;
272+ i--; /* else didn't match; reduce 1 repetition to try again */
266273 }
267− /* "luaI_singlematch" sets "ep" (so must be called even when *s == 0) */
268− return (luaI_singlematch((unsigned char)*s, p, ep) && s<cap->src_end) ?
269− s+1 : NULL;
274+ return NULL;
270275 }
271276
272277
273−static char *match (char *s, char *p, struct Capture *cap)
274−{
278+static char *min_expand (char *s, char *p, char *ep, struct Capture *cap) {
279+ for (;;) {
280+ char *res = match(s, ep+1, cap);
281+ if (res != NULL)
282+ return res;
283+ else if (s<cap->src_end && luaI_singlematch((unsigned char)*s, p, ep))
284+ s++; /* try with one more repetition */
285+ else return NULL;
286+ }
287+}
288+
289+
290+static char *start_capt (char *s, char *p, struct Capture *cap) {
291+ char *res;
292+ int level = cap->level;
293+ if (level >= MAX_CAPT) lua_error("too many captures");
294+ cap->capture[level].init = s;
295+ cap->capture[level].len = -1;
296+ cap->level = level+1;
297+ if ((res=match(s, p+1, cap)) == NULL) /* match failed? */
298+ cap->level--; /* undo capture */
299+ return res;
300+}
301+
302+
303+static char *end_capt (char *s, char *p, struct Capture *cap) {
304+ int l = capture_to_close(cap);
305+ char *res;
306+ cap->capture[l].len = s - cap->capture[l].init; /* close capture */
307+ if ((res = match(s, p+1, cap)) == NULL) /* match failed? */
308+ cap->capture[l].len = -1; /* undo capture */
309+ return res;
310+}
311+
312+
313+static char *match_capture (char *s, int level, struct Capture *cap) {
314+ int l = check_cap(level, cap);
315+ int len = cap->capture[l].len;
316+ if (cap->src_end-s >= len &&
317+ memcmp(cap->capture[l].init, s, len) == 0)
318+ return s+len;
319+ else return NULL;
320+}
321+
322+
323+static char *match (char *s, char *p, struct Capture *cap) {
275324 init: /* using goto's to optimize tail recursion */
276325 switch (*p) {
277− case '(': { /* start capture */
278− char *res;
279− if (cap->level >= MAX_CAPT) lua_error("too many captures");
280− cap->capture[cap->level].init = s;
281− cap->capture[cap->level].len = -1;
282− cap->level++;
283− if ((res=match(s, p+1, cap)) == NULL) /* match failed? */
284− cap->level--; /* undo capture */
285− return res;
286− }
287− case ')': { /* end capture */
288− int l = capture_to_close(cap);
289− char *res;
290− cap->capture[l].len = s - cap->capture[l].init; /* close capture */
291− if ((res = match(s, p+1, cap)) == NULL) /* match failed? */
292− cap->capture[l].len = -1; /* undo capture */
293− return res;
294− }
295− case '\0': case '$': /* (possibly) end of pattern */
296− if (*p == 0 || (*(p+1) == 0 && s == cap->src_end))
297− return s;
298− /* else go through */
299− default: { /* it is a pattern item */
300− char *ep; /* get what is next */
301− char *s1 = matchitem(s, p, cap, &ep);
326+ case '(': /* start capture */
327+ return start_capt(s, p, cap);
328+ case ')': /* end capture */
329+ return end_capt(s, p, cap);
330+ case ESC: /* may be %[0-9] or %b */
331+ if (isdigit((unsigned char)(*(p+1)))) { /* capture? */
332+ s = match_capture(s, *(p+1), cap);
333+ if (s == NULL) return NULL;
334+ p+=2; goto init; /* else return match(p+2, s, cap) */
335+ }
336+ else if (*(p+1) == 'b') { /* balanced string? */
337+ s = matchbalance(s, p+2, cap);
338+ if (s == NULL) return NULL;
339+ p+=4; goto init; /* else return match(p+4, s, cap); */
340+ }
341+ else goto dflt; /* case default */
342+ case '\0': /* end of pattern */
343+ return s; /* match succeeded */
344+ case '$':
345+ if (*(p+1) == '\0') /* is the '$' the last char in pattern? */
346+ return (s == cap->src_end) ? s : NULL; /* check end of string */
347+ else goto dflt;
348+ default: dflt: { /* it is a pattern item */
349+ char *ep = luaI_classend(p); /* points to what is next */
350+ int m = s<cap->src_end && luaI_singlematch((unsigned char)*s, p, ep);
302351 switch (*ep) {
303− case '*': { /* repetition */
304− char *res;
305− if (s1 && s1>s && ((res=match(s1, p, cap)) != NULL))
306− return res;
307− p=ep+1; goto init; /* else return match(s, ep+1, cap); */
308− }
309352 case '?': { /* optional */
310353 char *res;
311− if (s1 && ((res=match(s1, ep+1, cap)) != NULL))
354+ if (m && ((res=match(s+1, ep+1, cap)) != NULL))
312355 return res;
313356 p=ep+1; goto init; /* else return match(s, ep+1, cap); */
314357 }
315− case '-': { /* repetition */
316− char *res;
317− if ((res = match(s, ep+1, cap)) != NULL)
318− return res;
319− else if (s1 && s1>s) {
320− s = s1;
321− goto init; /* return match(s1, p, cap); */
322− }
323− else
324− return NULL;
325− }
358+ case '*': /* 0 or more repetitions */
359+ return max_expand(s, p, ep, cap);
360+ case '+': /* 1 or more repetitions */
361+ return (m ? max_expand(s+1, p, ep, cap) : NULL);
362+ case '-': /* 0 or more repetitions (minimum) */
363+ return min_expand(s, p, ep, cap);
326364 default:
327− if (s1) { s=s1; p=ep; goto init; } /* return match(s1, ep, cap); */
328− else return NULL;
365+ if (!m) return NULL;
366+ s++; p=ep; goto init; /* else return match(s+1, ep, cap); */
329367 }
330368 }
331369 }
332370 }
333371
334372
335−static void str_find (void)
336−{
373+static void str_find (void) {
337374 long l;
338375 char *s = luaL_check_lstr(1, &l);
339376 char *p = luaL_check_string(2);
340− long init = posrelat(luaL_opt_number(3, 1), l) - 1;
377+ long init = posrelat(luaL_opt_long(3, 1), l) - 1;
341378 struct Capture cap;
342379 luaL_arg_check(0 <= init && init <= l, 3, "out of range");
343380 if (lua_getparam(4) != LUA_NOOBJECT ||
@@ -368,8 +405,7 @@ static void str_find (void) · 24 unmodified lines
368405 }
369406
370407
371−static void add_s (lua_Object newp, struct Capture *cap)
372−{
408+static void add_s (lua_Object newp, struct Capture *cap) {
373409 if (lua_isstring(newp)) {
374410 char *news = lua_getstring(newp);
375411 int l = lua_strlen(newp);
@@ -411,13 +447,12 @@ static void add_s (lua_Object newp, struct Capture *cap) · 35 unmodified lines
411447 }
412448
413449
414−static void str_gsub (void)
415−{
450+static void str_gsub (void) {
416451 long srcl;
417452 char *src = luaL_check_lstr(1, &srcl);
418453 char *p = luaL_check_string(2);
419454 lua_Object newp = lua_getparam(3);
420− int max_s = (int)luaL_opt_number(4, srcl+1);
455+ int max_s = luaL_opt_int(4, srcl+1);
421456 int anchor = (*p == '^') ? (p++, 1) : 0;
422457 int n = 0;
423458 struct Capture cap;
@@ -445,26 +480,33 @@ static void str_gsub (void) · 21 unmodified lines
445480 lua_pushnumber(n); /* number of substitutions */
446481 }
447482
483+/* }====================================================== */
448484
449−static void luaI_addquoted (char *s)
450−{
485+
486+static void luaI_addquoted (int arg) {
487+ long l;
488+ char *s = luaL_check_lstr(arg, &l);
451489 luaL_addchar('"');
452− for (; *s; s++) {
453− if (strchr("\"\\\n", *s))
454− luaL_addchar('\\');
455− luaL_addchar(*s);
490+ while (l--) {
491+ switch (*s) {
492+ case '"': case '\\': case '\n':
493+ luaL_addchar('\\');
494+ luaL_addchar(*s);
495+ break;
496+ case '\0': addnchar("\\000", 4); break;
497+ default: luaL_addchar(*s);
498+ }
499+ s++;
456500 }
457501 luaL_addchar('"');
458502 }
459503
460−#define MAX_FORMAT 200
504+/* maximum size of each format specification (such as '%-099.99d') */
505+#define MAX_FORMAT 20 /* arbitrary limit */
461506
462−static void str_format (void)
463−{
507+static void str_format (void) {
464508 int arg = 1;
465509 char *strfrmt = luaL_check_string(arg);
466− struct Capture cap;
467− cap.src_end = strfrmt+strlen(strfrmt)+1;
468510 luaL_resetbuffer();
469511 while (*strfrmt) {
470512 if (*strfrmt != '%')
@@ -472,34 +514,28 @@ static void str_format (void) · 1 unmodified line
472514 else if (*++strfrmt == '%')
473515 luaL_addchar(*strfrmt++); /* %% */
474516 else { /* format item */
475− char form[MAX_FORMAT]; /* store the format ('%...') */
476− char *buff;
517+ struct Capture cap;
518+ char form[MAX_FORMAT]; /* to store the format ('%...') */
519+ char *buff; /* to store the formatted item */
477520 char *initf = strfrmt;
478521 form[0] = '%';
479− cap.level = 0;
480− if (isdigit((unsigned char)initf[0]) && initf[1] == '$') {
481− arg = initf[0] - '0';
522+ if (isdigit((unsigned char)*initf) && *(initf+1) == '$') {
523+ arg = *initf - '0';
482524 initf += 2; /* skip the 'n$' */
483525 }
484526 arg++;
527+ cap.src_end = strfrmt+strlen(strfrmt)+1;
528+ cap.level = 0;
485529 strfrmt = match(initf, "[-+ #0]*(%d*)%.?(%d*)", &cap);
486− if (cap.capture[0].len > 2 || cap.capture[1].len > 2) /* < 100? */
530+ if (cap.capture[0].len > 2 || cap.capture[1].len > 2 || /* < 100? */
531+ strfrmt-initf > MAX_FORMAT-2)
487532 lua_error("invalid format (width or precision too long)");
488533 strncpy(form+1, initf, strfrmt-initf+1); /* +1 to include conversion */
489534 form[strfrmt-initf+2] = 0;
490− buff = luaL_openspace(1000); /* to store the formatted value */
535+ buff = luaL_openspace(512); /* 512 > size of format('%99.99f', -1e308) */
491536 switch (*strfrmt++) {
492− case 'q':
493− luaI_addquoted(luaL_check_string(arg));
494− continue;
495− case 's': {
496− char *s = luaL_check_string(arg);
497− buff = luaL_openspace(strlen(s));
498− sprintf(buff, form, s);
499− break;
500− }
501537 case 'c': case 'd': case 'i':
502− sprintf(buff, form, (int)luaL_check_number(arg));
538+ sprintf(buff, form, luaL_check_int(arg));
503539 break;
504540 case 'o': case 'u': case 'x': case 'X':
505541 sprintf(buff, form, (unsigned int)luaL_check_number(arg));
@@ -507,6 +543,23 @@ static void str_format (void) · 1 unmodified line
507543 case 'e': case 'E': case 'f': case 'g': case 'G':
508544 sprintf(buff, form, luaL_check_number(arg));
509545 break;
546+ case 'q':
547+ luaI_addquoted(arg);
548+ continue; /* skip the "addsize" at the end */
549+ case 's': {
550+ long l;
551+ char *s = luaL_check_lstr(arg, &l);
552+ if (cap.capture[1].len == 0 && l >= 100) {
553+ /* no precision and string is too big to be formatted;
554+ keep original string */
555+ addnchar(s, l);
556+ continue; /* skip the "addsize" at the end */
557+ }
558+ else {
559+ sprintf(buff, form, s);
560+ break;
561+ }
562+ }
510563 default: /* also treat cases 'pnLlh' */
511564 lua_error("invalid option in `format'");
512565 }
@@ -524,7 +577,7 @@ static struct luaL_reg strlib[] = { · 11 unmodified lines
524577 {"strupper", str_upper},
525578 {"strchar", str_char},
526579 {"strrep", str_rep},
527−{"ascii", str_byte}, /* for compatibility */
580+{"ascii", str_byte}, /* for compatibility with 3.0 and earlier */
528581 {"strbyte", str_byte},
529582 {"format", str_format},
530583 {"strfind", str_find},
src/llex.c+52−78
@@ -1,6 +1,6 @@
11 /*
2−** $Id: llex.c,v 1.23 1998/07/06 22:04:58 roberto Exp $
3−** Lexical Analizer
2+** $Id: llex.c,v 1.36 1999/06/17 17:04:03 roberto Exp $
3+** Lexical Analyzer
44 ** See Copyright Notice in lua.h
55 */
66
@@ -20,9 +20,6 @@ · 13 unmodified lines
2020
2121
2222
23−int lua_debug=0;
24−
25−
2623 #define next(LS) (LS->current = zgetc(LS->lex_z))
2724
2825
@@ -35,8 +32,7 @@ char *reserved [] = {"and", "do", "else", "elseif", "end", "function", · 6 unmodified lines
3532 "until", "while"};
3633
3734
38−void luaX_init (void)
39−{
35+void luaX_init (void) {
4036 int i;
4137 for (i=0; i<(sizeof(reserved)/sizeof(reserved[0])); i++) {
4238 TaggedString *ts = luaS_new(reserved[i]);
@@ -45,24 +41,28 @@ void luaX_init (void) · 2 unmodified lines
4541 }
4642
4743
44+#define MAXSRC 80
45+
4846 void luaX_syntaxerror (LexState *ls, char *s, char *token) {
49− if (token[0] == 0)
47+ char buff[MAXSRC];
48+ luaL_chunkid(buff, zname(ls->lex_z), sizeof(buff));
49+ if (token[0] == '\0')
5050 token = "<eof>";
51− luaL_verror("%.100s;\n last token read: `%.50s' at line %d in chunk `%.50s'",
52− s, token, ls->linenumber, zname(ls->lex_z));
51+ luaL_verror("%.100s;\n last token read: `%.50s' at line %d in %.80s",
52+ s, token, ls->linenumber, buff);
5353 }
5454
5555
5656 void luaX_error (LexState *ls, char *s) {
57− save(0);
57+ save('\0');
5858 luaX_syntaxerror(ls, s, luaL_buffer());
5959 }
6060
6161
62−void luaX_token2str (LexState *ls, int token, char *s) {
62+void luaX_token2str (int token, char *s) {
6363 if (token < 255) {
64− s[0] = token;
65− s[1] = 0;
64+ s[0] = (char)token;
65+ s[1] = '\0';
6666 }
6767 else
6868 strcpy(s, reserved[token-FIRST_RESERVED]);
@@ -70,8 +70,8 @@ void luaX_token2str (LexState *ls, int token, char *s) { · 1 unmodified line
7070
7171
7272 static void luaX_invalidchar (LexState *ls, int c) {
73− char buff[10];
74− sprintf(buff, "0x%X", c);
73+ char buff[8];
74+ sprintf(buff, "0x%02X", c);
7575 luaX_syntaxerror(ls, "invalid control char", buff);
7676 }
7777
@@ -106,17 +106,17 @@ void luaX_setinput (LexState *LS, ZIO *z) · 28 unmodified lines
106106 ** =======================================================
107107 */
108108
109−#define PRAGMASIZE 20
109+#ifndef PRAGMASIZE
110+#define PRAGMASIZE 80 /* arbitrary limit */
111+#endif
110112
111−static void skipspace (LexState *LS)
112−{
113+static void skipspace (LexState *LS) {
113114 while (LS->current == ' ' || LS->current == '\t' || LS->current == '\r')
114115 next(LS);
115116 }
116117
117118
118−static int checkcond (LexState *LS, char *buff)
119−{
119+static int checkcond (LexState *LS, char *buff) {
120120 static char *opts[] = {"nil", "1", NULL};
121121 int i = luaL_findstring(buff, opts);
122122 if (i >= 0) return i;
@@ -129,8 +129,7 @@ static int checkcond (LexState *LS, char *buff) · 6 unmodified lines
129129 }
130130
131131
132−static void readname (LexState *LS, char *buff)
133−{
132+static void readname (LexState *LS, char *buff) {
134133 int i = 0;
135134 skipspace(LS);
136135 while (isalnum(LS->current) || LS->current == '_') {
@@ -138,7 +137,7 @@ static void readname (LexState *LS, char *buff) · 1 unmodified line
138137 buff[PRAGMASIZE] = 0;
139138 luaX_syntaxerror(LS, "pragma too long", buff);
140139 }
141− buff[i++] = LS->current;
140+ buff[i++] = (char)LS->current;
142141 next(LS);
143142 }
144143 buff[i] = 0;
@@ -148,8 +147,7 @@ static void readname (LexState *LS, char *buff) · 3 unmodified lines
148147 static void inclinenumber (LexState *LS);
149148
150149
151−static void ifskip (LexState *LS)
152−{
150+static void ifskip (LexState *LS) {
153151 while (LS->ifstate[LS->iflevel].skip) {
154152 if (LS->current == '\n')
155153 inclinenumber(LS);
@@ -160,8 +158,7 @@ static void ifskip (LexState *LS) · 4 unmodified lines
160158 }
161159
162160
163−static void inclinenumber (LexState *LS)
164−{
161+static void inclinenumber (LexState *LS) {
165162 static char *pragmas [] =
166163 {"debug", "nodebug", "endinput", "end", "ifnot", "if", "else", NULL};
167164 next(LS); /* skip '\n' */
@@ -174,10 +171,10 @@ static void inclinenumber (LexState *LS) · 6 unmodified lines
174171 readname(LS, buff);
175172 switch (luaL_findstring(buff, pragmas)) {
176173 case 0: /* debug */
177− if (!skip) lua_debug = 1;
174+ if (!skip) L->debug = 1;
178175 break;
179176 case 1: /* nodebug */
180− if (!skip) lua_debug = 0;
177+ if (!skip) L->debug = 0;
181178 break;
182179 case 2: /* endinput */
183180 if (!skip) {
@@ -221,6 +218,7 @@ static void inclinenumber (LexState *LS) · 37 unmodified lines
221218 }
222219
223220
221+
224222 /*
225223 ** =======================================================
226224 ** LEXICAL ANALIZER
@@ -229,12 +227,9 @@ static void inclinenumber (LexState *LS) · 2 unmodified lines
229227
230228
231229
232−
233−
234−static int read_long_string (LexState *LS)
235−{
230+static int read_long_string (LexState *LS) {
236231 int cont = 0;
237− while (1) {
232+ for (;;) {
238233 switch (LS->current) {
239234 case EOZ:
240235 luaX_error(LS, "unfinished long string");
@@ -262,17 +257,16 @@ static int read_long_string (LexState *LS) · 21 unmodified lines
262257 save_and_next(LS);
263258 }
264259 } endloop:
265− save_and_next(LS); /* pass the second ']' */
266− LS->seminfo.ts = luaS_newlstr(L->Mbuffbase+2,
267− L->Mbuffnext-(L->Mbuffbase-L->Mbuffer)-4);
260+ save_and_next(LS); /* skip the second ']' */
261+ LS->seminfo.ts = luaS_newlstr(L->Mbuffer+(L->Mbuffbase+2),
262+ L->Mbuffnext-L->Mbuffbase-4);
268263 return STRING;
269264 }
270265
271266
272267 int luaX_lex (LexState *LS) {
273− double a;
274268 luaL_resetbuffer();
275− while (1) {
269+ for (;;) {
276270 switch (LS->current) {
277271
278272 case ' ': case '\t': case '\r': /* CR: to avoid problems with DOS */
@@ -347,7 +341,7 @@ int luaX_lex (LexState *LS) { · 68 unmodified lines
347341 c = 10*c + (LS->current-'0');
348342 next(LS);
349343 } while (++i<3 && isdigit(LS->current));
350− if (c >= 256)
344+ if (c != (unsigned char)c)
351345 luaX_error(LS, "escape sequence too large");
352346 save(c);
353347 }
@@ -364,8 +358,8 @@ int luaX_lex (LexState *LS) { · 10 unmodified lines
364358 }
365359 }
366360 save_and_next(LS); /* skip delimiter */
367− LS->seminfo.ts = luaS_newlstr(L->Mbuffbase+1,
368− L->Mbuffnext-(L->Mbuffbase-L->Mbuffer)-2);
361+ LS->seminfo.ts = luaS_newlstr(L->Mbuffer+(L->Mbuffbase+1),
362+ L->Mbuffnext-L->Mbuffbase-2);
369363 return STRING;
370364 }
371365
@@ -382,15 +376,11 @@ int luaX_lex (LexState *LS) { · 10 unmodified lines
382376 else return CONC; /* .. */
383377 }
384378 else if (!isdigit(LS->current)) return '.';
385− /* LS->current is a digit: goes through to number */
386− a=0.0;
387− goto fraction;
379+ goto fraction; /* LS->current is a digit: goes through to number */
388380
389381 case '0': case '1': case '2': case '3': case '4':
390382 case '5': case '6': case '7': case '8': case '9':
391− a=0.0;
392383 do {
393− a = 10.0*a + (LS->current-'0');
394384 save_and_next(LS);
395385 } while (isdigit(LS->current));
396386 if (LS->current == '.') {
@@ -402,35 +392,19 @@ int luaX_lex (LexState *LS) { · 5 unmodified lines
402392 }
403393 }
404394 fraction:
405− { double da=0.1;
406− while (isdigit(LS->current))
407− {
408− a += (LS->current-'0')*da;
409− da /= 10.0;
410− save_and_next(LS);
411− }
412− if (toupper(LS->current) == 'E') {
413− int e = 0;
414− int neg;
415− double ea;
395+ while (isdigit(LS->current))
396+ save_and_next(LS);
397+ if (toupper(LS->current) == 'E') {
398+ save_and_next(LS); /* read 'E' */
399+ save_and_next(LS); /* read '+', '-' or first digit */
400+ while (isdigit(LS->current))
416401 save_and_next(LS);
417− neg = (LS->current=='-');
418− if (LS->current == '+' || LS->current == '-') save_and_next(LS);
419− if (!isdigit(LS->current))
420− luaX_error(LS, "invalid numeral format");
421− do {
422− e = 10*e + (LS->current-'0');
423− save_and_next(LS);
424− } while (isdigit(LS->current));
425− for (ea=neg?0.1:10.0; e>0; e>>=1)
426− {
427− if (e & 1) a *= ea;
428− ea *= ea;
429− }
430− }
431− LS->seminfo.r = a;
432− return NUMBER;
433402 }
403+ save('\0');
404+ LS->seminfo.r = luaO_str2d(L->Mbuffer+L->Mbuffbase);
405+ if (LS->seminfo.r < 0)
406+ luaX_error(LS, "invalid numeric format");
407+ return NUMBER;
434408
435409 case EOZ:
436410 if (LS->iflevel > 0)
@@ -450,9 +424,9 @@ int luaX_lex (LexState *LS) { · 13 unmodified lines
450424 do {
451425 save_and_next(LS);
452426 } while (isalnum(LS->current) || LS->current == '_');
453− save(0);
454− ts = luaS_new(L->Mbuffbase);
455− if (ts->head.marked >= 'A')
427+ save('\0');
428+ ts = luaS_new(L->Mbuffer+L->Mbuffbase);
429+ if (ts->head.marked >= FIRST_RESERVED)
456430 return ts->head.marked; /* reserved word */
457431 LS->seminfo.ts = ts;
458432 return NAME;
src/llex.h+7−5
@@ -1,6 +1,6 @@
11 /*
2−** $Id: llex.h,v 1.9 1998/06/19 16:14:09 roberto Exp $
3−** Lexical Analizer
2+** $Id: llex.h,v 1.12 1999/06/17 17:04:03 roberto Exp $
3+** Lexical Analyzer
44 ** See Copyright Notice in lua.h
55 */
66
@@ -25,12 +25,14 @@ enum RESERVED { · 18 unmodified lines
2525 NAME, CONC, DOTS, EQ, GE, LE, NE, NUMBER, STRING, EOS};
2626
2727
28−#define MAX_IFS 5
28+#ifndef MAX_IFS
29+#define MAX_IFS 5 /* arbitrary limit */
30+#endif
2931
3032 /* "ifstate" keeps the state of each nested $if the lexical is dealing with. */
3133
3234 struct ifState {
33− int elsepart; /* true if its in the $else part */
35+ int elsepart; /* true if it's in the $else part */
3436 int condition; /* true if $if condition is true */
3537 int skip; /* true if part must be skipped */
3638 };
@@ -56,7 +58,7 @@ void luaX_setinput (LexState *LS, ZIO *z); · 19 unmodified lines
5658 int luaX_lex (LexState *LS);
5759 void luaX_syntaxerror (LexState *ls, char *s, char *token);
5860 void luaX_error (LexState *ls, char *s);
59−void luaX_token2str (LexState *ls, int token, char *s);
61+void luaX_token2str (int token, char *s);
6062
6163
6264 #endif
src/lmem.c+80−53
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lmem.c,v 1.7 1998/06/29 22:03:06 roberto Exp $
2+** $Id: lmem.c,v 1.17 1999/05/24 17:51:05 roberto Exp $
33 ** Interface to Memory Manager
44 ** See Copyright Notice in lua.h
55 */
@@ -12,41 +12,54 @@ · 6 unmodified lines
1212 #include "lua.h"
1313
1414
15+/*
16+** real ANSI systems do not need these tests;
17+** but some systems (Sun OS) are not that ANSI...
18+*/
19+#ifdef OLD_ANSI
20+#define realloc(b,s) ((b) == NULL ? malloc(s) : (realloc)(b, s))
21+#define free(b) if (b) (free)(b)
22+#endif
23+
24+
25+#define MINSIZE 8 /* minimum size for "growing" vectors */
26+
27+
1528
16−int luaM_growaux (void **block, unsigned long nelems, int size,
17− char *errormsg, unsigned long limit)
18−{
19− if (nelems >= limit)
20− lua_error(errormsg);
21− nelems = (nelems == 0) ? 32 : nelems*2;
22− if (nelems > limit)
23− nelems = limit;
24− *block = luaM_realloc(*block, nelems*size);
25− return (int)nelems;
29+
30+static unsigned long power2 (unsigned long n) {
31+ unsigned long p = MINSIZE;
32+ while (p<=n) p<<=1;
33+ return p;
2634 }
2735
2836
37+void *luaM_growaux (void *block, unsigned long nelems, int inc, int size,
38+ char *errormsg, unsigned long limit) {
39+ unsigned long newn = nelems+inc;
40+ if (newn >= limit) lua_error(errormsg);
41+ if ((newn ^ nelems) <= nelems || /* still the same power of 2 limit? */
42+ (nelems > 0 && newn < MINSIZE)) /* or block already is MINSIZE? */
43+ return block; /* do not need to reallocate */
44+ else /* it crossed a power of 2 boundary; grow to next power */
45+ return luaM_realloc(block, power2(newn)*size);
46+}
47+
2948
3049 #ifndef DEBUG
3150
3251 /*
3352 ** generic allocation routine.
34−** real ANSI systems do not need some of these tests,
35−** since realloc(NULL, s)==malloc(s) and realloc(b, 0)==free(b).
36−** But some systems (e.g. Sun OS) are not that ANSI...
3753 */
38−void *luaM_realloc (void *block, unsigned long size)
39−{
54+void *luaM_realloc (void *block, unsigned long size) {
4055 size_t s = (size_t)size;
4156 if (s != size)
42− lua_error("Allocation Error: Block too big");
57+ lua_error("memory allocation error: block too big");
4358 if (size == 0) {
44− if (block) {
45− free(block);
46− }
59+ free(block); /* block may be NULL, that is OK for free */
4760 return NULL;
4861 }
49− block = block ? realloc(block, s) : malloc(s);
62+ block = realloc(block, s);
5063 if (block == NULL)
5164 lua_error(memEM);
5265 return block;
@@ -61,52 +74,66 @@ void *luaM_realloc (void *block, unsigned long size) · 8 unmodified lines
6174
6275
6376 #define HEADER (sizeof(double))
77+#define MARKSIZE 16
6478
6579 #define MARK 55
6680
81+
82+#define blocksize(b) ((unsigned long *)((char *)(b) - HEADER))
83+
6784 unsigned long numblocks = 0;
6885 unsigned long totalmem = 0;
6986
7087
71−static void *checkblock (void *block)
72−{
73− unsigned long *b = (unsigned long *)((char *)block - HEADER);
74− unsigned long size = *b;
75− LUA_ASSERT(*(((char *)b)+size+HEADER) == MARK,
76− "corrupted block");
77− numblocks--;
78− totalmem -= size;
79− return b;
88+static void *checkblock (void *block) {
89+ if (block == NULL)
90+ return NULL;
91+ else {
92+ unsigned long *b = blocksize(block);
93+ unsigned long size = *b;
94+ int i;
95+ for (i=0;i<MARKSIZE;i++)
96+ LUA_ASSERT(*(((char *)b)+HEADER+size+i) == MARK+i, "corrupted block");
97+ numblocks--;
98+ totalmem -= size;
99+ return b;
100+ }
80101 }
81102
82103
83−void *luaM_realloc (void *block, unsigned long size)
84−{
85− unsigned long realsize = HEADER+size+1;
104+static void freeblock (void *block) {
105+ if (block)
106+ memset(block, -1, *blocksize(block)); /* erase block */
107+ free(checkblock(block));
108+}
109+
110+
111+void *luaM_realloc (void *block, unsigned long size) {
112+ unsigned long realsize = HEADER+size+MARKSIZE;
86113 if (realsize != (size_t)realsize)
87− lua_error("Allocation Error: Block too big");
88− if (size == 0) { /* ANSI dosen't need this, but some machines... */
89− if (block) {
90− unsigned long *b = (unsigned long *)((char *)block - HEADER);
91− memset(block, -1, *b); /* erase block */
92− block = checkblock(block);
93− free(block);
94− }
114+ lua_error("memory allocation error: block too big");
115+ if (size == 0) {
116+ freeblock(block);
95117 return NULL;
96118 }
97− if (block) {
98− block = checkblock(block);
99− block = (unsigned long *)realloc(block, realsize);
119+ else {
120+ char *newblock = malloc(realsize);
121+ int i;
122+ if (block) {
123+ unsigned long oldsize = *blocksize(block);
124+ if (oldsize > size) oldsize = size;
125+ memcpy(newblock+HEADER, block, oldsize);
126+ freeblock(block); /* erase (and check) old copy */
127+ }
128+ if (newblock == NULL)
129+ lua_error(memEM);
130+ totalmem += size;
131+ numblocks++;
132+ *(unsigned long *)newblock = size;
133+ for (i=0;i<MARKSIZE;i++)
134+ *(newblock+HEADER+size+i) = MARK+i;
135+ return newblock+HEADER;
100136 }
101− else
102− block = (unsigned long *)malloc(realsize);
103− if (block == NULL)
104− lua_error(memEM);
105− totalmem += size;
106− numblocks++;
107− *(unsigned long *)block = size;
108− *(((char *)block)+size+HEADER) = MARK;
109− return (unsigned long *)((char *)block+HEADER);
110137 }
111138
112139
src/lmem.h+7−9
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lmem.h,v 1.5 1997/12/17 20:48:58 roberto Exp $
2+** $Id: lmem.h,v 1.8 1999/02/26 15:48:55 roberto Exp $
33 ** Interface to Memory Manager
44 ** See Copyright Notice in lua.h
55 */
@@ -8,10 +8,7 @@ · 2 unmodified lines
88 #define lmem_h
99
1010
11−#ifndef NULL
12−#define NULL 0
13−#endif
14−
11+#include <stdlib.h>
1512
1613 /* memory error messages */
1714 #define codeEM "code size overflow"
@@ -19,18 +16,19 @@ · 1 unmodified line
1916 #define refEM "reference table overflow"
2017 #define tableEM "table overflow"
2118 #define memEM "not enough memory"
19+#define arrEM "internal array bigger than `int' limit"
2220
2321 void *luaM_realloc (void *oldblock, unsigned long size);
24−int luaM_growaux (void **block, unsigned long nelems, int size,
22+void *luaM_growaux (void *block, unsigned long nelems, int inc, int size,
2523 char *errormsg, unsigned long limit);
2624
2725 #define luaM_free(b) luaM_realloc((b), 0)
2826 #define luaM_malloc(t) luaM_realloc(NULL, (t))
2927 #define luaM_new(t) ((t *)luaM_malloc(sizeof(t)))
3028 #define luaM_newvector(n,t) ((t *)luaM_malloc((n)*sizeof(t)))
31−#define luaM_growvector(old,n,t,e,l) \
32− (luaM_growaux((void**)old,n,sizeof(t),e,l))
33−#define luaM_reallocvector(v,n,t) ((t *)luaM_realloc(v,(n)*sizeof(t)))
29+#define luaM_growvector(v,nelems,inc,t,e,l) \
30+ ((v)=(t *)luaM_growaux(v,nelems,inc,sizeof(t),e,l))
31+#define luaM_reallocvector(v,n,t) ((v)=(t *)luaM_realloc(v,(n)*sizeof(t)))
3432
3533
3634 #ifdef DEBUG
src/lobject.c+61−15
@@ -1,9 +1,10 @@
11 /*
2−** $Id: lobject.c,v 1.13 1998/06/19 16:14:09 roberto Exp $
2+** $Id: lobject.c,v 1.19 1999/04/13 19:28:49 roberto Exp $
33 ** Some generic functions over Lua objects
44 ** See Copyright Notice in lua.h
55 */
66
7+#include <ctype.h>
78 #include <stdlib.h>
89
910 #include "lobject.h"
@@ -34,14 +35,12 @@ int luaO_redimension (int oldsize) · 24 unmodified lines
3435 if (dimensions[i] > oldsize)
3536 return dimensions[i];
3637 }
37− lua_error("table overflow");
38+ lua_error("tableEM");
3839 return 0; /* to avoid warnings */
3940 }
4041
4142
42−int luaO_equalObj (TObject *t1, TObject *t2)
43−{
44− if (ttype(t1) != ttype(t2)) return 0;
43+int luaO_equalval (TObject *t1, TObject *t2) {
4544 switch (ttype(t1)) {
4645 case LUA_T_NIL: return 1;
4746 case LUA_T_NUMBER: return nvalue(t1) == nvalue(t2);
@@ -64,20 +63,67 @@ void luaO_insertlist (GCnode *root, GCnode *node) · 16 unmodified lines
6463 node->marked = 0;
6564 }
6665
66+
6767 #ifdef OLD_ANSI
68−void luaO_memup (void *dest, void *src, int size)
69−{
70− char *d = dest;
71− char *s = src;
72− while (size--) d[size]=s[size];
68+void luaO_memup (void *dest, void *src, int size) {
69+ while (size--)
70+ ((char *)dest)[size]=((char *)src)[size];
7371 }
7472
75−void luaO_memdown (void *dest, void *src, int size)
76−{
77− char *d = dest;
78− char *s = src;
73+void luaO_memdown (void *dest, void *src, int size) {
7974 int i;
80− for (i=0; i<size; i++) d[i]=s[i];
75+ for (i=0; i<size; i++)
76+ ((char *)dest)[i]=((char *)src)[i];
8177 }
8278 #endif
8379
80+
81+
82+static double expten (unsigned int e) {
83+ double exp = 10.0;
84+ double res = 1.0;
85+ for (; e; e>>=1) {
86+ if (e & 1) res *= exp;
87+ exp *= exp;
88+ }
89+ return res;
90+}
91+
92+
93+double luaO_str2d (char *s) { /* LUA_NUMBER */
94+ double a = 0.0;
95+ int point = 0;
96+ while (isdigit((unsigned char)*s)) {
97+ a = 10.0*a + (*(s++)-'0');
98+ }
99+ if (*s == '.') {
100+ s++;
101+ while (isdigit((unsigned char)*s)) {
102+ a = 10.0*a + (*(s++)-'0');
103+ point++;
104+ }
105+ }
106+ if (toupper((unsigned char)*s) == 'E') {
107+ int e = 0;
108+ int sig = 1;
109+ s++;
110+ if (*s == '-') {
111+ s++;
112+ sig = -1;
113+ }
114+ else if (*s == '+') s++;
115+ if (!isdigit((unsigned char)*s)) return -1; /* no digit in the exponent? */
116+ do {
117+ e = 10*e + (*(s++)-'0');
118+ } while (isdigit((unsigned char)*s));
119+ point -= sig*e;
120+ }
121+ while (isspace((unsigned char)*s)) s++;
122+ if (*s != '\0') return -1; /* invalid trailing characters? */
123+ if (point > 0)
124+ a /= expten(point);
125+ else if (point < 0)
126+ a *= expten(-point);
127+ return a;
128+}
129+
src/lobject.h+9−15
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lobject.h,v 1.21 1998/06/18 16:57:03 roberto Exp $
2+** $Id: lobject.h,v 1.28 1999/03/16 16:43:27 roberto Exp $
33 ** Type definitions for Lua objects
44 ** See Copyright Notice in lua.h
55 */
@@ -32,10 +32,6 @@ · 26 unmodified lines
3232 #define LUA_NUM_TYPE double
3333 #endif
3434
35−/*
36−** format to convert number to strings
37−*/
38−#define NUMBER_FMT "%g"
3935
4036 typedef LUA_NUM_TYPE real;
4137
@@ -45,13 +41,6 @@ typedef unsigned char Byte; /* unsigned 8 bits */ · 3 unmodified lines
4541
4642 #define MAX_INT (INT_MAX-2) /* maximum value of an int (-2 for safety) */
4743
48−/* maximum value of a word of 2 bytes (-2 for safety); must fit in an "int" */
49−#if MAX_INT < 65534
50−#define MAX_WORD MAX_INT
51−#else
52−#define MAX_WORD 65534
53−#endif
54−
5544 typedef unsigned int IntPoint; /* unsigned with same size as a pointer (for hashing) */
5645
5746
@@ -75,7 +64,6 @@ typedef enum { · 17 unmodified lines
7564 LUA_T_LINE = -11
7665 } lua_Type;
7766
78−#define NUM_TYPES 11
7967 #define NUM_TAGS 7
8068
8169
@@ -139,7 +127,7 @@ typedef struct TProtoFunc { · 57 unmodified lines
139127 int nconsts;
140128 Byte *code; /* ends with opcode ENDCODE */
141129 int lineDefined;
142− TaggedString *fileName;
130+ TaggedString *source;
143131 struct LocVar *locvars; /* ends with line = -1 */
144132 } TProtoFunc;
145133
@@ -192,11 +180,17 @@ typedef struct Hash { · 46 unmodified lines
192180
193181 extern char *luaO_typenames[];
194182
183+#define luaO_typename(o) luaO_typenames[-ttype(o)]
184+
185+
195186 extern TObject luaO_nilobject;
196187
197−int luaO_equalObj (TObject *t1, TObject *t2);
188+#define luaO_equalObj(t1,t2) ((ttype(t1) != ttype(t2)) ? 0 \
189+ : luaO_equalval(t1,t2))
190+int luaO_equalval (TObject *t1, TObject *t2);
198191 int luaO_redimension (int oldsize);
199192 void luaO_insertlist (GCnode *root, GCnode *node);
193+double luaO_str2d (char *s);
200194
201195 #ifdef OLD_ANSI
202196 void luaO_memup (void *dest, void *src, int size);
src/lopcodes.h+113−156
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lopcodes.h,v 1.18 1998/06/25 14:37:00 roberto Exp $
2+** $Id: lopcodes.h,v 1.33 1999/06/17 17:04:03 roberto Exp $
33 ** Opcodes for Lua virtual machine
44 ** See Copyright Notice in lua.h
55 */
@@ -10,172 +10,129 @@ · 4 unmodified lines
1010
1111 /*
1212 ** NOTICE: variants of the same opcode must be consecutive: First, those
13−** with byte parameter, then with built-in parameters, and last with
14−** word parameter.
13+** with word parameter, then with byte parameter.
1514 */
1615
1716
1817 typedef enum {
1918 /* name parm before after side effect
2019 -----------------------------------------------------------------------------*/
21−ENDCODE,/* - - - */
22−
23−PUSHNIL,/* b - nil_0...nil_b */
24−PUSHNIL0,/* - - nil */
25−
26−PUSHNUMBER,/* b - (float)b */
27−PUSHNUMBER0,/* - - 0.0 */
28−PUSHNUMBER1,/* - - 1.0 */
29−PUSHNUMBER2,/* - - 2.0 */
30−PUSHNUMBERW,/* w - (float)w */
31−
32−PUSHCONSTANT,/* b - CNST[b] */
33−PUSHCONSTANT0,/*- - CNST[0] */
34−PUSHCONSTANT1,/*- - CNST[1] */
35−PUSHCONSTANT2,/*- - CNST[2] */
36−PUSHCONSTANT3,/*- - CNST[3] */
37−PUSHCONSTANT4,/*- - CNST[4] */
38−PUSHCONSTANT5,/*- - CNST[5] */
39−PUSHCONSTANT6,/*- - CNST[6] */
40−PUSHCONSTANT7,/*- - CNST[7] */
41−PUSHCONSTANTW,/*w - CNST[w] */
42−
43−PUSHUPVALUE,/* b - Closure[b] */
44−PUSHUPVALUE0,/* - - Closure[0] */
45−PUSHUPVALUE1,/* - - Closure[1] */
46−
47−PUSHLOCAL,/* b - LOC[b] */
48−PUSHLOCAL0,/* - - LOC[0] */
49−PUSHLOCAL1,/* - - LOC[1] */
50−PUSHLOCAL2,/* - - LOC[2] */
51−PUSHLOCAL3,/* - - LOC[3] */
52−PUSHLOCAL4,/* - - LOC[4] */
53−PUSHLOCAL5,/* - - LOC[5] */
54−PUSHLOCAL6,/* - - LOC[6] */
55−PUSHLOCAL7,/* - - LOC[7] */
56−
57−GETGLOBAL,/* b - VAR[CNST[b]] */
58−GETGLOBAL0,/* - - VAR[CNST[0]] */
59−GETGLOBAL1,/* - - VAR[CNST[1]] */
60−GETGLOBAL2,/* - - VAR[CNST[2]] */
61−GETGLOBAL3,/* - - VAR[CNST[3]] */
62−GETGLOBAL4,/* - - VAR[CNST[4]] */
63−GETGLOBAL5,/* - - VAR[CNST[5]] */
64−GETGLOBAL6,/* - - VAR[CNST[6]] */
65−GETGLOBAL7,/* - - VAR[CNST[7]] */
66−GETGLOBALW,/* w - VAR[CNST[w]] */
67−
68−GETTABLE,/* - i t t[i] */
69−
70−GETDOTTED,/* b t t[CNST[b]] */
71−GETDOTTED0,/* - t t[CNST[0]] */
72−GETDOTTED1,/* - t t[CNST[1]] */
73−GETDOTTED2,/* - t t[CNST[2]] */
74−GETDOTTED3,/* - t t[CNST[3]] */
75−GETDOTTED4,/* - t t[CNST[4]] */
76−GETDOTTED5,/* - t t[CNST[5]] */
77−GETDOTTED6,/* - t t[CNST[6]] */
78−GETDOTTED7,/* - t t[CNST[7]] */
79−GETDOTTEDW,/* w t t[CNST[w]] */
80−
81−PUSHSELF,/* b t t t[CNST[b]] */
82−PUSHSELF0,/* - t t t[CNST[0]] */
83−PUSHSELF1,/* - t t t[CNST[1]] */
84−PUSHSELF2,/* - t t t[CNST[2]] */
85−PUSHSELF3,/* - t t t[CNST[3]] */
86−PUSHSELF4,/* - t t t[CNST[4]] */
87−PUSHSELF5,/* - t t t[CNST[5]] */
88−PUSHSELF6,/* - t t t[CNST[6]] */
89−PUSHSELF7,/* - t t t[CNST[7]] */
90−PUSHSELFW,/* w t t t[CNST[w]] */
91−
92−CREATEARRAY,/* b - newarray(size = b) */
93−CREATEARRAY0,/* - - newarray(size = 0) */
94−CREATEARRAY1,/* - - newarray(size = 1) */
95−CREATEARRAYW,/* w - newarray(size = w) */
96−
97−SETLOCAL,/* b x - LOC[b]=x */
98−SETLOCAL0,/* - x - LOC[0]=x */
99−SETLOCAL1,/* - x - LOC[1]=x */
100−SETLOCAL2,/* - x - LOC[2]=x */
101−SETLOCAL3,/* - x - LOC[3]=x */
102−SETLOCAL4,/* - x - LOC[4]=x */
103−SETLOCAL5,/* - x - LOC[5]=x */
104−SETLOCAL6,/* - x - LOC[6]=x */
105−SETLOCAL7,/* - x - LOC[7]=x */
106−
107−SETGLOBAL,/* b x - VAR[CNST[b]]=x */
108−SETGLOBAL0,/* - x - VAR[CNST[0]]=x */
109−SETGLOBAL1,/* - x - VAR[CNST[1]]=x */
110−SETGLOBAL2,/* - x - VAR[CNST[2]]=x */
111−SETGLOBAL3,/* - x - VAR[CNST[3]]=x */
112−SETGLOBAL4,/* - x - VAR[CNST[4]]=x */
113−SETGLOBAL5,/* - x - VAR[CNST[5]]=x */
114−SETGLOBAL6,/* - x - VAR[CNST[6]]=x */
115−SETGLOBAL7,/* - x - VAR[CNST[7]]=x */
116−SETGLOBALW,/* w x - VAR[CNST[w]]=x */
117−
118−SETTABLE0,/* - v i t - t[i]=v */
119−
120−SETTABLE,/* b v a_b...a_1 i t a_b...a_1 i t t[i]=v */
121−
122−SETLIST,/* b c v_c...v_1 t - t[i+b*FPF]=v_i */
123−SETLIST0,/* b v_b...v_1 t - t[i]=v_i */
124−SETLISTW,/* w c v_c...v_1 t - t[i+w*FPF]=v_i */
125−
126−SETMAP,/* b v_b k_b ...v_0 k_0 t t t[k_i]=v_i */
127−SETMAP0,/* - v_0 k_0 t t t[k_0]=v_0 */
128−
129−EQOP,/* - y x (x==y)? 1 : nil */
130−NEQOP,/* - y x (x~=y)? 1 : nil */
131−LTOP,/* - y x (x<y)? 1 : nil */
132−LEOP,/* - y x (x<y)? 1 : nil */
133−GTOP,/* - y x (x>y)? 1 : nil */
134−GEOP,/* - y x (x>=y)? 1 : nil */
135−ADDOP,/* - y x x+y */
136−SUBOP,/* - y x x-y */
137−MULTOP,/* - y x x*y */
138−DIVOP,/* - y x x/y */
139−POWOP,/* - y x x^y */
140−CONCOP,/* - y x x..y */
141−MINUSOP,/* - x -x */
142−NOTOP,/* - x (x==nil)? 1 : nil */
143−
144−ONTJMP,/* b x (x!=nil)? x : - (x!=nil)? PC+=b */
145−ONTJMPW,/* w x (x!=nil)? x : - (x!=nil)? PC+=w */
146−ONFJMP,/* b x (x==nil)? x : - (x==nil)? PC+=b */
147−ONFJMPW,/* w x (x==nil)? x : - (x==nil)? PC+=w */
148−JMP,/* b - - PC+=b */
149−JMPW,/* w - - PC+=w */
150−IFFJMP,/* b x - (x==nil)? PC+=b */
151−IFFJMPW,/* w x - (x==nil)? PC+=w */
152−IFTUPJMP,/* b x - (x!=nil)? PC-=b */
153−IFTUPJMPW,/* w x - (x!=nil)? PC-=w */
154−IFFUPJMP,/* b x - (x==nil)? PC-=b */
155−IFFUPJMPW,/* w x - (x==nil)? PC-=w */
156−
157−CLOSURE,/* b c v_c...v_1 closure(CNST[b], v_c...v_1) */
158−CLOSUREW,/* w c v_b...v_1 closure(CNST[w], v_c...v_1) */
159−
160−CALLFUNC,/* b c v_c...v_1 f r_b...r_1 f(v1,...,v_c) */
161−CALLFUNC0,/* b v_b...v_1 f - f(v1,...,v_b) */
162−CALLFUNC1,/* b v_b...v_1 f r_1 f(v1,...,v_b) */
163−
164−RETCODE,/* b - - */
165−
166−SETLINE,/* b - - LINE=b */
167−SETLINEW,/* w - - LINE=w */
168−
169−POP,/* b - - TOP-=(b+1) */
170−POP0,/* - - - TOP-=1 */
171−POP1/* - - - TOP-=2 */
20+ENDCODE,/* - - (return) */
21+RETCODE,/* b - (return) */
22+
23+CALL,/* b c v_c...v_1 f r_b...r_1 f(v1,...,v_c) */
24+
25+TAILCALL,/* b c v_c...v_1 f (return) f(v1,...,v_c) */
26+
27+PUSHNIL,/* b - nil_0...nil_b */
28+POP,/* b a_b...a_1 - */
29+
30+PUSHNUMBERW,/* w - (float)w */
31+PUSHNUMBER,/* b - (float)b */
32+
33+PUSHNUMBERNEGW,/* w - (float)-w */
34+PUSHNUMBERNEG,/* b - (float)-b */
35+
36+PUSHCONSTANTW,/*w - CNST[w] */
37+PUSHCONSTANT,/* b - CNST[b] */
38+
39+PUSHUPVALUE,/* b - Closure[b] */
40+
41+PUSHLOCAL,/* b - LOC[b] */
42+
43+GETGLOBALW,/* w - VAR[CNST[w]] */
44+GETGLOBAL,/* b - VAR[CNST[b]] */
45+
46+GETTABLE,/* - i t t[i] */
47+
48+GETDOTTEDW,/* w t t[CNST[w]] */
49+GETDOTTED,/* b t t[CNST[b]] */
50+
51+PUSHSELFW,/* w t t t[CNST[w]] */
52+PUSHSELF,/* b t t t[CNST[b]] */
53+
54+CREATEARRAYW,/* w - newarray(size = w) */
55+CREATEARRAY,/* b - newarray(size = b) */
56+
57+SETLOCAL,/* b x - LOC[b]=x */
58+
59+SETGLOBALW,/* w x - VAR[CNST[w]]=x */
60+SETGLOBAL,/* b x - VAR[CNST[b]]=x */
61+
62+SETTABLEPOP,/* - v i t - t[i]=v */
63+
64+SETTABLE,/* b v a_b...a_1 i t a_b...a_1 i t t[i]=v */
65+
66+SETLISTW,/* w c v_c...v_1 t t t[i+w*FPF]=v_i */
67+SETLIST,/* b c v_c...v_1 t t t[i+b*FPF]=v_i */
68+
69+SETMAP,/* b v_b k_b ...v_0 k_0 t t t[k_i]=v_i */
70+
71+NEQOP,/* - y x (x~=y)? 1 : nil */
72+EQOP,/* - y x (x==y)? 1 : nil */
73+LTOP,/* - y x (x<y)? 1 : nil */
74+LEOP,/* - y x (x<y)? 1 : nil */
75+GTOP,/* - y x (x>y)? 1 : nil */
76+GEOP,/* - y x (x>=y)? 1 : nil */
77+ADDOP,/* - y x x+y */
78+SUBOP,/* - y x x-y */
79+MULTOP,/* - y x x*y */
80+DIVOP,/* - y x x/y */
81+POWOP,/* - y x x^y */
82+CONCOP,/* - y x x..y */
83+MINUSOP,/* - x -x */
84+NOTOP,/* - x (x==nil)? 1 : nil */
85+
86+ONTJMPW,/* w x (x!=nil)? x : - (x!=nil)? PC+=w */
87+ONTJMP,/* b x (x!=nil)? x : - (x!=nil)? PC+=b */
88+ONFJMPW,/* w x (x==nil)? x : - (x==nil)? PC+=w */
89+ONFJMP,/* b x (x==nil)? x : - (x==nil)? PC+=b */
90+JMPW,/* w - - PC+=w */
91+JMP,/* b - - PC+=b */
92+IFFJMPW,/* w x - (x==nil)? PC+=w */
93+IFFJMP,/* b x - (x==nil)? PC+=b */
94+IFTUPJMPW,/* w x - (x!=nil)? PC-=w */
95+IFTUPJMP,/* b x - (x!=nil)? PC-=b */
96+IFFUPJMPW,/* w x - (x==nil)? PC-=w */
97+IFFUPJMP,/* b x - (x==nil)? PC-=b */
98+
99+CLOSUREW,/* w c v_c...v_1 closure(CNST[w], v_c...v_1) */
100+CLOSURE,/* b c v_c...v_1 closure(CNST[b], v_c...v_1) */
101+
102+SETLINEW,/* w - - LINE=w */
103+SETLINE,/* b - - LINE=b */
104+
105+LONGARGW,/* w (add w*(1<<16) to arg of next instruction) */
106+LONGARG,/* b (add b*(1<<16) to arg of next instruction) */
107+
108+CHECKSTACK /* b (assert #temporaries == b; only for internal debuging!) */
172109
173110 } OpCode;
174111
175112
176113 #define RFIELDS_PER_FLUSH 32 /* records (SETMAP) */
177−#define LFIELDS_PER_FLUSH 64 /* lists (SETLIST) */
114+#define LFIELDS_PER_FLUSH 64 /* FPF - lists (SETLIST) */
115+
116+#define ZEROVARARG 128
117+
118+
119+/* maximum value of an arg of 3 bytes; must fit in an "int" */
120+#if MAX_INT < (1<<24)
121+#define MAX_ARG MAX_INT
122+#else
123+#define MAX_ARG ((1<<24)-1)
124+#endif
125+
126+/* maximum value of a word of 2 bytes; cannot be bigger than MAX_ARG */
127+#if MAX_ARG < (1<<16)
128+#define MAX_WORD MAX_ARG
129+#else
130+#define MAX_WORD ((1<<16)-1)
131+#endif
132+
133+
134+/* maximum value of a byte */
135+#define MAX_BYTE ((1<<8)-1)
178136
179−#define ZEROVARARG 64
180137
181138 #endif
src/lparser.c+314−256
@@ -1,11 +1,12 @@
11 /*
2−** $Id: lparser.c,v 1.3 1998/07/06 22:07:51 roberto Exp $
2+** $Id: lparser.c,v 1.37 1999/06/17 17:04:03 roberto Exp $
33 ** LL(1) Parser and code generator for Lua
44 ** See Copyright Notice in lua.h
55 */
66
77
88 #include <stdio.h>
9+#include <string.h>
910
1011 #include "lauxlib.h"
1112 #include "ldo.h"
@@ -21,35 +22,48 @@ · 9 unmodified lines
2122 #include "lzio.h"
2223
2324
24−/* for limit numbers in error messages */
25−#define MES_LIM(x) "(limit=" x ")"
26−
2725
2826 /* size of a "normal" jump instruction: OpCode + 1 byte */
2927 #define JMPSIZE 2
3028
3129 /* maximum number of local variables */
32−#define MAXLOCALS 32
33−#define SMAXLOCALS "32"
30+#ifndef MAXLOCALS
31+#define MAXLOCALS 200 /* arbitrary limit (<256) */
32+#endif
3433
3534
3635 /* maximum number of upvalues */
37−#define MAXUPVALUES 16
38−#define SMAXUPVALUES "16"
36+#ifndef MAXUPVALUES
37+#define MAXUPVALUES 32 /* arbitrary limit (<256) */
38+#endif
39+
40+
41+/* maximum number of variables in the left side of an assignment */
42+#ifndef MAXVARSLH
43+#define MAXVARSLH 100 /* arbitrary limit (<255) */
44+#endif
45+
46+
47+/* maximum number of parameters in a function */
48+#ifndef MAXPARAMS
49+#define MAXPARAMS 100 /* arbitrary limit (<ZEROVARARG) */
50+#endif
3951
4052
4153 /*
4254 ** Variable descriptor:
43−** must include a "exp" option because LL(1) cannot distinguish
55+** must include an "exp" option because LL(1) cannot distinguish
4456 ** between variables, upvalues and function calls on first sight.
45−** VGLOBAL: info is constant index of global name
46−** VLOCAL: info is stack index
47−** VDOT: info is constant index of index name
48−** VEXP: info is pc index of "nparam" of function call (or 0 if exp is closed)
4957 */
50−typedef enum {VGLOBAL, VLOCAL, VDOT, VINDEXED, VEXP} varkind;
51−
52−typedef struct {
58+typedef enum {
59+ VGLOBAL, /* info is constant index of global name */
60+ VLOCAL, /* info is stack index */
61+ VDOT, /* info is constant index of index name */
62+ VINDEXED, /* no info (table and index are on the stack) */
63+ VEXP /* info is pc index of "nparam" of a call (or 0 if exp is closed) */
64+} varkind;
65+
66+typedef struct vardesc {
5367 varkind k;
5468 int info;
5569 } vardesc;
@@ -61,7 +75,7 @@ typedef struct { · 5 unmodified lines
6175 ** and, if last expression is open (a function call),
6276 ** where is its pc index of "nparam"
6377 */
64−typedef struct {
78+typedef struct listdesc {
6579 int n;
6680 int pc; /* 0 if last expression is closed */
6781 } listdesc;
@@ -73,7 +87,7 @@ typedef struct { · 5 unmodified lines
7387 ** it is a list constructor (k = 0) or a record constructor (k = 1)
7488 ** or empty (k = ';' or '}')
7589 */
76−typedef struct {
90+typedef struct constdesc {
7791 int n;
7892 int k;
7993 } constdesc;
@@ -88,16 +102,16 @@ typedef struct FuncState { · 8 unmodified lines
88102 int maxstacksize; /* maximum number of values on activation register */
89103 int nlocalvar; /* number of active local variables */
90104 int nupvalues; /* number of upvalues */
91− int nvars; /* number of entries in f->locvars */
92− int maxcode; /* size of f->code */
93− int maxvars; /* size of f->locvars (-1 if no debug information) */
94− int maxconsts; /* size of f->consts */
105+ int nvars; /* number of entries in f->locvars (-1 if no debug information) */
95106 int lastsetline; /* line where last SETLINE was issued */
96107 vardesc upvalues[MAXUPVALUES]; /* upvalues */
97108 TaggedString *localvar[MAXLOCALS]; /* store local variable names */
98109 } FuncState;
99110
100111
112+/*
113+** prototypes for non-terminal functions
114+*/
101115 static int assignment (LexState *ls, vardesc *v, int nvars);
102116 static int cond (LexState *ls);
103117 static int funcname (LexState *ls, vardesc *v);
@@ -117,22 +131,28 @@ static void exp1 (LexState *ls); · 13 unmodified lines
117131 static void exp2 (LexState *ls, vardesc *v);
118132 static void explist (LexState *ls, listdesc *e);
119133 static void explist1 (LexState *ls, listdesc *e);
120−static void ifpart (LexState *ls);
134+static void ifpart (LexState *ls, int line);
121135 static void parlist (LexState *ls);
122136 static void part (LexState *ls, constdesc *cd);
123137 static void recfield (LexState *ls);
124138 static void ret (LexState *ls);
125−static void simpleexp (LexState *ls, vardesc *v);
126139 static void statlist (LexState *ls);
127140 static void var_or_func (LexState *ls, vardesc *v);
128141 static void var_or_func_tail (LexState *ls, vardesc *v);
129142
130143
131144
145+static void checklimit (LexState *ls, int val, int limit, char *msg) {
146+ if (val > limit) {
147+ char buff[100];
148+ sprintf(buff, "too many %s (limit=%d)", msg, limit);
149+ luaX_error(ls, buff);
150+ }
151+}
152+
153+
132154 static void check_pc (FuncState *fs, int n) {
133− if (fs->pc+n > fs->maxcode)
134− fs->maxcode = luaM_growvector(&fs->f->code, fs->maxcode,
135− Byte, codeEM, MAX_INT);
155+ luaM_growvector(fs->f->code, fs->pc, n, Byte, codeEM, MAX_INT);
136156 }
137157
138158
@@ -146,76 +166,79 @@ static void deltastack (LexState *ls, int delta) { · 7 unmodified lines
146166 FuncState *fs = ls->fs;
147167 fs->stacksize += delta;
148168 if (fs->stacksize > fs->maxstacksize) {
149− if (fs->stacksize > 255)
169+ if (fs->stacksize > MAX_BYTE)
150170 luaX_error(ls, "function/expression too complex");
151171 fs->maxstacksize = fs->stacksize;
152172 }
153173 }
154174
155175
156−static int code_oparg_at (LexState *ls, int pc, OpCode op, int builtin,
157− int arg, int delta) {
176+static void code_oparg_at (LexState *ls, int pc, OpCode op,
177+ int arg, int delta) {
158178 Byte *code = ls->fs->f->code;
159179 deltastack(ls, delta);
160− if (arg < builtin) {
161− code[pc] = op+1+arg;
162− return 1;
180+ if (arg <= MAX_BYTE) {
181+ code[pc] = (Byte)op;
182+ code[pc+1] = (Byte)arg;
163183 }
164− else if (arg <= 255) {
165− code[pc] = op;
166− code[pc+1] = arg;
167− return 2;
168− }
169− else if (arg <= MAX_WORD) {
170− code[pc] = op+1+builtin;
171− code[pc+1] = arg>>8;
172− code[pc+2] = arg&0xFF;
173− return 3;
184+ else if (arg > MAX_ARG)
185+ luaX_error(ls, "code too long");
186+ else { /* MAX_BYTE < arg < MAX_ARG */
187+ if (arg > MAX_WORD) {
188+ code[pc] = (Byte)LONGARG;
189+ code[pc+1] = (Byte)(arg>>16);
190+ pc += 2;
191+ }
192+ code[pc] = (Byte)(op-1); /* opcode for word argument */
193+ code[pc+1] = (Byte)((arg&0xFFFF)>>8);
194+ code[pc+2] = (Byte)(arg&0xFF);
174195 }
175− else luaX_error(ls, "code too long " MES_LIM("64K"));
176− return 0; /* to avoid warnings */
177196 }
178197
179198
180−static int fix_opcode (LexState *ls, int pc, OpCode op, int builtin, int arg) {
181− FuncState *fs = ls->fs;
182− TProtoFunc *f = fs->f;
183− if (arg < builtin) { /* close space */
184− luaO_memdown(f->code+pc+1, f->code+pc+2, fs->pc-(pc+2));
185− fs->pc--;
186− }
187− else if (arg > 255) { /* open space */
188− check_pc(fs, 1);
189− luaO_memup(f->code+pc+1, f->code+pc, fs->pc-pc);
190− fs->pc++;
199+static int codesize (int arg) {
200+ if (arg <= MAX_BYTE) return 2; /* opcode + 1 byte */
201+ else if (arg <= MAX_WORD) return 3; /* opcode + 1 word (2 bytes) */
202+ else return 5; /* LONGARG + 1 byte + opcode + 1 word (2 bytes) */
203+}
204+
205+
206+static int fix_opcode (LexState *ls, int pc, OpCode op, int arg) {
207+ int tomove = codesize(arg)-2;
208+ if (tomove > 0) { /* need to open space? */
209+ FuncState *fs = ls->fs;
210+ TProtoFunc *f = fs->f;
211+ check_pc(fs, tomove);
212+ luaO_memup(f->code+pc+tomove, f->code+pc, fs->pc-pc);
213+ fs->pc += tomove;
191214 }
192− return code_oparg_at(ls, pc, op, builtin, arg, 0) - 2;
215+ code_oparg_at(ls, pc, op, arg, 0);
216+ return tomove;
193217 }
194218
195−static void code_oparg (LexState *ls, OpCode op, int builtin, int arg,
196− int delta) {
197− check_pc(ls->fs, 3); /* maximum code size */
198− ls->fs->pc += code_oparg_at(ls, ls->fs->pc, op, builtin, arg, delta);
219+
220+static void code_oparg (LexState *ls, OpCode op, int arg, int delta) {
221+ int size = codesize(arg);
222+ check_pc(ls->fs, size);
223+ code_oparg_at(ls, ls->fs->pc, op, arg, delta);
224+ ls->fs->pc += size;
199225 }
200226
201227
202228 static void code_opcode (LexState *ls, OpCode op, int delta) {
203229 deltastack(ls, delta);
204− code_byte(ls->fs, op);
230+ code_byte(ls->fs, (Byte)op);
205231 }
206232
207233
208234 static void code_constant (LexState *ls, int c) {
209− code_oparg(ls, PUSHCONSTANT, 8, c, 1);
235+ code_oparg(ls, PUSHCONSTANT, c, 1);
210236 }
211237
212238
213239 static int next_constant (FuncState *fs) {
214240 TProtoFunc *f = fs->f;
215− if (f->nconsts >= fs->maxconsts) {
216− fs->maxconsts = luaM_growvector(&f->consts, fs->maxconsts, TObject,
217− constantEM, MAX_WORD);
218− }
241+ luaM_growvector(f->consts, f->nconsts, 1, TObject, constantEM, MAX_ARG);
219242 return f->nconsts++;
220243 }
221244
@@ -249,9 +272,9 @@ static int real_constant (FuncState *fs, real r) { · 27 unmodified lines
249272 if (ttype(&cnt[c]) == LUA_T_NUMBER && nvalue(&cnt[c]) == r)
250273 return c;
251274 }
252− /* not found; create a luaM_new entry */
275+ /* not found; create a new entry */
253276 c = next_constant(fs);
254− cnt = fs->f->consts; /* 'next_constant' may reallocate this vector */
277+ cnt = fs->f->consts; /* 'next_constant' may have reallocated this vector */
255278 ttype(&cnt[c]) = LUA_T_NUMBER;
256279 nvalue(&cnt[c]) = r;
257280 return c;
@@ -259,9 +282,11 @@ static int real_constant (FuncState *fs, real r) { · 1 unmodified line
259282
260283
261284 static void code_number (LexState *ls, real f) {
262− int i;
263− if (f >= 0 && f <= (real)MAX_WORD && (real)(i=(int)f) == f)
264− code_oparg(ls, PUSHNUMBER, 3, i, 1); /* f has a short integer value */
285+ real af = (f<0) ? -f : f;
286+ if (0 <= af && af <= (real)MAX_WORD && (int)af == af) {
287+ /* abs(f) has a short integer value */
288+ code_oparg(ls, (f<0) ? PUSHNUMBERNEG : PUSHNUMBER, (int)af, 1);
289+ }
265290 else
266291 code_constant(ls, real_constant(ls->fs, f));
267292 }
@@ -269,24 +294,23 @@ static void code_number (LexState *ls, real f) { · 1 unmodified line
269294
270295 static void flush_record (LexState *ls, int n) {
271296 if (n > 0)
272− code_oparg(ls, SETMAP, 1, n-1, -2*n);
297+ code_oparg(ls, SETMAP, n-1, -2*n);
273298 }
274299
275300
276301 static void flush_list (LexState *ls, int m, int n) {
277− if (n == 0) return;
278− code_oparg(ls, SETLIST, 1, m, -n);
279− code_byte(ls->fs, n);
302+ if (n > 0) {
303+ code_oparg(ls, SETLIST, m, -n);
304+ code_byte(ls->fs, (Byte)n);
305+ }
280306 }
281307
282308
283309 static void luaI_registerlocalvar (FuncState *fs, TaggedString *varname,
284310 int line) {
285− if (fs->maxvars != -1) { /* debug information? */
311+ if (fs->nvars != -1) { /* debug information? */
286312 TProtoFunc *f = fs->f;
287− if (fs->nvars >= fs->maxvars)
288− fs->maxvars = luaM_growvector(&f->locvars, fs->maxvars,
289− LocVar, "", MAX_WORD);
313+ luaM_growvector(f->locvars, fs->nvars, 1, LocVar, "", MAX_INT);
290314 f->locvars[fs->nvars].varname = varname;
291315 f->locvars[fs->nvars].line = line;
292316 fs->nvars++;
@@ -301,10 +325,8 @@ static void luaI_unregisterlocalvar (FuncState *fs, int line) { · 8 unmodified lines
301325
302326 static void store_localvar (LexState *ls, TaggedString *name, int n) {
303327 FuncState *fs = ls->fs;
304− if (fs->nlocalvar+n < MAXLOCALS)
305− fs->localvar[fs->nlocalvar+n] = name;
306− else
307− luaX_error(ls, "too many local variables " MES_LIM(SMAXLOCALS));
328+ checklimit(ls, fs->nlocalvar+n+1, MAXLOCALS, "local variables");
329+ fs->localvar[fs->nlocalvar+n] = name;
308330 luaI_registerlocalvar(fs, name, ls->linenumber);
309331 }
310332
@@ -315,6 +337,16 @@ static void add_localvar (LexState *ls, TaggedString *name) { · 4 unmodified lines
315337 }
316338
317339
340+static void correctvarlines (LexState *ls, int nvars) {
341+ FuncState *fs = ls->fs;
342+ if (fs->nvars != -1) { /* debug information? */
343+ for (; nvars; nvars--) { /* correct line information */
344+ fs->f->locvars[fs->nvars-nvars].line = fs->lastsetline;
345+ }
346+ }
347+}
348+
349+
318350 static int aux_localname (FuncState *fs, TaggedString *n) {
319351 int i;
320352 for (i=fs->nlocalvar-1; i >= 0; i--)
@@ -326,13 +358,13 @@ static int aux_localname (FuncState *fs, TaggedString *n) { · 5 unmodified lines
326358 static void singlevar (LexState *ls, TaggedString *n, vardesc *var, int prev) {
327359 FuncState *fs = prev ? ls->fs->prev : ls->fs;
328360 int i = aux_localname(fs, n);
329− if (i >= 0) { /* local value */
361+ if (i >= 0) { /* local value? */
330362 var->k = VLOCAL;
331363 var->info = i;
332364 }
333− else { /* check shadowing */
365+ else {
334366 FuncState *level = fs;
335− while ((level = level->prev) != NULL)
367+ while ((level = level->prev) != NULL) /* check shadowing */
336368 if (aux_localname(level, n) >= 0)
337369 luaX_syntaxerror(ls, "cannot access a variable in outer scope", n->str);
338370 var->k = VGLOBAL;
@@ -351,29 +383,26 @@ static int indexupvalue (LexState *ls, TaggedString *n) { · 12 unmodified lines
351383 return i;
352384 }
353385 /* new one */
354− if (++(fs->nupvalues) > MAXUPVALUES)
355− luaX_error(ls, "too many upvalues in a single function "
356− MES_LIM(SMAXUPVALUES));
386+ ++(fs->nupvalues);
387+ checklimit(ls, fs->nupvalues, MAXUPVALUES, "upvalues");
357388 fs->upvalues[i] = v; /* i = fs->nupvalues - 1 */
358389 return i;
359390 }
360391
361392
362393 static void pushupvalue (LexState *ls, TaggedString *n) {
363− int i;
364394 if (ls->fs->prev == NULL)
365395 luaX_syntaxerror(ls, "cannot access upvalue in main", n->str);
366396 if (aux_localname(ls->fs, n) >= 0)
367397 luaX_syntaxerror(ls, "cannot access an upvalue in current scope", n->str);
368− i = indexupvalue(ls, n);
369− code_oparg(ls, PUSHUPVALUE, 2, i, 1);
398+ code_oparg(ls, PUSHUPVALUE, indexupvalue(ls, n), 1);
370399 }
371400
372401
373402
374403 static void check_debugline (LexState *ls) {
375− if (lua_debug && ls->linenumber != ls->fs->lastsetline) {
376− code_oparg(ls, SETLINE, 0, ls->linenumber, 0);
404+ if (L->debug && ls->linenumber != ls->fs->lastsetline) {
405+ code_oparg(ls, SETLINE, ls->linenumber, 0);
377406 ls->fs->lastsetline = ls->linenumber;
378407 }
379408 }
@@ -381,22 +410,22 @@ static void check_debugline (LexState *ls) { · 1 unmodified line
381410
382411 static void adjuststack (LexState *ls, int n) {
383412 if (n > 0)
384− code_oparg(ls, POP, 2, n-1, -n);
413+ code_oparg(ls, POP, n, -n);
385414 else if (n < 0)
386− code_oparg(ls, PUSHNIL, 1, (-n)-1, -n);
415+ code_oparg(ls, PUSHNIL, (-n)-1, -n);
387416 }
388417
389418
390419 static void close_exp (LexState *ls, int pc, int nresults) {
391− if (pc > 0) { /* expression is an open function call */
420+ if (pc > 0) { /* expression is an open function call? */
392421 Byte *code = ls->fs->f->code;
393− int nparams = code[pc]; /* save nparams */
394− pc += fix_opcode(ls, pc-2, CALLFUNC, 2, nresults);
395− code[pc] = nparams; /* restore nparams */
396− if (nresults != MULT_RET)
397− deltastack(ls, nresults); /* "push" results */
398− deltastack(ls, -(nparams+1)); /* "pop" params and function */
422+ code[pc-1] = (Byte)nresults; /* set nresults */
423+ /* push results, pop params (at code[pc]) and function */
424+ deltastack(ls, nresults-(code[pc]+1));
399425 }
426+#ifdef DEBUG
427+ code_oparg(ls, CHECKSTACK, ls->fs->stacksize, 0);
428+#endif
400429 }
401430
402431
@@ -408,7 +437,7 @@ static void adjust_mult_assign (LexState *ls, int nvars, listdesc *d) { · 5 unmodified lines
408437 }
409438 else { /* must correct function call */
410439 diff--; /* do not count function call itself */
411− if (diff < 0) { /* more variables than values */
440+ if (diff <= 0) { /* more variables than values? */
412441 /* function call must provide extra values */
413442 close_exp(ls, d->pc, -diff);
414443 }
@@ -423,29 +452,39 @@ static void adjust_mult_assign (LexState *ls, int nvars, listdesc *d) { · 8 unmodified lines
423452 static void code_args (LexState *ls, int nparams, int dots) {
424453 FuncState *fs = ls->fs;
425454 fs->nlocalvar += nparams; /* "self" may already be there */
455+ checklimit(ls, fs->nlocalvar, MAXPARAMS, "parameters");
426456 nparams = fs->nlocalvar;
427457 if (!dots) {
428− fs->f->code[1] = nparams; /* fill-in arg information */
458+ fs->f->code[1] = (Byte)nparams; /* fill-in arg information */
429459 deltastack(ls, nparams);
430460 }
431461 else {
432− fs->f->code[1] = nparams+ZEROVARARG;
462+ fs->f->code[1] = (Byte)(nparams+ZEROVARARG);
433463 deltastack(ls, nparams+1);
434464 add_localvar(ls, luaS_new("arg"));
435465 }
436466 }
437467
438468
469+static void unloaddot (LexState *ls, vardesc *v) {
470+ /* dotted variables <a.x> must be stored like regular indexed vars <a["x"]> */
471+ if (v->k == VDOT) {
472+ code_constant(ls, v->info);
473+ v->k = VINDEXED;
474+ }
475+}
476+
477+
439478 static void lua_pushvar (LexState *ls, vardesc *var) {
440479 switch (var->k) {
441480 case VLOCAL:
442− code_oparg(ls, PUSHLOCAL, 8, var->info, 1);
481+ code_oparg(ls, PUSHLOCAL, var->info, 1);
443482 break;
444483 case VGLOBAL:
445− code_oparg(ls, GETGLOBAL, 8, var->info, 1);
484+ code_oparg(ls, GETGLOBAL, var->info, 1);
446485 break;
447486 case VDOT:
448− code_oparg(ls, GETDOTTED, 8, var->info, 0);
487+ code_oparg(ls, GETDOTTED, var->info, 0);
449488 break;
450489 case VINDEXED:
451490 code_opcode(ls, GETTABLE, -1);
@@ -462,13 +501,13 @@ static void lua_pushvar (LexState *ls, vardesc *var) { · 10 unmodified lines
462501 static void storevar (LexState *ls, vardesc *var) {
463502 switch (var->k) {
464503 case VLOCAL:
465− code_oparg(ls, SETLOCAL, 8, var->info, -1);
504+ code_oparg(ls, SETLOCAL, var->info, -1);
466505 break;
467506 case VGLOBAL:
468− code_oparg(ls, SETGLOBAL, 8, var->info, -1);
507+ code_oparg(ls, SETGLOBAL, var->info, -1);
469508 break;
470509 case VINDEXED:
471− code_opcode(ls, SETTABLE0, -3);
510+ code_opcode(ls, SETTABLEPOP, -3);
472511 break;
473512 default:
474513 LUA_INTERNALERROR("invalid var kind to store");
@@ -478,21 +517,20 @@ static void storevar (LexState *ls, vardesc *var) { · 3 unmodified lines
478517
479518 static int fix_jump (LexState *ls, int pc, OpCode op, int n) {
480519 /* jump is relative to position following jump instruction */
481− return fix_opcode(ls, pc, op, 0, n-(pc+JMPSIZE));
520+ return fix_opcode(ls, pc, op, n-(pc+JMPSIZE));
482521 }
483522
484523
485524 static void fix_upjmp (LexState *ls, OpCode op, int pos) {
486525 int delta = ls->fs->pc+JMPSIZE - pos; /* jump is relative */
487− if (delta > 255) delta++;
488− code_oparg(ls, op, 0, delta, 0);
526+ code_oparg(ls, op, delta+(codesize(delta)-2), 0);
489527 }
490528
491529
492530 static void codeIf (LexState *ls, int thenAdd, int elseAdd) {
493531 FuncState *fs = ls->fs;
494532 int elseinit = elseAdd+JMPSIZE;
495− if (fs->pc == elseinit) { /* no else part */
533+ if (fs->pc == elseinit) { /* no else part? */
496534 fs->pc -= JMPSIZE;
497535 elseinit = fs->pc;
498536 }
@@ -513,13 +551,14 @@ static void func_onstack (LexState *ls, FuncState *func) { · 14 unmodified lines
513551 else {
514552 for (i=0; i<func->nupvalues; i++)
515553 lua_pushvar(ls, &func->upvalues[i]);
516− code_oparg(ls, CLOSURE, 0, c, -func->nupvalues+1);
517− code_byte(fs, func->nupvalues);
554+ deltastack(ls, 1); /* CLOSURE puts one extra element (before poping) */
555+ code_oparg(ls, CLOSURE, c, -func->nupvalues);
556+ code_byte(fs, (Byte)func->nupvalues);
518557 }
519558 }
520559
521560
522−static void init_state (LexState *ls, FuncState *fs, TaggedString *filename) {
561+static void init_state (LexState *ls, FuncState *fs, TaggedString *source) {
523562 TProtoFunc *f = luaF_newproto();
524563 fs->prev = ls->fs; /* linked list of funcstates */
525564 ls->fs = fs;
@@ -529,17 +568,15 @@ static void init_state (LexState *ls, FuncState *fs, TaggedString *filename) { · 3 unmodified lines
529568 fs->nupvalues = 0;
530569 fs->lastsetline = 0;
531570 fs->f = f;
532− f->fileName = filename;
571+ f->source = source;
533572 fs->pc = 0;
534− fs->maxcode = 0;
535573 f->code = NULL;
536− fs->maxconsts = 0;
537− if (lua_debug)
538− fs->nvars = fs->maxvars = 0;
539− else
540− fs->maxvars = -1; /* flag no debug information */
541− code_byte(fs, 0); /* to be filled with stacksize */
574+ fs->nvars = (L->debug) ? 0 : -1; /* flag no debug information? */
575+ code_byte(fs, 0); /* to be filled with maxstacksize */
542576 code_byte(fs, 0); /* to be filled with arg information */
577+ /* push function (to avoid GC) */
578+ tfvalue(L->stack.top) = f; ttype(L->stack.top) = LUA_T_PROTO;
579+ incr_top;
543580 }
544581
545582
@@ -547,14 +584,15 @@ static void close_func (LexState *ls) { · 1 unmodified line
547584 FuncState *fs = ls->fs;
548585 TProtoFunc *f = fs->f;
549586 code_opcode(ls, ENDCODE, 0);
550− f->code[0] = fs->maxstacksize;
551− f->code = luaM_reallocvector(f->code, fs->pc, Byte);
552− f->consts = luaM_reallocvector(f->consts, f->nconsts, TObject);
553− if (fs->maxvars != -1) { /* debug information? */
587+ f->code[0] = (Byte)fs->maxstacksize;
588+ luaM_reallocvector(f->code, fs->pc, Byte);
589+ luaM_reallocvector(f->consts, f->nconsts, TObject);
590+ if (fs->nvars != -1) { /* debug information? */
554591 luaI_registerlocalvar(fs, NULL, -1); /* flag end of vector */
555− f->locvars = luaM_reallocvector(f->locvars, fs->nvars, LocVar);
592+ luaM_reallocvector(f->locvars, fs->nvars, LocVar);
556593 }
557594 ls->fs = fs->prev;
595+ L->stack.top--; /* pop function */
558596 }
559597
560598
@@ -562,13 +600,11 @@ static void close_func (LexState *ls) { · 1 unmodified line
562600 static int expfollow [] = {ELSE, ELSEIF, THEN, IF, WHILE, REPEAT, DO, NAME,
563601 LOCAL, FUNCTION, END, UNTIL, RETURN, ')', ']', '}', ';', EOS, ',', 0};
564602
603+
565604 static int is_in (int tok, int *toks) {
566− int *t = toks;
567− while (*t) {
568− if (*t == tok)
569− return t-toks;
570− t++;
571− }
605+ int *t;
606+ for (t=toks; *t; t++)
607+ if (*t == tok) return t-toks;
572608 return -1;
573609 }
574610
@@ -580,19 +616,25 @@ static void next (LexState *ls) { · 5 unmodified lines
580616
581617 static void error_expected (LexState *ls, int token) {
582618 char buff[100], t[TOKEN_LEN];
583− luaX_token2str(ls, token, t);
619+ luaX_token2str(token, t);
584620 sprintf(buff, "`%s' expected", t);
585621 luaX_error(ls, buff);
586622 }
587623
624+
625+static void error_unexpected (LexState *ls) {
626+ luaX_error(ls, "unexpected token");
627+}
628+
629+
588630 static void error_unmatched (LexState *ls, int what, int who, int where) {
589631 if (where == ls->linenumber)
590632 error_expected(ls, what);
591633 else {
592634 char buff[100];
593635 char t_what[TOKEN_LEN], t_who[TOKEN_LEN];
594− luaX_token2str(ls, what, t_what);
595− luaX_token2str(ls, who, t_who);
636+ luaX_token2str(what, t_what);
637+ luaX_token2str(who, t_who);
596638 sprintf(buff, "`%s' expected (to close `%s' at line %d)",
597639 t_what, t_who, where);
598640 luaX_error(ls, buff);
@@ -612,13 +654,18 @@ static void check_match (LexState *ls, int what, int who, int where) { · 13 unmodified lines
612654 next(ls);
613655 }
614656
615−static TaggedString *checkname (LexState *ls) {
616− TaggedString *ts;
657+static int checkname (LexState *ls) {
658+ int sc;
617659 if (ls->token != NAME)
618660 luaX_error(ls, "`NAME' expected");
619− ts = ls->seminfo.ts;
661+ sc = string_constant(ls->fs, ls->seminfo.ts);
620662 next(ls);
621− return ts;
663+ return sc;
664+}
665+
666+
667+static TaggedString *str_checkname (LexState *ls) {
668+ return tsvalue(&ls->fs->f->consts[checkname(ls)]);
622669 }
623670
624671
@@ -669,12 +716,9 @@ static int stat (LexState *ls) { · 44 unmodified lines
669716 int line = ls->linenumber; /* may be needed for error messages */
670717 FuncState *fs = ls->fs;
671718 switch (ls->token) {
672− case IF: { /* stat -> IF ifpart END */
673− next(ls);
674− ifpart(ls);
675− check_match(ls, END, IF, line);
719+ case IF: /* stat -> IF ifpart END */
720+ ifpart(ls, line);
676721 return 1;
677− }
678722
679723 case WHILE: { /* stat -> WHILE cond DO block END */
680724 TProtoFunc *f = fs->f;
@@ -732,7 +776,8 @@ static int stat (LexState *ls) { · 51 unmodified lines
732776 next(ls);
733777 nvars = localnamelist(ls);
734778 decinit(ls, &d);
735− ls->fs->nlocalvar += nvars;
779+ fs->nlocalvar += nvars;
780+ correctvarlines(ls, nvars); /* vars will be alive only after decinit */
736781 adjust_mult_assign(ls, nvars, &d);
737782 return 1;
738783 }
@@ -746,8 +791,8 @@ static int stat (LexState *ls) { · 7 unmodified lines
746791 luaX_error(ls, "syntax error");
747792 close_exp(ls, v.info, 0);
748793 }
749− else {
750− int left = assignment(ls, &v, 1); /* stat -> ['%'] NAME assignment */
794+ else { /* stat -> ['%'] NAME assignment */
795+ int left = assignment(ls, &v, 1);
751796 adjuststack(ls, left); /* remove eventual 'garbage' left on stack */
752797 }
753798 return 1;
@@ -758,7 +803,7 @@ static int stat (LexState *ls) { · 4 unmodified lines
758803 return 0;
759804
760805 default:
761− luaX_error(ls, "<statement> expected");
806+ error_unexpected(ls);
762807 return 0; /* to avoid warnings */
763808 }
764809 }
@@ -788,18 +833,18 @@ static void block (LexState *ls) { · 23 unmodified lines
788833 chunk(ls);
789834 adjuststack(ls, fs->nlocalvar - nlocalvar);
790835 for (; fs->nlocalvar > nlocalvar; fs->nlocalvar--)
791− luaI_unregisterlocalvar(fs, ls->linenumber);
836+ luaI_unregisterlocalvar(fs, fs->lastsetline);
792837 }
793838
794839 static int funcname (LexState *ls, vardesc *v) {
795840 /* funcname -> NAME [':' NAME | '.' NAME] */
796841 int needself = 0;
797− singlevar(ls, checkname(ls), v, 0);
842+ singlevar(ls, str_checkname(ls), v, 0);
798843 if (ls->token == ':' || ls->token == '.') {
799844 needself = (ls->token == ':');
800845 next(ls);
801846 lua_pushvar(ls, v);
802− code_string(ls, checkname(ls));
847+ code_constant(ls, checkname(ls));
803848 v->k = VINDEXED;
804849 }
805850 return needself;
@@ -808,7 +853,7 @@ static int funcname (LexState *ls, vardesc *v) { · 2 unmodified lines
808853 static void body (LexState *ls, int needself, int line) {
809854 /* body -> '(' parlist ')' chunk END */
810855 FuncState newfs;
811− init_state(ls, &newfs, ls->fs->f->fileName);
856+ init_state(ls, &newfs, ls->fs->f->source);
812857 newfs.f->lineDefined = line;
813858 check(ls, '(');
814859 if (needself)
@@ -821,36 +866,40 @@ static void body (LexState *ls, int needself, int line) { · 6 unmodified lines
821866 func_onstack(ls, &newfs);
822867 }
823868
824−static void ifpart (LexState *ls) {
869+
870+static void ifpart (LexState *ls, int line) {
825871 /* ifpart -> cond THEN block [ELSE block | ELSEIF ifpart] */
826− int c = cond(ls);
872+ int c;
827873 int e;
874+ next(ls); /* skip IF or ELSEIF */
875+ c = cond(ls);
828876 check(ls, THEN);
829877 block(ls);
830878 e = SaveWord(ls);
831− switch (ls->token) {
832− case ELSE:
833− next(ls);
879+ if (ls->token == ELSEIF)
880+ ifpart(ls, line);
881+ else {
882+ if (optional(ls, ELSE))
834883 block(ls);
835− break;
836−
837− case ELSEIF:
838− next(ls);
839− ifpart(ls);
840− break;
884+ check_match(ls, END, IF, line);
841885 }
842886 codeIf(ls, c, e);
843887 }
844888
889+
845890 static void ret (LexState *ls) {
846891 /* ret -> [RETURN explist sc] */
847− if (ls->token == RETURN) {
892+ if (optional(ls, RETURN)) {
848893 listdesc e;
849894 check_debugline(ls);
850− next(ls);
851− explist(ls, &e);
852− close_exp(ls, e.pc, MULT_RET);
853− code_oparg(ls, RETCODE, 0, ls->fs->nlocalvar, 0);
895+ explist(ls, &e);
896+ if (e.pc > 0) { /* expression is an open function call? */
897+ Byte *code = ls->fs->f->code;
898+ code[e.pc-2] = TAILCALL; /* instead of a conventional CALL */
899+ code[e.pc-1] = (Byte)ls->fs->nlocalvar;
900+ }
901+ else
902+ code_oparg(ls, RETCODE, ls->fs->nlocalvar, 0);
854903 ls->fs->stacksize = ls->fs->nlocalvar; /* removes all temp values */
855904 optional(ls, ';');
856905 }
@@ -863,6 +912,9 @@ static void ret (LexState *ls) { · 6 unmodified lines
863912 ** (EQ=2, NE=3, ... '^'=13). The unary NOT is 0 and UNMINUS is 1.
864913 */
865914
915+#define INDNOT 0
916+#define INDMINUS 1
917+
866918 /* code of first binary operator */
867919 #define FIRSTBIN 2
868920
@@ -879,9 +931,9 @@ static int priority [POW+1] = {5, 5, 1, 1, 1, 1, 1, 1, 2, 3, 3, 4, 4, 6}; · 10 unmodified lines
879931 static OpCode opcodes [POW+1] = {NOTOP, MINUSOP, EQOP, NEQOP, GTOP, LTOP,
880932 LEOP, GEOP, CONCOP, ADDOP, SUBOP, MULTOP, DIVOP, POWOP};
881933
882−#define MAXOPS 20
934+#define MAXOPS 20 /* op's stack size (arbitrary limit) */
883935
884−typedef struct {
936+typedef struct stack_op {
885937 int ops[MAXOPS];
886938 int top;
887939 } stack_op;
@@ -892,39 +944,33 @@ static void exp1 (LexState *ls) { · 4 unmodified lines
892944 exp0(ls, &v);
893945 lua_pushvar(ls, &v);
894946 if (is_in(ls->token, expfollow) < 0)
895− luaX_error(ls, "ill formed expression");
947+ luaX_error(ls, "ill-formed expression");
896948 }
897949
898950
899951 static void exp0 (LexState *ls, vardesc *v) {
952+ /* exp0 -> exp2 {(AND | OR) exp2} */
900953 exp2(ls, v);
901954 while (ls->token == AND || ls->token == OR) {
902− int is_and = (ls->token == AND);
955+ int op = (ls->token == AND) ? ONFJMP : ONTJMP;
903956 int pc;
904957 lua_pushvar(ls, v);
905958 next(ls);
906959 pc = SaveWordPop(ls);
907960 exp2(ls, v);
908961 lua_pushvar(ls, v);
909− fix_jump(ls, pc, (is_and?ONFJMP:ONTJMP), ls->fs->pc);
962+ fix_jump(ls, pc, op, ls->fs->pc);
910963 }
911964 }
912965
913966
914967 static void push (LexState *ls, stack_op *s, int op) {
915− if (s->top == MAXOPS)
968+ if (s->top >= MAXOPS)
916969 luaX_error(ls, "expression too complex");
917970 s->ops[s->top++] = op;
918971 }
919972
920973
921−static void prefix (LexState *ls, stack_op *s) {
922− while (ls->token == NOT || ls->token == '-') {
923− push(ls, s, ls->token==NOT?0:1);
924− next(ls);
925− }
926−}
927−
928974 static void pop_to (LexState *ls, stack_op *s, int prio) {
929975 int op;
930976 while (s->top > 0 && priority[(op=s->ops[s->top-1])] >= prio) {
@@ -933,92 +979,104 @@ static void pop_to (LexState *ls, stack_op *s, int prio) { · 2 unmodified lines
933979 }
934980 }
935981
936−static void exp2 (LexState *ls, vardesc *v) {
937− stack_op s;
938− int op;
939− s.top = 0;
940− prefix(ls, &s);
941− simpleexp(ls, v);
942− while ((op = is_in(ls->token, binop)) >= 0) {
943− op += FIRSTBIN;
944− lua_pushvar(ls, v);
945− /* '^' is right associative, so must 'simulate' a higher priority */
946− pop_to(ls, &s, (op == POW)?priority[op]+1:priority[op]);
947− push(ls, &s, op);
948− next(ls);
949− prefix(ls, &s);
950− simpleexp(ls, v);
951− lua_pushvar(ls, v);
952− }
953− if (s.top > 0) {
954− lua_pushvar(ls, v);
955− pop_to(ls, &s, 0);
956− }
957−}
958−
959−
960−static void simpleexp (LexState *ls, vardesc *v) {
982+static void simpleexp (LexState *ls, vardesc *v, stack_op *s) {
961983 check_debugline(ls);
962984 switch (ls->token) {
963− case '(': /* simpleexp -> '(' exp0 ')' */
964− next(ls);
965− exp0(ls, v);
966− check(ls, ')');
967− break;
968−
969− case NUMBER: /* simpleexp -> NUMBER */
970− code_number(ls, ls->seminfo.r);
985+ case NUMBER: { /* simpleexp -> NUMBER */
986+ real r = ls->seminfo.r;
971987 next(ls);
972− v->k = VEXP; v->info = 0;
988+ /* dirty trick: check whether it is a -NUMBER not followed by '^' */
989+ /* (because the priority of '^' is closer than '-'...) */
990+ if (s->top > 0 && s->ops[s->top-1] == INDMINUS && ls->token != '^') {
991+ s->top--; /* remove '-' from stack */
992+ r = -r;
993+ }
994+ code_number(ls, r);
973995 break;
996+ }
974997
975998 case STRING: /* simpleexp -> STRING */
976− code_string(ls, ls->seminfo.ts);
999+ code_string(ls, ls->seminfo.ts); /* must use 'seminfo' before "next" */
9771000 next(ls);
978− v->k = VEXP; v->info = 0;
9791001 break;
9801002
9811003 case NIL: /* simpleexp -> NIL */
9821004 adjuststack(ls, -1);
9831005 next(ls);
984− v->k = VEXP; v->info = 0;
9851006 break;
9861007
9871008 case '{': /* simpleexp -> constructor */
9881009 constructor(ls);
989− v->k = VEXP; v->info = 0;
9901010 break;
9911011
992− case FUNCTION: { /* simpleexp -> FUNCTION body */
993− int line = ls->linenumber;
1012+ case FUNCTION: /* simpleexp -> FUNCTION body */
9941013 next(ls);
995− body(ls, 0, line);
996− v->k = VEXP; v->info = 0;
1014+ body(ls, 0, ls->linenumber);
9971015 break;
998− }
1016+
1017+ case '(': /* simpleexp -> '(' exp0 ')' */
1018+ next(ls);
1019+ exp0(ls, v);
1020+ check(ls, ')');
1021+ return;
9991022
10001023 case NAME: case '%':
10011024 var_or_func(ls, v);
1002− break;
1025+ return;
10031026
10041027 default:
10051028 luaX_error(ls, "<expression> expected");
1006− break;
1029+ return;
1030+ }
1031+ v->k = VEXP; v->info = 0;
1032+}
1033+
1034+
1035+static void prefixexp (LexState *ls, vardesc *v, stack_op *s) {
1036+ /* prefixexp -> {NOT | '-'} simpleexp */
1037+ while (ls->token == NOT || ls->token == '-') {
1038+ push(ls, s, (ls->token==NOT)?INDNOT:INDMINUS);
1039+ next(ls);
1040+ }
1041+ simpleexp(ls, v, s);
1042+}
1043+
1044+
1045+static void exp2 (LexState *ls, vardesc *v) {
1046+ stack_op s;
1047+ int op;
1048+ s.top = 0;
1049+ prefixexp(ls, v, &s);
1050+ while ((op = is_in(ls->token, binop)) >= 0) {
1051+ op += FIRSTBIN;
1052+ lua_pushvar(ls, v);
1053+ /* '^' is right associative, so must 'simulate' a higher priority */
1054+ pop_to(ls, &s, (op == POW)?priority[op]+1:priority[op]);
1055+ push(ls, &s, op);
1056+ next(ls);
1057+ prefixexp(ls, v, &s);
1058+ lua_pushvar(ls, v);
1059+ }
1060+ if (s.top > 0) {
1061+ lua_pushvar(ls, v);
1062+ pop_to(ls, &s, 0);
10071063 }
10081064 }
10091065
1066+
10101067 static void var_or_func (LexState *ls, vardesc *v) {
10111068 /* var_or_func -> ['%'] NAME var_or_func_tail */
10121069 if (optional(ls, '%')) { /* upvalue? */
1013− pushupvalue(ls, checkname(ls));
1070+ pushupvalue(ls, str_checkname(ls));
10141071 v->k = VEXP;
10151072 v->info = 0; /* closed expression */
10161073 }
10171074 else /* variable name */
1018− singlevar(ls, checkname(ls), v, 0);
1075+ singlevar(ls, str_checkname(ls), v, 0);
10191076 var_or_func_tail(ls, v);
10201077 }
10211078
1079+
10221080 static void var_or_func_tail (LexState *ls, vardesc *v) {
10231081 for (;;) {
10241082 switch (ls->token) {
@@ -1026,7 +1084,7 @@ static void var_or_func_tail (LexState *ls, vardesc *v) { · 1 unmodified line
10261084 next(ls);
10271085 lua_pushvar(ls, v); /* 'v' must be on stack */
10281086 v->k = VDOT;
1029− v->info = string_constant(ls->fs, checkname(ls));
1087+ v->info = checkname(ls);
10301088 break;
10311089
10321090 case '[': /* var_or_func_tail -> '[' exp1 ']' */
@@ -1040,7 +1098,7 @@ static void var_or_func_tail (LexState *ls, vardesc *v) { · 7 unmodified lines
10401098 case ':': /* var_or_func_tail -> ':' NAME funcparams */
10411099 next(ls);
10421100 lua_pushvar(ls, v); /* 'v' must be on stack */
1043− code_oparg(ls, PUSHSELF, 8, string_constant(ls->fs, checkname(ls)), 1);
1101+ code_oparg(ls, PUSHSELF, checkname(ls), 1);
10441102 v->k = VEXP;
10451103 v->info = funcparams(ls, 1);
10461104 break;
@@ -1058,13 +1116,14 @@ static void var_or_func_tail (LexState *ls, vardesc *v) { · 11 unmodified lines
10581116
10591117 static int funcparams (LexState *ls, int slf) {
10601118 FuncState *fs = ls->fs;
1061− int nparams = 1; /* default value */
1119+ int nparams = 1; /* in cases STRING and constructor */
10621120 switch (ls->token) {
10631121 case '(': { /* funcparams -> '(' explist ')' */
1122+ int line = ls->linenumber;
10641123 listdesc e;
10651124 next(ls);
10661125 explist(ls, &e);
1067− check(ls, ')');
1126+ check_match(ls, ')', '(', line);
10681127 close_exp(ls, e.pc, 1);
10691128 nparams = e.n;
10701129 break;
@@ -1075,7 +1134,7 @@ static int funcparams (LexState *ls, int slf) { · 4 unmodified lines
10751134 break;
10761135
10771136 case STRING: /* funcparams -> STRING */
1078− code_string(ls, ls->seminfo.ts);
1137+ code_string(ls, ls->seminfo.ts); /* must use 'seminfo' before "next" */
10791138 next(ls);
10801139 break;
10811140
@@ -1083,9 +1142,9 @@ static int funcparams (LexState *ls, int slf) { · 1 unmodified line
10831142 luaX_error(ls, "function arguments expected");
10841143 break;
10851144 }
1086− code_byte(fs, 0); /* save space for opcode */
1087− code_byte(fs, 0); /* and nresult */
1088− code_byte(fs, nparams+slf);
1145+ code_byte(fs, CALL);
1146+ code_byte(fs, 0); /* save space for nresult */
1147+ code_byte(fs, (Byte)(nparams+slf));
10891148 return fs->pc-1;
10901149 }
10911150
@@ -1131,7 +1190,7 @@ static void parlist (LexState *ls) { · 39 unmodified lines
11311190
11321191 case NAME: /* parlist, tailparlist -> NAME [',' tailparlist] */
11331192 init:
1134− store_localvar(ls, checkname(ls), nparams++);
1193+ store_localvar(ls, str_checkname(ls), nparams++);
11351194 if (ls->token == ',') {
11361195 next(ls);
11371196 switch (ls->token) {
@@ -1158,10 +1217,10 @@ static void parlist (LexState *ls) { · 20 unmodified lines
11581217 static int localnamelist (LexState *ls) {
11591218 /* localnamelist -> NAME {',' NAME} */
11601219 int i = 1;
1161− store_localvar(ls, checkname(ls), 0);
1220+ store_localvar(ls, str_checkname(ls), 0);
11621221 while (ls->token == ',') {
11631222 next(ls);
1164− store_localvar(ls, checkname(ls), i++);
1223+ store_localvar(ls, str_checkname(ls), i++);
11651224 }
11661225 return i;
11671226 }
@@ -1178,13 +1237,11 @@ static void decinit (LexState *ls, listdesc *d) { · 10 unmodified lines
11781237 }
11791238 }
11801239
1240+
11811241 static int assignment (LexState *ls, vardesc *v, int nvars) {
11821242 int left = 0;
1183− /* dotted variables <a.x> must be stored like regular indexed vars <a["x"]> */
1184− if (v->k == VDOT) {
1185− code_constant(ls, v->info);
1186− v->k = VINDEXED;
1187− }
1243+ checklimit(ls, nvars, MAXVARSLH, "variables in a multiple assignment");
1244+ unloaddot(ls, v);
11881245 if (ls->token == ',') { /* assignment -> ',' NAME assignment */
11891246 vardesc nv;
11901247 next(ls);
@@ -1204,12 +1261,13 @@ static int assignment (LexState *ls, vardesc *v, int nvars) { · 13 unmodified lines
12041261 storevar(ls, v);
12051262 }
12061263 else { /* indexed var with values in between*/
1207− code_oparg(ls, SETTABLE, 0, left+(nvars-1), -1);
1208− left += 2; /* table/index are not popped, because they aren't on top */
1264+ code_oparg(ls, SETTABLE, left+(nvars-1), -1);
1265+ left += 2; /* table&index are not popped, because they aren't on top */
12091266 }
12101267 return left;
12111268 }
12121269
1270+
12131271 static void constructor (LexState *ls) {
12141272 /* constructor -> '{' part [';' part] '}' */
12151273 int line = ls->linenumber;
@@ -1229,7 +1287,7 @@ static void constructor (LexState *ls) { · 13 unmodified lines
12291287 nelems += other_cd.n;
12301288 }
12311289 check_match(ls, '}', '{', line);
1232− fix_opcode(ls, pc, CREATEARRAY, 2, nelems);
1290+ fix_opcode(ls, pc, CREATEARRAY, nelems);
12331291 }
12341292
12351293 static void part (LexState *ls, constdesc *cd) {
@@ -1251,7 +1309,7 @@ static void part (LexState *ls, constdesc *cd) { · 15 unmodified lines
12511309 code_string(ls, ls->fs->localvar[v.info]);
12521310 break;
12531311 default:
1254− luaX_error(ls, "`=' unexpected");
1312+ error_unexpected(ls);
12551313 }
12561314 next(ls);
12571315 exp1(ls);
@@ -1316,7 +1374,7 @@ static void recfield (LexState *ls) { · 58 unmodified lines
13161374 /* recfield -> (NAME | '['exp1']') = exp1 */
13171375 switch (ls->token) {
13181376 case NAME:
1319− code_string(ls, checkname(ls));
1377+ code_constant(ls, checkname(ls));
13201378 break;
13211379
13221380 case '[':
src/lparser.h+2−2
@@ -1,6 +1,6 @@
11 /*
2−** $Id: lparser.h,v 1.2 1997/12/22 20:57:18 roberto Exp $
3−** Syntax analizer and code generator
2+** $Id: lparser.h,v 1.3 1999/02/25 19:13:56 roberto Exp $
3+** LL(1) Parser and code generator for Lua
44 ** See Copyright Notice in lua.h
55 */
66
src/lstate.c+12−12
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lstate.c,v 1.6 1998/06/02 20:37:04 roberto Exp $
2+** $Id: lstate.c,v 1.12 1999/05/11 20:08:20 roberto Exp $
33 ** Global State
44 ** See Copyright Notice in lua.h
55 */
@@ -24,11 +24,19 @@ void lua_open (void) · 18 unmodified lines
2424 {
2525 if (lua_state) return;
2626 lua_state = luaM_new(lua_State);
27− L->numCblocks = 0;
2827 L->Cstack.base = 0;
2928 L->Cstack.lua2C = 0;
3029 L->Cstack.num = 0;
3130 L->errorJmp = NULL;
31+ L->Mbuffer = NULL;
32+ L->Mbuffbase = 0;
33+ L->Mbuffsize = 0;
34+ L->Mbuffnext = 0;
35+ L->Cblocks = NULL;
36+ L->numCblocks = 0;
37+ L->debug = 0;
38+ L->callhook = NULL;
39+ L->linehook = NULL;
3240 L->rootproto.next = NULL;
3341 L->rootproto.marked = 0;
3442 L->rootcl.next = NULL;
@@ -37,12 +45,9 @@ void lua_open (void) · 2 unmodified lines
3745 L->rootglobal.marked = 0;
3846 L->roottable.next = NULL;
3947 L->roottable.marked = 0;
48+ L->IMtable = NULL;
4049 L->refArray = NULL;
4150 L->refSize = 0;
42− L->Mbuffsize = 0;
43− L->Mbuffnext = 0;
44− L->Mbuffbase = NULL;
45− L->Mbuffer = NULL;
4651 L->GCthreshold = GARBAGE_BLOCK;
4752 L->nblocks = 0;
4853 luaD_init();
@@ -69,6 +74,7 @@ void lua_close (void) · 20 unmodified lines
6974 luaM_free(L->IMtable);
7075 luaM_free(L->refArray);
7176 luaM_free(L->Mbuffer);
77+ luaM_free(L->Cblocks);
7278 luaM_free(L);
7379 L = NULL;
7480 #ifdef DEBUG
@@ -78,9 +84,3 @@ void lua_close (void) · 3 unmodified lines
7884 }
7985
8086
81−lua_State *lua_setstate (lua_State *st) {
82− lua_State *old = lua_state;
83− lua_state = st;
84− return old;
85−}
86−
src/lstate.h+20−12
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lstate.h,v 1.11 1998/06/24 13:33:00 roberto Exp $
2+** $Id: lstate.h,v 1.19 1999/05/11 20:08:20 roberto Exp $
33 ** Global State
44 ** See Copyright Notice in lua.h
55 */
@@ -11,15 +11,24 @@ · 5 unmodified lines
1111
1212 #include "lobject.h"
1313 #include "lua.h"
14+#include "luadebug.h"
1415
1516
16−#define MAX_C_BLOCKS 10
17−
1817 #define GARBAGE_BLOCK 150
1918
2019
2120 typedef int StkId; /* index to stack elements */
2221
22+
23+/*
24+** "jmp_buf" may be an array, so it is better to make sure it has an
25+** address (and not that it *is* an address...)
26+*/
27+struct lua_longjmp {
28+ jmp_buf b;
29+};
30+
31+
2332 struct Stack {
2433 TObject *top;
2534 TObject *stack;
@@ -34,7 +43,7 @@ struct C_Lua_Stack { · 8 unmodified lines
3443 };
3544
3645
37−typedef struct {
46+typedef struct stringtable {
3847 int size;
3948 int nuse; /* number of elements (including EMPTYs) */
4049 TaggedString **hash;
@@ -53,22 +62,23 @@ struct lua_State { · 12 unmodified lines
5362 /* thread-specific state */
5463 struct Stack stack; /* Lua stack */
5564 struct C_Lua_Stack Cstack; /* C2lua struct */
56− jmp_buf *errorJmp; /* current error recover point */
65+ struct lua_longjmp *errorJmp; /* current error recover point */
5766 char *Mbuffer; /* global buffer */
58− char *Mbuffbase; /* current first position of Mbuffer */
67+ int Mbuffbase; /* current first position of Mbuffer */
5968 int Mbuffsize; /* size of Mbuffer */
6069 int Mbuffnext; /* next position to fill in Mbuffer */
61− struct C_Lua_Stack Cblocks[MAX_C_BLOCKS];
70+ struct C_Lua_Stack *Cblocks;
6271 int numCblocks; /* number of nested Cblocks */
72+ int debug;
73+ lua_CHFunction callhook;
74+ lua_LHFunction linehook;
6375 /* global state */
64− TObject errorim; /* error tag method */
6576 GCnode rootproto; /* list of all prototypes */
6677 GCnode rootcl; /* list of all closures */
6778 GCnode roottable; /* list of all tables */
6879 GCnode rootglobal; /* list of strings with global values */
6980 stringtable *string_root; /* array of hash tables for strings and udata */
7081 struct IM *IMtable; /* table for tag methods */
71− int IMtable_size; /* size of IMtable */
7282 int last_tag; /* last used tag in IMtable */
7383 struct ref *refArray; /* locked objects */
7484 int refSize; /* size of refArray */
@@ -77,10 +87,8 @@ struct lua_State { · 2 unmodified lines
7787 };
7888
7989
80−extern lua_State *lua_state;
81−
82−
8390 #define L lua_state
8491
8592
8693 #endif
94+
src/lstring.c+62−77
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lstring.c,v 1.13 1998/06/19 16:14:09 roberto Exp $
2+** $Id: lstring.c,v 1.19 1999/02/26 15:49:53 roberto Exp $
33 ** String table (keeps all strings handled by Lua)
44 ** See Copyright Notice in lua.h
55 */
@@ -14,7 +14,9 @@ · 8 unmodified lines
1414 #include "lua.h"
1515
1616
17−#define NUM_HASHS 61
17+#define NUM_HASHSTR 31
18+#define NUM_HASHUDATA 31
19+#define NUM_HASHS (NUM_HASHSTR+NUM_HASHUDATA)
1820
1921
2022 #define gcsizestring(l) (1+(l/64)) /* "weight" for a string with length 'l' */
@@ -25,8 +27,7 @@ static TaggedString EMPTY = {{NULL, 2}, 0L, 0, · 4 unmodified lines
2527 {{{LUA_T_NIL, {NULL}}, 0L}}, {0}};
2628
2729
28−void luaS_init (void)
29−{
30+void luaS_init (void) {
3031 int i;
3132 L->string_root = luaM_newvector(NUM_HASHS, stringtable);
3233 for (i=0; i<NUM_HASHS; i++) {
@@ -37,16 +38,14 @@ void luaS_init (void) · 4 unmodified lines
3738 }
3839
3940
40−static unsigned long hash_s (char *s, long l)
41−{
42− unsigned long h = 0;
41+static unsigned long hash_s (char *s, long l) {
42+ unsigned long h = 0; /* seed */
4343 while (l--)
44− h = ((h<<5)-h)^(unsigned char)*(s++);
44+ h = h ^ ((h<<5)+(h>>2)+(unsigned char)*(s++));
4545 return h;
4646 }
4747
48−static int newsize (stringtable *tb)
49−{
48+static int newsize (stringtable *tb) {
5049 int size = tb->size;
5150 int realuse = 0;
5251 int i;
@@ -54,16 +53,11 @@ static int newsize (stringtable *tb) · 1 unmodified line
5453 for (i=0; i<size; i++)
5554 if (tb->hash[i] != NULL && tb->hash[i] != &EMPTY)
5655 realuse++;
57− if (2*(realuse+1) <= size) /* +1 is the new element */
58− return size; /* don't need to grow, just rehash to clear EMPTYs */
59− else
60− return luaO_redimension(size);
56+ return luaO_redimension((realuse+1)*2); /* +1 is the new element */
6157 }
6258
6359
64−static void grow (stringtable *tb)
65−{
66−
60+static void grow (stringtable *tb) {
6761 int ns = newsize(tb);
6862 TaggedString **newhash = luaM_newvector(ns, TaggedString *);
6963 int i;
@@ -73,10 +67,13 @@ static void grow (stringtable *tb) · 3 unmodified lines
7367 tb->nuse = 0;
7468 for (i=0; i<tb->size; i++) {
7569 if (tb->hash[i] != NULL && tb->hash[i] != &EMPTY) {
76− int h = tb->hash[i]->hash%ns;
77− while (newhash[h])
78− h = (h+1)%ns;
79− newhash[h] = tb->hash[i];
70+ unsigned long h = tb->hash[i]->hash;
71+ int h1 = h%ns;
72+ while (newhash[h1]) {
73+ h1 += (h&(ns-2)) + 1; /* double hashing */
74+ if (h1 >= ns) h1 -= ns;
75+ }
76+ newhash[h1] = tb->hash[i];
8077 tb->nuse++;
8178 }
8279 }
@@ -86,8 +83,7 @@ static void grow (stringtable *tb) · 3 unmodified lines
8683 }
8784
8885
89−static TaggedString *newone_s (char *str, long l, unsigned long h)
90−{
86+static TaggedString *newone_s (char *str, long l, unsigned long h) {
9187 TaggedString *ts = (TaggedString *)luaM_malloc(sizeof(TaggedString)+l);
9288 memcpy(ts->str, str, l);
9389 ts->str[l] = 0; /* ending 0 */
@@ -101,8 +97,7 @@ static TaggedString *newone_s (char *str, long l, unsigned long h) · 7 unmodified lines
10197 return ts;
10298 }
10399
104−static TaggedString *newone_u (char *buff, int tag, unsigned long h)
105−{
100+static TaggedString *newone_u (char *buff, int tag, unsigned long h) {
106101 TaggedString *ts = luaM_new(TaggedString);
107102 ts->u.d.v = buff;
108103 ts->u.d.tag = (tag == LUA_ANYTAG) ? 0 : tag;
@@ -114,82 +109,79 @@ static TaggedString *newone_u (char *buff, int tag, unsigned long h) · 5 unmodified lines
114109 return ts;
115110 }
116111
117−static TaggedString *insert_s (char *str, long l, stringtable *tb)
118−{
112+static TaggedString *insert_s (char *str, long l, stringtable *tb) {
119113 TaggedString *ts;
120114 unsigned long h = hash_s(str, l);
121115 int size = tb->size;
122− int i;
123116 int j = -1;
117+ int h1;
124118 if ((long)tb->nuse*3 >= (long)size*2) {
125119 grow(tb);
126120 size = tb->size;
127121 }
128− for (i = h%size; (ts = tb->hash[i]) != NULL; ) {
122+ h1 = h%size;
123+ while ((ts = tb->hash[h1]) != NULL) {
129124 if (ts == &EMPTY)
130− j = i;
131− else if (ts->constindex >= 0 &&
132− ts->u.s.len == l &&
133− (memcmp(str, ts->str, l) == 0))
125+ j = h1;
126+ else if (ts->u.s.len == l && (memcmp(str, ts->str, l) == 0))
134127 return ts;
135− if (++i == size) i=0;
128+ h1 += (h&(size-2)) + 1; /* double hashing */
129+ if (h1 >= size) h1 -= size;
136130 }
137131 /* not found */
138132 if (j != -1) /* is there an EMPTY space? */
139− i = j;
133+ h1 = j;
140134 else
141135 tb->nuse++;
142− ts = tb->hash[i] = newone_s(str, l, h);
136+ ts = tb->hash[h1] = newone_s(str, l, h);
143137 return ts;
144138 }
145139
146−static TaggedString *insert_u (void *buff, int tag, stringtable *tb)
147−{
140+
141+static TaggedString *insert_u (void *buff, int tag, stringtable *tb) {
148142 TaggedString *ts;
149143 unsigned long h = (unsigned long)buff;
150144 int size = tb->size;
151− int i;
152145 int j = -1;
146+ int h1;
153147 if ((long)tb->nuse*3 >= (long)size*2) {
154148 grow(tb);
155149 size = tb->size;
156150 }
157− for (i = h%size; (ts = tb->hash[i]) != NULL; ) {
151+ h1 = h%size;
152+ while ((ts = tb->hash[h1]) != NULL) {
158153 if (ts == &EMPTY)
159− j = i;
160− else if (ts->constindex < 0 && /* is a udata? */
161− (tag == ts->u.d.tag || tag == LUA_ANYTAG) &&
162− buff == ts->u.d.v)
154+ j = h1;
155+ else if ((tag == ts->u.d.tag || tag == LUA_ANYTAG) && buff == ts->u.d.v)
163156 return ts;
164− if (++i == size) i=0;
157+ h1 += (h&(size-2)) + 1; /* double hashing */
158+ if (h1 >= size) h1 -= size;
165159 }
166160 /* not found */
167161 if (j != -1) /* is there an EMPTY space? */
168− i = j;
162+ h1 = j;
169163 else
170164 tb->nuse++;
171− ts = tb->hash[i] = newone_u(buff, tag, h);
165+ ts = tb->hash[h1] = newone_u(buff, tag, h);
172166 return ts;
173167 }
174168
175−TaggedString *luaS_createudata (void *udata, int tag)
176−{
177− return insert_u(udata, tag, &L->string_root[(unsigned)udata%NUM_HASHS]);
169+
170+TaggedString *luaS_createudata (void *udata, int tag) {
171+ int t = ((unsigned)udata%NUM_HASHUDATA)+NUM_HASHSTR;
172+ return insert_u(udata, tag, &L->string_root[t]);
178173 }
179174
180−TaggedString *luaS_newlstr (char *str, long l)
181−{
182− int i = (l==0)?0:(unsigned char)str[0];
183− return insert_s(str, l, &L->string_root[i%NUM_HASHS]);
175+TaggedString *luaS_newlstr (char *str, long l) {
176+ int t = (l==0) ? 0 : ((int)((unsigned char)str[0]*l))%NUM_HASHSTR;
177+ return insert_s(str, l, &L->string_root[t]);
184178 }
185179
186−TaggedString *luaS_new (char *str)
187−{
180+TaggedString *luaS_new (char *str) {
188181 return luaS_newlstr(str, strlen(str));
189182 }
190183
191−TaggedString *luaS_newfixedstring (char *str)
192−{
184+TaggedString *luaS_newfixedstring (char *str) {
193185 TaggedString *ts = luaS_new(str);
194186 if (ts->head.marked == 0)
195187 ts->head.marked = 2; /* avoid GC */
@@ -197,8 +189,7 @@ TaggedString *luaS_newfixedstring (char *str) · 1 unmodified line
197189 }
198190
199191
200−void luaS_free (TaggedString *l)
201−{
192+void luaS_free (TaggedString *l) {
202193 while (l) {
203194 TaggedString *next = (TaggedString *)l->head.next;
204195 L->nblocks -= (l->constindex == -1) ? 1 : gcsizestring(l->u.s.len);
@@ -212,8 +203,7 @@ void luaS_free (TaggedString *l) · 7 unmodified lines
212203 ** Garbage collection functions.
213204 */
214205
215−static void remove_from_list (GCnode *l)
216−{
206+static void remove_from_list (GCnode *l) {
217207 while (l) {
218208 GCnode *next = l->next;
219209 while (next && !next->marked)
@@ -223,8 +213,7 @@ static void remove_from_list (GCnode *l) · 3 unmodified lines
223213 }
224214
225215
226−TaggedString *luaS_collector (void)
227−{
216+TaggedString *luaS_collector (void) {
228217 TaggedString *frees = NULL;
229218 int i;
230219 remove_from_list(&(L->rootglobal));
@@ -247,18 +236,18 @@ TaggedString *luaS_collector (void) · 16 unmodified lines
247236 }
248237
249238
250−TaggedString *luaS_collectudata (void)
251−{
239+TaggedString *luaS_collectudata (void) {
252240 TaggedString *frees = NULL;
253241 int i;
254242 L->rootglobal.next = NULL; /* empty list of globals */
255− for (i=0; i<NUM_HASHS; i++) {
243+ for (i=NUM_HASHSTR; i<NUM_HASHS; i++) {
256244 stringtable *tb = &L->string_root[i];
257245 int j;
258246 for (j=0; j<tb->size; j++) {
259247 TaggedString *t = tb->hash[j];
260− if (t == NULL || t == &EMPTY || t->constindex != -1)
261− continue; /* get only user data */
248+ if (t == NULL || t == &EMPTY)
249+ continue;
250+ LUA_ASSERT(t->constindex == -1, "must be userdata");
262251 t->head.next = (GCnode *)frees;
263252 frees = t;
264253 tb->hash[j] = &EMPTY;
@@ -268,8 +257,7 @@ TaggedString *luaS_collectudata (void) · 3 unmodified lines
268257 }
269258
270259
271−void luaS_freeall (void)
272−{
260+void luaS_freeall (void) {
273261 int i;
274262 for (i=0; i<NUM_HASHS; i++) {
275263 stringtable *tb = &L->string_root[i];
@@ -285,8 +273,7 @@ void luaS_freeall (void) · 9 unmodified lines
285273 }
286274
287275
288−void luaS_rawsetglobal (TaggedString *ts, TObject *newval)
289−{
276+void luaS_rawsetglobal (TaggedString *ts, TObject *newval) {
290277 ts->u.s.globalval = *newval;
291278 if (ts->head.next == (GCnode *)ts) { /* is not in list? */
292279 ts->head.next = L->rootglobal.next;
@@ -295,8 +282,7 @@ void luaS_rawsetglobal (TaggedString *ts, TObject *newval) · 2 unmodified lines
295282 }
296283
297284
298−char *luaS_travsymbol (int (*fn)(TObject *))
299−{
285+char *luaS_travsymbol (int (*fn)(TObject *)) {
300286 TaggedString *g;
301287 for (g=(TaggedString *)L->rootglobal.next; g; g=(TaggedString *)g->head.next)
302288 if (fn(&g->u.s.globalval))
@@ -305,8 +291,7 @@ char *luaS_travsymbol (int (*fn)(TObject *)) · 2 unmodified lines
305291 }
306292
307293
308−int luaS_globaldefined (char *name)
309−{
294+int luaS_globaldefined (char *name) {
310295 TaggedString *ts = luaS_new(name);
311296 return ts->u.s.globalval.ttype != LUA_T_NIL;
312297 }
src/ltable.c+65−104
@@ -1,5 +1,5 @@
11 /*
2−** $Id: ltable.c,v 1.12 1998/01/28 16:50:33 roberto Exp $
2+** $Id: ltable.c,v 1.22 1999/05/21 19:41:49 roberto Exp $
33 ** Lua tables (hash)
44 ** See Copyright Notice in lua.h
55 */
@@ -20,14 +20,11 @@ · 14 unmodified lines
2020 #define nodevector(t) ((t)->node)
2121
2222
23−#define REHASH_LIMIT 0.70 /* avoid more than this % full */
24−
2523 #define TagDefault LUA_T_ARRAY;
2624
2725
2826
29−static long int hashindex (TObject *ref)
30−{
27+static long int hashindex (TObject *ref) {
3128 long int h;
3229 switch (ttype(ref)) {
3330 case LUA_T_NUMBER:
@@ -56,61 +53,45 @@ static long int hashindex (TObject *ref) · 22 unmodified lines
5653 }
5754
5855
59−static int present (Hash *t, TObject *key)
60−{
56+Node *luaH_present (Hash *t, TObject *key) {
6157 int tsize = nhash(t);
6258 long int h = hashindex(key);
6359 int h1 = h%tsize;
64− TObject *rf = ref(node(t, h1));
65− if (ttype(rf) != LUA_T_NIL && !luaO_equalObj(key, rf)) {
66− int h2 = h%(tsize-2) + 1;
67− do {
68− h1 += h2;
69− if (h1 >= tsize) h1 -= tsize;
70− rf = ref(node(t, h1));
71− } while (ttype(rf) != LUA_T_NIL && !luaO_equalObj(key, rf));
60+ Node *n = node(t, h1);
61+ /* keep looking until an entry with "ref" equal to key or nil */
62+ while ((ttype(ref(n)) == ttype(key)) ? !luaO_equalval(key, ref(n))
63+ : ttype(ref(n)) != LUA_T_NIL) {
64+ h1 += (h&(tsize-2)) + 1; /* double hashing */
65+ if (h1 >= tsize) h1 -= tsize;
66+ n = node(t, h1);
7267 }
73− return h1;
68+ return n;
7469 }
7570
7671
77−/*
78−** Alloc a vector node
79−*/
80−static Node *hashnodecreate (int nhash)
81−{
82− Node *v = luaM_newvector(nhash, Node);
83− int i;
84− for (i=0; i<nhash; i++)
85− ttype(ref(&v[i])) = LUA_T_NIL;
86− return v;
87−}
88−
89−/*
90−** Delete a hash
91−*/
92−static void hashdelete (Hash *t)
93−{
94− luaM_free(nodevector(t));
95− luaM_free(t);
96−}
97−
98−
99−void luaH_free (Hash *frees)
100−{
72+void luaH_free (Hash *frees) {
10173 while (frees) {
10274 Hash *next = (Hash *)frees->head.next;
10375 L->nblocks -= gcsize(frees->nhash);
104− hashdelete(frees);
76+ luaM_free(nodevector(frees));
77+ luaM_free(frees);
10578 frees = next;
10679 }
10780 }
10881
10982
110−Hash *luaH_new (int nhash)
111−{
83+static Node *hashnodecreate (int nhash) {
84+ Node *v = luaM_newvector(nhash, Node);
85+ int i;
86+ for (i=0; i<nhash; i++)
87+ ttype(ref(&v[i])) = ttype(val(&v[i])) = LUA_T_NIL;
88+ return v;
89+}
90+
91+
92+Hash *luaH_new (int nhash) {
11293 Hash *t = luaM_new(Hash);
113− nhash = luaO_redimension((int)((float)nhash/REHASH_LIMIT));
94+ nhash = luaO_redimension(nhash*3/2);
11495 nodevector(t) = hashnodecreate(nhash);
11596 nhash(t) = nhash;
11697 nuse(t) = 0;
@@ -121,96 +102,76 @@ Hash *luaH_new (int nhash) · 4 unmodified lines
121102 }
122103
123104
124−static int newsize (Hash *t)
125−{
105+static int newsize (Hash *t) {
126106 Node *v = t->node;
127107 int size = nhash(t);
128108 int realuse = 0;
129109 int i;
130110 for (i=0; i<size; i++) {
131− if (ttype(ref(v+i)) != LUA_T_NIL && ttype(val(v+i)) != LUA_T_NIL)
111+ if (ttype(val(v+i)) != LUA_T_NIL)
132112 realuse++;
133113 }
134− if (2*(realuse+1) <= size) /* +1 is the new element */
135− return size; /* don't need to grow, just rehash */
136− else
137− return luaO_redimension(size);
114+ return luaO_redimension((realuse+1)*2); /* +1 is the new element */
138115 }
139116
140−static void rehash (Hash *t)
141−{
117+
118+static void rehash (Hash *t) {
142119 int nold = nhash(t);
143120 Node *vold = nodevector(t);
144121 int nnew = newsize(t);
145122 int i;
146123 nodevector(t) = hashnodecreate(nnew);
147124 nhash(t) = nnew;
125+ nuse(t) = 0;
148126 for (i=0; i<nold; i++) {
149127 Node *n = vold+i;
150− if (ttype(ref(n)) != LUA_T_NIL && ttype(val(n)) != LUA_T_NIL)
151− *node(t, present(t, ref(n))) = *n; /* copy old node to luaM_new hash */
128+ if (ttype(val(n)) != LUA_T_NIL) {
129+ *luaH_present(t, ref(n)) = *n; /* copy old node to new hash */
130+ nuse(t)++;
131+ }
152132 }
153133 L->nblocks += gcsize(nnew)-gcsize(nold);
154134 luaM_free(vold);
155135 }
156136
157−/*
158−** If the hash node is present, return its pointer, otherwise return
159−** null.
160−*/
161−TObject *luaH_get (Hash *t, TObject *ref)
162−{
163− int h = present(t, ref);
164− if (ttype(ref(node(t, h))) != LUA_T_NIL) return val(node(t, h));
165− else return NULL;
166−}
167137
168−
169−/*
170−** If the hash node is present, return its pointer, otherwise create a luaM_new
171−** node for the given reference and also return its pointer.
172−*/
173−TObject *luaH_set (Hash *t, TObject *ref)
174−{
175− Node *n = node(t, present(t, ref));
176− if (ttype(ref(n)) == LUA_T_NIL) {
177− nuse(t)++;
178− if ((float)nuse(t) > (float)nhash(t)*REHASH_LIMIT) {
138+void luaH_set (Hash *t, TObject *ref, TObject *val) {
139+ Node *n = luaH_present(t, ref);
140+ if (ttype(ref(n)) != LUA_T_NIL)
141+ *val(n) = *val;
142+ else {
143+ TObject buff;
144+ buff = *val; /* rehash may invalidate this address */
145+ if ((long)nuse(t)*3L > (long)nhash(t)*2L) {
179146 rehash(t);
180− n = node(t, present(t, ref));
147+ n = luaH_present(t, ref);
181148 }
149+ nuse(t)++;
182150 *ref(n) = *ref;
183− ttype(val(n)) = LUA_T_NIL;
151+ *val(n) = buff;
184152 }
185− return (val(n));
186153 }
187154
188155
189−static Node *hashnext (Hash *t, int i)
190−{
191− Node *n;
192− int tsize = nhash(t);
193− if (i >= tsize)
194− return NULL;
195− n = node(t, i);
196− while (ttype(ref(n)) == LUA_T_NIL || ttype(val(n)) == LUA_T_NIL) {
197− if (++i >= tsize)
198− return NULL;
199− n = node(t, i);
200− }
201− return node(t, i);
156+int luaH_pos (Hash *t, TObject *r) {
157+ Node *n = luaH_present(t, r);
158+ luaL_arg_check(ttype(val(n)) != LUA_T_NIL, 2, "key not found");
159+ return n-(t->node);
202160 }
203161
204−Node *luaH_next (TObject *o, TObject *r)
205−{
206− Hash *t = avalue(o);
207− if (ttype(r) == LUA_T_NIL)
208− return hashnext(t, 0);
209− else {
210− int i = present(t, r);
211− Node *n = node(t, i);
212− luaL_arg_check(ttype(ref(n))!=LUA_T_NIL && ttype(val(n))!=LUA_T_NIL,
213− 2, "key not found");
214− return hashnext(t, i+1);
215− }
162+
163+void luaH_setint (Hash *t, int ref, TObject *val) {
164+ TObject index;
165+ ttype(&index) = LUA_T_NUMBER;
166+ nvalue(&index) = ref;
167+ luaH_set(t, &index, val);
216168 }
169+
170+
171+TObject *luaH_getint (Hash *t, int ref) {
172+ TObject index;
173+ ttype(&index) = LUA_T_NUMBER;
174+ nvalue(&index) = ref;
175+ return luaH_get(t, &index);
176+}
177+
src/ltable.h+10−4
@@ -1,5 +1,5 @@
11 /*
2−** $Id: ltable.h,v 1.5 1997/11/26 18:53:45 roberto Exp $
2+** $Id: ltable.h,v 1.11 1999/02/23 14:57:28 roberto Exp $
33 ** Lua tables (hash)
44 ** See Copyright Notice in lua.h
55 */
@@ -15,10 +15,16 @@ · 9 unmodified lines
1515 #define val(n) (&(n)->val)
1616 #define nhash(t) ((t)->nhash)
1717
18+#define luaH_get(t,ref) (val(luaH_present((t), (ref))))
19+#define luaH_move(t,from,to) (luaH_setint(t, to, luaH_getint(t, from)))
20+
1821 Hash *luaH_new (int nhash);
1922 void luaH_free (Hash *frees);
20−TObject *luaH_get (Hash *t, TObject *ref);
21−TObject *luaH_set (Hash *t, TObject *ref);
22−Node *luaH_next (TObject *o, TObject *r);
23+Node *luaH_present (Hash *t, TObject *key);
24+void luaH_set (Hash *t, TObject *ref, TObject *val);
25+int luaH_pos (Hash *t, TObject *r);
26+void luaH_setint (Hash *t, int ref, TObject *val);
27+TObject *luaH_getint (Hash *t, int ref);
28+
2329
2430 #endif
src/ltm.c+38−53
@@ -1,5 +1,5 @@
11 /*
2−** $Id: ltm.c,v 1.16 1998/06/18 16:57:03 roberto Exp $
2+** $Id: ltm.c,v 1.25 1999/05/21 19:41:49 roberto Exp $
33 ** Tag methods
44 ** See Copyright Notice in lua.h
55 */
@@ -22,8 +22,7 @@ char *luaT_eventname[] = { /* ORDER IM */ · 16 unmodified lines
2222 };
2323
2424
25−static int luaI_checkevent (char *name, char *list[])
26−{
25+static int luaI_checkevent (char *name, char *list[]) {
2726 int e = luaL_findstring(name, list);
2827 if (e < 0)
2928 luaL_verror("`%.50s' is not a valid event name", name);
@@ -35,7 +34,7 @@ static int luaI_checkevent (char *name, char *list[]) · 5 unmodified lines
3534 /* events in LUA_T_NIL are all allowed, since this is used as a
3635 * 'placeholder' for "default" fallbacks
3736 */
38−static char validevents[NUM_TAGS][IM_N] = { /* ORDER LUA_T, ORDER IM */
37+static char luaT_validevents[NUM_TAGS][IM_N] = { /* ORDER LUA_T, ORDER IM */
3938 {1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1}, /* LUA_T_USERDATA */
4039 {1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1}, /* LUA_T_NUMBER */
4140 {1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, /* LUA_T_STRING */
@@ -45,71 +44,59 @@ static char validevents[NUM_TAGS][IM_N] = { /* ORDER LUA_T, ORDER IM */ · 3 unmodified lines
4544 {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1} /* LUA_T_NIL */
4645 };
4746
48−
49−static int validevent (int t, int e)
50−{ /* ORDER LUA_T */
51− return (t < LUA_T_NIL) ? 1 : validevents[-t][e];
47+static int luaT_validevent (int t, int e) { /* ORDER LUA_T */
48+ return (t < LUA_T_NIL) ? 1 : luaT_validevents[-t][e];
5249 }
5350
5451
55−static void init_entry (int tag)
56−{
52+static void init_entry (int tag) {
5753 int i;
5854 for (i=0; i<IM_N; i++)
5955 ttype(luaT_getim(tag, i)) = LUA_T_NIL;
6056 }
6157
6258
63−void luaT_init (void)
64−{
59+void luaT_init (void) {
6560 int t;
66− L->IMtable_size = NUM_TAGS*2;
6761 L->last_tag = -(NUM_TAGS-1);
68− L->IMtable = luaM_newvector(L->IMtable_size, struct IM);
62+ luaM_growvector(L->IMtable, 0, NUM_TAGS, struct IM, arrEM, MAX_INT);
6963 for (t=L->last_tag; t<=0; t++)
7064 init_entry(t);
7165 }
7266
7367
74−int lua_newtag (void)
75−{
68+int lua_newtag (void) {
7669 --L->last_tag;
77− if ((-L->last_tag) >= L->IMtable_size)
78− L->IMtable_size = luaM_growvector(&L->IMtable, L->IMtable_size,
79− struct IM, memEM, MAX_INT);
70+ luaM_growvector(L->IMtable, -(L->last_tag), 1, struct IM, arrEM, MAX_INT);
8071 init_entry(L->last_tag);
8172 return L->last_tag;
8273 }
8374
8475
85−static void checktag (int tag)
86−{
76+static void checktag (int tag) {
8777 if (!(L->last_tag <= tag && tag <= 0))
8878 luaL_verror("%d is not a valid tag", tag);
8979 }
9080
91−void luaT_realtag (int tag)
92−{
81+void luaT_realtag (int tag) {
9382 if (!(L->last_tag <= tag && tag < LUA_T_NIL))
94− luaL_verror("tag %d is not result of `newtag'", tag);
83+ luaL_verror("tag %d was not created by `newtag'", tag);
9584 }
9685
9786
98−int lua_copytagmethods (int tagto, int tagfrom)
99−{
87+int lua_copytagmethods (int tagto, int tagfrom) {
10088 int e;
10189 checktag(tagto);
10290 checktag(tagfrom);
10391 for (e=0; e<IM_N; e++) {
104− if (validevent(tagto, e))
92+ if (luaT_validevent(tagto, e))
10593 *luaT_getim(tagto, e) = *luaT_getim(tagfrom, e);
10694 }
10795 return tagto;
10896 }
10997
11098
111−int luaT_efectivetag (TObject *o)
112−{
99+int luaT_effectivetag (TObject *o) {
113100 int t;
114101 switch (t = ttype(o)) {
115102 case LUA_T_ARRAY:
@@ -131,36 +118,34 @@ int luaT_efectivetag (TObject *o) · 15 unmodified lines
131118 }
132119
133120
134−TObject *luaT_gettagmethod (int t, char *event)
135−{
121+TObject *luaT_gettagmethod (int t, char *event) {
136122 int e = luaI_checkevent(event, luaT_eventname);
137123 checktag(t);
138− if (validevent(t, e))
124+ if (luaT_validevent(t, e))
139125 return luaT_getim(t,e);
140126 else
141127 return &luaO_nilobject;
142128 }
143129
144130
145−void luaT_settagmethod (int t, char *event, TObject *func)
146−{
147− TObject temp = *func;
131+void luaT_settagmethod (int t, char *event, TObject *func) {
132+ TObject temp;
148133 int e = luaI_checkevent(event, luaT_eventname);
149134 checktag(t);
150− if (!validevent(t, e))
151− luaL_verror("settagmethod: cannot change tag method `%.20s' for tag %d",
152− luaT_eventname[e], t);
135+ if (!luaT_validevent(t, e))
136+ luaL_verror("cannot change tag method `%.20s' for type `%.20s'%.20s",
137+ luaT_eventname[e], luaO_typenames[-t],
138+ (t == LUA_T_ARRAY || t == LUA_T_USERDATA) ? " with default tag"
139+ : "");
140+ temp = *func;
153141 *func = *luaT_getim(t,e);
154142 *luaT_getim(t, e) = temp;
155143 }
156144
157145
158−char *luaT_travtagmethods (int (*fn)(TObject *))
159−{
146+char *luaT_travtagmethods (int (*fn)(TObject *)) { /* ORDER IM */
160147 int e;
161− if (fn(&L->errorim))
162− return "error";
163− for (e=IM_GETTABLE; e<=IM_FUNCTION; e++) { /* ORDER IM */
148+ for (e=IM_GETTABLE; e<=IM_FUNCTION; e++) {
164149 int t;
165150 for (t=0; t>=L->last_tag; t--)
166151 if (fn(luaT_getim(t,e)))
@@ -177,6 +162,7 @@ char *luaT_travtagmethods (int (*fn)(TObject *)) · 10 unmodified lines
177162 #ifdef LUA_COMPAT2_5
178163
179164 #include "lapi.h"
165+#include "lstring.h"
180166
181167 static void errorFB (void)
182168 {
@@ -191,23 +177,20 @@ static void errorFB (void) · 8 unmodified lines
191177 static void nilFB (void) { }
192178
193179
194−static void typeFB (void)
195−{
180+static void typeFB (void) {
196181 lua_error("unexpected type");
197182 }
198183
199184
200−static void fillvalids (IMS e, TObject *func)
201−{
185+static void fillvalids (IMS e, TObject *func) {
202186 int t;
203187 for (t=LUA_T_NIL; t<=LUA_T_USERDATA; t++)
204− if (validevent(t, e))
188+ if (luaT_validevent(t, e))
205189 *luaT_getim(t, e) = *func;
206190 }
207191
208192
209−void luaT_setfallback (void)
210−{
193+void luaT_setfallback (void) {
211194 static char *oldnames [] = {"error", "getglobal", "arith", "order", NULL};
212195 TObject oldfunc;
213196 lua_CFunction replace;
@@ -215,11 +198,13 @@ void luaT_setfallback (void) · 1 unmodified line
215198 lua_Object func = lua_getparam(2);
216199 luaL_arg_check(lua_isfunction(func), 2, "function expected");
217200 switch (luaL_findstring(name, oldnames)) {
218− case 0: /* old error fallback */
219− oldfunc = L->errorim;
220− L->errorim = *luaA_Address(func);
201+ case 0: { /* old error fallback */
202+ TObject *em = &(luaS_new("_ERRORMESSAGE")->u.s.globalval);
203+ oldfunc = *em;
204+ *em = *luaA_Address(func);
221205 replace = errorFB;
222206 break;
207+ }
223208 case 1: /* old getglobal fallback */
224209 oldfunc = *luaT_getim(LUA_T_NIL, IM_GETGLOBAL);
225210 *luaT_getim(LUA_T_NIL, IM_GETGLOBAL) = *luaA_Address(func);
src/ltm.h+3−3
@@ -1,5 +1,5 @@
11 /*
2−** $Id: ltm.h,v 1.4 1997/11/26 18:53:45 roberto Exp $
2+** $Id: ltm.h,v 1.5 1999/01/15 13:11:57 roberto Exp $
33 ** Tag methods
44 ** See Copyright Notice in lua.h
55 */
@@ -45,14 +45,14 @@ struct IM { · 39 unmodified lines
4545
4646
4747 #define luaT_getim(tag,event) (&L->IMtable[-(tag)].int_method[event])
48−#define luaT_getimbyObj(o,e) (luaT_getim(luaT_efectivetag(o),(e)))
48+#define luaT_getimbyObj(o,e) (luaT_getim(luaT_effectivetag(o),(e)))
4949
5050 extern char *luaT_eventname[];
5151
5252
5353 void luaT_init (void);
5454 void luaT_realtag (int tag);
55−int luaT_efectivetag (TObject *o);
55+int luaT_effectivetag (TObject *o);
5656 void luaT_settagmethod (int t, char *event, TObject *func);
5757 TObject *luaT_gettagmethod (int t, char *event);
5858 char *luaT_travtagmethods (int (*fn)(TObject *));
src/lua/Makefile+2−2
@@ -17,10 +17,10 @@ $T: $(OBJS) $(LIB)/liblua.a $(LIB)/liblualib.a · 16 unmodified lines
1717 $(CC) -o $@ $(OBJS) -L$(LIB) -llua -llualib -lm
1818
1919 $(LIB)/liblua.a:
20− cd ..; make
20+ cd ..; $(MAKE)
2121
2222 $(LIB)/liblualib.a:
23− cd ../lib; make
23+ cd ../lib; $(MAKE)
2424
2525 clean:
2626 rm -f $(OBJS) $T
src/lua/README+21−3
@@ -1,5 +1,6 @@
11 This client is a sample lua interpreter.
2−It can be used as a batch interpreter and interactively.
2+It can be used as a batch interpreter and also interactively.
3+
34 Here are the options it understands:
45
56 -v print version information
@@ -11,10 +12,27 @@ Here are the options it understands: · 5 unmodified lines
1112 a=b sets global `a' with string `b' (no need to quote b)
1213 name dofile `name'
1314
14−If no options are given, then it reads and executes lines from stdin.
15−In this case, each line must contain a complete statement.
15+If no options are given, then it reads lines from stdin and executes them
16+as they are read. So, each line must contain a complete statement.
1617 To span a statement across several lines, end each line with a backslash '\'.
18+
1719 To change the prompt, set the global variable _PROMPT to whatever you want.
20+You can do after calling the interpreter or on the command line with
21+ _PROMPT="lua: "
22+for example.
23+
24+You must be careful when using quotes on the command line because they are
25+usually handled by the shell.
1826
1927 This interpreter is good for using Lua as a standalone language.
2028 For a minimal interpreter, see etc/min.c.
29+
30+If your application simply exports new functions to Lua (which is common),
31+then you can use this interpreter unmodified: just define a function
32+
33+ void lua_userinit (void)
34+
35+in your code. In this function, you should do whatever initializations are
36+need, typically exporting your functions to Lua.
37+If you use this scheme, you must explicily open any standard libraries you need.
38+See ../lib/linit.c
src/lua/lua.c+29−35
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lua.c,v 1.14 1998/02/11 20:56:05 roberto Exp $
2+** $Id: lua.c,v 1.21 1999/07/02 18:22:38 roberto Exp $
33 ** Lua stand-alone interpreter
44 ** See Copyright Notice in lua.h
55 */
@@ -15,12 +15,6 @@ · 9 unmodified lines
1515 #include "lualib.h"
1616
1717
18−#ifndef OLD_ANSI
19−#include <locale.h>
20−#else
21−#define setlocale(a,b) 0
22−#endif
23−
2418 #ifdef _POSIX_SOURCE
2519 #include <unistd.h>
2620 #else
@@ -32,27 +26,33 @@ typedef void (*handler)(int); /* type for signal actions */ · 5 unmodified lines
3226
3327 static void laction (int i);
3428
35−static handler lreset (void)
36−{
37− lua_linehook = NULL;
38− lua_callhook = NULL;
29+
30+static lua_LHFunction old_linehook = NULL;
31+static lua_CHFunction old_callhook = NULL;
32+
33+
34+static handler lreset (void) {
3935 return signal(SIGINT, laction);
4036 }
4137
42−static void lstop (void)
43−{
38+
39+static void lstop (void) {
40+ lua_setlinehook(old_linehook);
41+ lua_setcallhook(old_callhook);
4442 lreset();
4543 lua_error("interrupted!");
4644 }
4745
48−static void laction (int i)
49−{
50− lua_linehook = (lua_LHFunction)lstop;
51− lua_callhook = (lua_CHFunction)lstop;
46+
47+static void laction (int i) {
48+ signal(SIGINT, SIG_DFL); /* if another SIGINT happens before lstop,
49+ terminate process (default action) */
50+ old_linehook = lua_setlinehook((lua_LHFunction)lstop);
51+ old_callhook = lua_setcallhook((lua_CHFunction)lstop);
5252 }
5353
54−static int ldo (int (*f)(char *), char *name)
55−{
54+
55+static int ldo (int (*f)(char *), char *name) {
5656 int res;
5757 handler h = lreset();
5858 res = f(name); /* dostring | dofile */
@@ -61,8 +61,7 @@ static int ldo (int (*f)(char *), char *name) · 2 unmodified lines
6161 }
6262
6363
64−static void print_message (void)
65−{
64+static void print_message (void) {
6665 fprintf(stderr,
6766 "Lua: command line options:\n"
6867 " -v print version information\n"
@@ -76,8 +75,7 @@ static void print_message (void) · 7 unmodified lines
7675 }
7776
7877
79−static void assign (char *arg)
80−{
78+static void assign (char *arg) {
8179 if (strlen(arg) >= 500)
8280 fprintf(stderr, "lua: shell argument too long");
8381 else {
@@ -90,13 +88,11 @@ static void assign (char *arg) · 6 unmodified lines
9088 }
9189 }
9290
93−#define BUF_SIZE 512
9491
95−static void manual_input (int prompt)
96−{
92+static void manual_input (int prompt) {
9793 int cont = 1;
9894 while (cont) {
99− char buffer[BUF_SIZE];
95+ char buffer[BUFSIZ];
10096 int i = 0;
10197 lua_beginblock();
10298 if (prompt)
@@ -112,13 +108,13 @@ static void manual_input (int prompt) · 9 unmodified lines
112108 buffer[i-1] = '\n';
113109 else break;
114110 }
115− else if (i >= BUF_SIZE-1) {
111+ else if (i >= BUFSIZ-1) {
116112 fprintf(stderr, "lua: argument line too long\n");
117113 break;
118114 }
119− else buffer[i++] = c;
115+ else buffer[i++] = (char)c;
120116 }
121− buffer[i] = 0;
117+ buffer[i] = '\0';
122118 ldo(lua_dostring, buffer);
123119 lua_endblock();
124120 }
@@ -129,11 +125,9 @@ static void manual_input (int prompt) · 4 unmodified lines
129125 int main (int argc, char *argv[])
130126 {
131127 int i;
132− setlocale(LC_ALL, "");
133− lua_iolibopen();
134− lua_strlibopen();
135− lua_mathlibopen();
128+ lua_open();
136129 lua_pushstring("> "); lua_setglobal("_PROMPT");
130+ lua_userinit();
137131 if (argc < 2) { /* no arguments? */
138132 if (isatty(0)) {
139133 printf("%s %s\n", LUA_VERSION, LUA_COPYRIGHT);
@@ -155,7 +149,7 @@ int main (int argc, char *argv[]) · 15 unmodified lines
155149 manual_input(0);
156150 break;
157151 case 'd':
158− lua_debug = 1;
152+ lua_setdebug(1);
159153 break;
160154 case 'v':
161155 printf("%s %s\n(written by %s)\n\n",
src/luac/Makefile+3−3
@@ -5,8 +5,8 @@ LUA= ../.. · 4 unmodified lines
55 include $(LUA)/config
66
77 INCS= -I$(INC) $(EXTRA_INCS) -I..
8−OBJS= dump.o luac.o opcode.o opt.o print.o stubs.o
9−SRCS= dump.c luac.c opcode.c opt.c print.c stubs.c luac.h opcode.h
8+OBJS= dump.o luac.o opcode.o opt.o print.o stubs.o test.o
9+SRCS= dump.c luac.c opcode.c opt.c print.c stubs.c test.c luac.h opcode.h
1010
1111 T= $(BIN)/luac
1212
@@ -16,7 +16,7 @@ $T: $(OBJS) $(LIB)/liblua.a · 3 unmodified lines
1616 $(CC) -o $@ $(OBJS) -L$(LIB) -llua
1717
1818 $(LIB)/liblua.a:
19− cd ..; make
19+ cd ..; $(MAKE)
2020
2121 clean:
2222 rm -f $(OBJS) $T
src/luac/README+17−14
@@ -2,24 +2,27 @@ luac translates Lua programs into binary files that can be loaded and executed · 1 unmodified line
22 with lua_dofile in C or with dofile in Lua.
33 The main advantages of pre-compiling chunks are: faster loading,
44 protecting source code from user changes, off-line syntax error detection.
5−
65 luac can also be used to learn about the Lua virtual machine.
76
8−Here are the options it understands:
7+Here are the options that luac understands:
98
10− -c compile (default)
11− -u undump
12− -d generate debugging information
13− -D predefine symbol for conditional compilation
14− -l list (default for -u)
15− -o output file for -c (default is "luac.out")
16− -O optimize
17− -p parse only
18− -q quiet (default for -c)
19− -v show version information
20− -V verbose
21− - compile "stdin"
9+ -c compile (default)
10+ -d generate debugging information
11+ -D name predefine 'name' for conditional compilation
12+ -l list (default for -u)
13+ -n save numbers in native format (file may not be portable)
14+ -o file output file for -c (default is "luac.out")
15+ -O optimize
16+ -p parse only
17+ -q quiet (default for -c)
18+ -t test code integrity
19+ -u undump
20+ -U name undefine 'name' for conditional compilation
21+ -v show version information
22+ -V verbose
23+ - compile "stdin"
2224
2325 Finally, luac is an example of how to use the internals of Lua (politely).
2426 Also, luac does not need the runtime code and stubs.c makes sure it is not
2527 linked into luac. This file also shows how to avoid linking the parser.
28+
src/luac/dump.c+61−65
@@ -1,16 +1,20 @@
11 /*
2−** $Id: dump.c,v 1.11 1998/07/12 00:17:37 lhf Exp $
2+** $Id: dump.c,v 1.20 1999/07/02 19:34:26 lhf Exp $
33 ** save bytecodes to file
44 ** See Copyright Notice in lua.h
55 */
66
7+#include <errno.h>
78 #include <stdio.h>
89 #include <stdlib.h>
910 #include "luac.h"
1011
11−#define NotWord(x) ((unsigned short)x!=x)
12+#ifdef OLD_ANSI
13+#define strerror(e) "(no error message provided by operating system)"
14+#endif
15+
1216 #define DumpBlock(b,size,D) fwrite(b,size,1,D)
13−#define DumpNative(t,D) DumpBlock(&t,sizeof(t),D)
17+#define DumpInt DumpLong
1418
1519 static void DumpWord(int i, FILE* D)
1620 {
@@ -28,43 +32,24 @@ static void DumpLong(long i, FILE* D) · 11 unmodified lines
2832 DumpWord(lo,D);
2933 }
3034
31−#if ID_NUMBER==ID_REAL4
32−/* LUA_NUMBER */
33−/* assumes sizeof(long)==4 and sizeof(float)==4 (IEEE) */
34−static void DumpFloat(float f, FILE* D)
35+static void DumpNumber(real x, FILE* D, int native, TProtoFunc* tf)
3536 {
36− long l=*(long*)&f;
37− DumpLong(l,D);
38−}
39−#endif
40−
41−#if ID_NUMBER==ID_REAL8
42−/* LUA_NUMBER */
43−/* assumes sizeof(long)==4 and sizeof(double)==8 (IEEE) */
44−static void DumpDouble(double f, FILE* D)
45−{
46− long* l=(long*)&f;
47− int x=1;
48− if (*(char*)&x==1) /* little-endian */
49− {
50− DumpLong(l[1],D);
51− DumpLong(l[0],D);
52− }
53− else /* big-endian */
37+ if (native)
38+ DumpBlock(&x,sizeof(x),D);
39+ else
5440 {
55− DumpLong(l[0],D);
56− DumpLong(l[1],D);
41+ char b[256];
42+ int n;
43+ sprintf(b,NUMBER_FMT"%n",x,&n);
44+ luaU_str2d(b,tf->source->str); /* help lundump not to fail */
45+ fputc(n,D);
46+ DumpBlock(b,n,D);
5747 }
5848 }
59−#endif
6049
6150 static void DumpCode(TProtoFunc* tf, FILE* D)
6251 {
63− int size=CodeSize(tf);
64− if (NotWord(size))
65− fprintf(stderr,"luac: warning: "
66− "\"%s\":%d code too long for 16-bit machines (%d bytes)\n",
67− fileName(tf),tf->lineDefined,size);
52+ int size=luaU_codesize(tf);
6853 DumpLong(size,D);
6954 DumpBlock(tf->code,size,D);
7055 }
@@ -72,87 +57,98 @@ static void DumpCode(TProtoFunc* tf, FILE* D) · 1 unmodified line
7257 static void DumpString(char* s, int size, FILE* D)
7358 {
7459 if (s==NULL)
75− DumpWord(0,D);
60+ DumpLong(0,D);
7661 else
7762 {
78− if (NotWord(size))
79− luaL_verror("string too long (%d bytes): \"%.32s...\"",size,s);
80− DumpWord(size,D);
63+ DumpLong(size,D);
8164 DumpBlock(s,size,D);
8265 }
8366 }
8467
8568 static void DumpTString(TaggedString* s, FILE* D)
8669 {
87− if (s==NULL) DumpString(NULL,0,D); else DumpString(s->str,s->u.s.len+1,D);
70+ if (s==NULL)
71+ DumpString(NULL,0,D);
72+ else
73+ DumpString(s->str,s->u.s.len+1,D);
8874 }
8975
9076 static void DumpLocals(TProtoFunc* tf, FILE* D)
9177 {
92− int n;
93− LocVar* lv;
94− for (n=0,lv=tf->locvars; lv && lv->line>=0; lv++) ++n;
95− DumpWord(n,D);
96− for (lv=tf->locvars; lv && lv->line>=0; lv++)
78+ if (tf->locvars==NULL)
79+ DumpInt(0,D);
80+ else
9781 {
98− DumpWord(lv->line,D);
99− DumpTString(lv->varname,D);
82+ LocVar* v;
83+ int n=0;
84+ for (v=tf->locvars; v->line>=0; v++)
85+ ++n;
86+ DumpInt(n,D);
87+ for (v=tf->locvars; v->line>=0; v++)
88+ {
89+ DumpInt(v->line,D);
90+ DumpTString(v->varname,D);
91+ }
10092 }
10193 }
10294
103−static void DumpFunction(TProtoFunc* tf, FILE* D);
95+static void DumpFunction(TProtoFunc* tf, FILE* D, int native);
10496
105−static void DumpConstants(TProtoFunc* tf, FILE* D)
97+static void DumpConstants(TProtoFunc* tf, FILE* D, int native)
10698 {
10799 int i,n=tf->nconsts;
108− DumpWord(n,D);
100+ DumpInt(n,D);
109101 for (i=0; i<n; i++)
110102 {
111103 TObject* o=tf->consts+i;
112− fputc(-ttype(o),D);
104+ fputc(-ttype(o),D); /* ttype(o) is negative - ORDER LUA_T */
113105 switch (ttype(o))
114106 {
115107 case LUA_T_NUMBER:
116− DumpNumber(nvalue(o),D);
108+ DumpNumber(nvalue(o),D,native,tf);
117109 break;
118110 case LUA_T_STRING:
119111 DumpTString(tsvalue(o),D);
120112 break;
121113 case LUA_T_PROTO:
122− DumpFunction(tfvalue(o),D);
114+ DumpFunction(tfvalue(o),D,native);
123115 break;
124116 case LUA_T_NIL:
125117 break;
126118 default: /* cannot happen */
127− luaL_verror("cannot dump constant #%d: type=%d [%s]",
128− i,ttype(o),luaO_typename(o));
119+ luaU_badconstant("dump",i,o,tf);
129120 break;
130121 }
131122 }
132123 }
133124
134−static void DumpFunction(TProtoFunc* tf, FILE* D)
125+static void DumpFunction(TProtoFunc* tf, FILE* D, int native)
135126 {
136− DumpWord(tf->lineDefined,D);
137− DumpTString(tf->fileName,D);
127+ DumpInt(tf->lineDefined,D);
128+ DumpTString(tf->source,D);
138129 DumpCode(tf,D);
139130 DumpLocals(tf,D);
140− DumpConstants(tf,D);
131+ DumpConstants(tf,D,native);
132+ if (ferror(D))
133+ luaL_verror("write error" IN ": %s (errno=%d)",INLOC,strerror(errno),errno);
141134 }
142135
143−static void DumpHeader(TProtoFunc* Main, FILE* D)
136+static void DumpHeader(TProtoFunc* Main, FILE* D, int native)
144137 {
145− real t=TEST_NUMBER;
146138 fputc(ID_CHUNK,D);
147139 fputs(SIGNATURE,D);
148140 fputc(VERSION,D);
149− fputc(ID_NUMBER,D);
150− fputc(sizeof(t),D);
151− DumpNumber(t,D);
141+ if (native)
142+ {
143+ fputc(sizeof(real),D);
144+ DumpNumber(TEST_NUMBER,D,native,Main);
145+ }
146+ else
147+ fputc(0,D);
152148 }
153149
154−void DumpChunk(TProtoFunc* Main, FILE* D)
150+void luaU_dumpchunk(TProtoFunc* Main, FILE* D, int native)
155151 {
156− DumpHeader(Main,D);
157− DumpFunction(Main,D);
152+ DumpHeader(Main,D,native);
153+ DumpFunction(Main,D,native);
158154 }
src/luac/luac.c+51−48
@@ -1,5 +1,5 @@
11 /*
2−** $Id: luac.c,v 1.10 1998/07/12 00:38:30 lhf Exp $
2+** $Id: luac.c,v 1.17 1999/07/02 19:34:26 lhf Exp $
33 ** lua compiler (saves bytecodes to files; also list binary files)
44 ** See Copyright Notice in lua.h
55 */
@@ -9,43 +9,45 @@ · 3 unmodified lines
99 #include <string.h>
1010 #include "luac.h"
1111 #include "lparser.h"
12+#include "lstate.h"
1213 #include "lzio.h"
13−#include "luadebug.h"
1414
1515 #define OUTPUT "luac.out" /* default output file */
1616
17−extern void DumpChunk(TProtoFunc* Main, FILE* D);
18−extern void PrintChunk(TProtoFunc* Main);
19−extern void OptChunk(TProtoFunc* Main);
20−
2117 static FILE* efopen(char* name, char* mode);
2218 static void doit(int undump, char* filename);
2319
2420 static int listing=0; /* list bytecodes? */
25−static int debugging=0; /* debug? */
21+static int debugging=0; /* emit debug information? */
2622 static int dumping=1; /* dump bytecodes? */
2723 static int undumping=0; /* undump bytecodes? */
2824 static int optimizing=0; /* optimize? */
2925 static int parsing=0; /* parse only? */
26+static int testing=0; /* test integrity? */
3027 static int verbose=0; /* tell user what is done */
28+static int native=0; /* save numbers in native format? */
3129 static FILE* D; /* output file */
3230
33−static void usage(void)
31+static void usage(char* op)
3432 {
35− fprintf(stderr,"usage: "
36− "luac [-c | -u] [-D name] [-d] [-l] [-o output] [-O] [-p] [-q] [-v] [-V] [files]\n"
37− " -c\tcompile (default)\n"
38− " -u\tundump\n"
39− " -d\tgenerate debugging information\n"
40− " -D\tpredefine symbol for conditional compilation\n"
41− " -l\tlist (default for -u)\n"
42− " -o\toutput file for -c (default is \"" OUTPUT "\")\n"
43− " -O\toptimize\n"
44− " -p\tparse only\n"
45− " -q\tquiet (default for -c)\n"
46− " -v\tshow version information\n"
47− " -V\tverbose\n"
48− " -\tcompile \"stdin\"\n"
33+ if (op) fprintf(stderr,"luac: unrecognized option '%s'\n",op);
34+ fprintf(stderr,
35+ "usage: luac [options] [filenames]. Available options are:\n"
36+ " -c\t\tcompile (default)\n"
37+ " -d\t\tgenerate debugging information\n"
38+ " -D name\tpredefine 'name' for conditional compilation\n"
39+ " -l\t\tlist (default for -u)\n"
40+ " -n\t\tsave numbers in native format (file may not be portable)\n"
41+ " -o file\toutput file for -c (default is \"" OUTPUT "\")\n"
42+ " -O\t\toptimize\n"
43+ " -p\t\tparse only\n"
44+ " -q\t\tquiet (default for -c)\n"
45+ " -t\t\ttest code integrity\n"
46+ " -u\t\tundump\n"
47+ " -U name\tundefine 'name' for conditional compilation\n"
48+ " -v\t\tshow version information\n"
49+ " -V\t\tverbose\n"
50+ " -\t\tcompile \"stdin\"\n"
4951 );
5052 exit(1);
5153 }
@@ -61,7 +63,7 @@ int main(int argc, char* argv[]) · 9 unmodified lines
6163 {
6264 if (argv[i][0]!='-') /* end of options */
6365 break;
64− else if (IS("-")) /* use stdin */
66+ else if (IS("-")) /* end of options; use stdin */
6567 break;
6668 else if (IS("-c")) /* compile (and dump) */
6769 {
@@ -78,6 +80,8 @@ int main(int argc, char* argv[]) · 10 unmodified lines
7880 debugging=1;
7981 else if (IS("-l")) /* list */
8082 listing=1;
83+ else if (IS("-n")) /* native */
84+ native=1;
8185 else if (IS("-o")) /* output file */
8286 d=argv[++i];
8387 else if (IS("-O")) /* optimize */
@@ -89,34 +93,37 @@ int main(int argc, char* argv[]) · 5 unmodified lines
8993 }
9094 else if (IS("-q")) /* quiet */
9195 listing=0;
96+ else if (IS("-t")) /* test */
97+ testing=1;
9298 else if (IS("-u")) /* undump */
9399 {
94100 dumping=0;
95101 undumping=1;
96102 listing=1;
97103 }
104+ else if (IS("-U")) /* undefine */
105+ {
106+ TaggedString* s=luaS_new(argv[++i]);
107+ s->u.s.globalval.ttype=LUA_T_NIL;
108+ }
98109 else if (IS("-v")) /* show version */
99110 printf("%s %s\n(written by %s)\n\n",LUA_VERSION,LUA_COPYRIGHT,LUA_AUTHORS);
100111 else if (IS("-V")) /* verbose */
101112 verbose=1;
102113 else /* unknown option */
103− usage();
114+ usage(argv[i]);
104115 }
105116 --i; /* fake new argv[0] */
106117 argc-=i;
107118 argv+=i;
108119 if (dumping || parsing)
109120 {
110− if (argc<2) usage();
121+ if (argc<2) usage(NULL);
111122 if (dumping)
112123 {
113124 for (i=1; i<argc; i++) /* play safe with output file */
114125 if (IS(d)) luaL_verror("will not overwrite input file \"%s\"",d);
115126 D=efopen(d,"wb"); /* must open in binary mode */
116−#if ID_NUMBER==ID_NATIVE
117− if (verbose) fprintf(stderr,"luac: warning: "
118− "saving numbers in native format. file may not be portable.\n");
119−#endif
120127 }
121128 for (i=1; i<argc; i++) doit(0,IS("-")? NULL : argv[i]);
122129 if (dumping) fclose(D);
@@ -134,39 +141,35 @@ int main(int argc, char* argv[]) · 11 unmodified lines
134141 static void do_compile(ZIO* z)
135142 {
136143 TProtoFunc* Main;
137− if (optimizing) lua_debug=0; /* set debugging before parsing */
138− if (debugging) lua_debug=1;
144+ if (optimizing) L->debug=0;
145+ if (debugging) L->debug=1;
139146 Main=luaY_parser(z);
140− if (optimizing) OptChunk(Main);
141− if (listing) PrintChunk(Main);
142− if (dumping) DumpChunk(Main,D);
147+ if (optimizing) luaU_optchunk(Main);
148+ if (listing) luaU_printchunk(Main);
149+ if (testing) luaU_testchunk(Main);
150+ if (dumping) luaU_dumpchunk(Main,D,native);
143151 }
144152
145153 static void do_undump(ZIO* z)
146154 {
147− while (1)
155+ for (;;)
148156 {
149157 TProtoFunc* Main=luaU_undump1(z);
150158 if (Main==NULL) break;
151− if (optimizing) OptChunk(Main);
152− if (listing) PrintChunk(Main);
159+ if (optimizing) luaU_optchunk(Main);
160+ if (listing) luaU_printchunk(Main);
161+ if (testing) luaU_testchunk(Main);
153162 }
154163 }
155164
156165 static void doit(int undump, char* filename)
157166 {
158− FILE* f;
167+ FILE* f= (filename==NULL) ? stdin : efopen(filename, undump ? "rb" : "r");
159168 ZIO z;
160− if (filename==NULL)
161− {
162− f=stdin; filename="(stdin)";
163− }
164− else
165− {
166− f=efopen(filename, undump ? "rb" : "r");
167− }
168− zFopen(&z,f,filename);
169− if (verbose) fprintf(stderr,"%s\n",filename);
169+ char source[255+2]; /* +2 for '@' and '\0' */
170+ luaL_filesource(source,filename,sizeof(source));
171+ zFopen(&z,f,source);
172+ if (verbose) fprintf(stderr,"%s\n",source+1);
170173 if (undump) do_undump(&z); else do_compile(&z);
171174 if (f!=stdin) fclose(f);
172175 }
src/luac/luac.h+29−14
@@ -1,11 +1,12 @@
11 /*
2−** $Id: luac.h,v 1.6 1998/07/12 00:17:37 lhf Exp $
2+** $Id: luac.h,v 1.11 1999/07/02 19:34:26 lhf Exp $
33 ** definitions for luac
44 ** See Copyright Notice in lua.h
55 */
66
77 #include "lauxlib.h"
88 #include "lfunc.h"
9+#include "lmem.h"
910 #include "lobject.h"
1011 #include "lopcodes.h"
1112 #include "lstring.h"
@@ -13,21 +14,35 @@ · 1 unmodified line
1314
1415 typedef struct
1516 {
16− char* name;
17− int size;
18− int op;
19− int class;
20− int arg;
21− int arg2;
17+ char* name; /* name of opcode */
18+ int op; /* value of opcode */
19+ int class; /* class of opcode (byte variant) */
20+ int args; /* types of arguments (operands) */
21+ int arg; /* arg #1 */
22+ int arg2; /* arg #2 */
2223 } Opcode;
2324
24−int OpcodeInfo(TProtoFunc* tf, Byte* p, Opcode* I, char* xFILE, int xLINE);
25−int CodeSize(TProtoFunc* tf);
25+/* from dump.c */
26+void luaU_dumpchunk(TProtoFunc* Main, FILE* D, int native);
2627
27−#define INFO(tf,p,I) OpcodeInfo(tf,p,I,__FILE__,__LINE__)
28−#define fileName(tf) ( (tf->fileName)==NULL ? NULL : tf->fileName->str )
28+/* from opcode.c */
29+int luaU_opcodeinfo(TProtoFunc* tf, Byte* p, Opcode* I, char* xFILE, int xLINE);
30+int luaU_codesize(TProtoFunc* tf);
2931
32+/* from opt.c */
33+void luaU_optchunk(TProtoFunc* Main);
34+
35+/* from print.c */
36+void luaU_printchunk(TProtoFunc* Main);
37+
38+/* from test.c */
39+void luaU_testchunk(TProtoFunc* Main);
40+TObject* luaU_getconstant(TProtoFunc* tf, int i, int at);
41+
42+#define INFO(tf,p,I) luaU_opcodeinfo(tf,p,I,__FILE__,__LINE__)
43+
44+/* fake (but convenient) opcodes */
3045 #define NOP 255
31−#define STACK -1
32−#define ARGS -2
33−#define VARARGS -3
46+#define STACK (-1)
47+#define ARGS (-2)
48+#define VARARGS (-3)
src/luac/opcode.c+50−35
@@ -1,83 +1,98 @@
11 /*
2−** $Id: opcode.c,v 1.4 1998/07/12 00:17:37 lhf Exp $
2+** $Id: opcode.c,v 1.9 1999/05/25 19:58:55 lhf Exp $
33 ** opcode information
44 ** See Copyright Notice in lua.h
55 */
66
77 #include "luac.h"
88
9+enum { /* for Opcode.args */
10+ ARGS_NONE,
11+ ARGS_B,
12+ ARGS_W,
13+ ARGS_BB,
14+ ARGS_WB
15+};
16+
917 static Opcode Info[]= /* ORDER lopcodes.h */
1018 {
1119 #include "opcode.h"
1220 };
1321
22+static Opcode Fake[]= /* ORDER luac.h */
23+{
24+{ "NOP", NOP, NOP, ARGS_NONE, -1, -1 },
25+{ "STACK", STACK, STACK, ARGS_B, -1, -1 },
26+{ "ARGS", ARGS, ARGS, ARGS_B, -1, -1 },
27+{ "VARARGS", VARARGS, VARARGS, ARGS_B, -1, -1 },
28+};
29+
1430 #define NOPCODES (sizeof(Info)/sizeof(Info[0]))
1531
16−int OpcodeInfo(TProtoFunc* tf, Byte* p, Opcode* I, char* xFILE, int xLINE)
32+int luaU_opcodeinfo(TProtoFunc* tf, Byte* p, Opcode* I, char* xFILE, int xLINE)
1733 {
1834 Opcode OP;
1935 Byte* code=tf->code;
2036 int op=*p;
21− if (p==code)
37+ int size=1;
38+ if (p==code) /* first byte is STACK */
2239 {
23− OP.name="STACK";
24− OP.size=1;
25− OP.op=STACK;
26− OP.class=STACK;
40+ OP=Fake[-STACK];
2741 OP.arg=op;
2842 }
29− else if (p==code+1)
43+ else if (p==code+1) /* second byte is ARGS or VARARGS */
3044 {
31− OP.size=1;
32− if (op>=ZEROVARARG)
45+ if (op<ZEROVARARG)
3346 {
34− OP.name="VARARGS";
35− OP.op=VARARGS;
36− OP.class=VARARGS;
37− OP.arg=op-ZEROVARARG;
47+ OP=Fake[-ARGS];
48+ OP.arg=op;
3849 }
3950 else
4051 {
41− OP.name="ARGS";
42− OP.op=ARGS;
43− OP.class=ARGS;
44− OP.arg=op;
52+ OP=Fake[-VARARGS];
53+ OP.arg=op-ZEROVARARG;
4554 }
4655 }
47− else if (op==NOP)
56+ else if (op==NOP) /* NOP is fake */
4857 {
49− OP.name="NOP";
50− OP.size=1;
51− OP.op=NOP;
52− OP.class=NOP;
58+ OP=Fake[0];
5359 }
5460 else if (op>=NOPCODES) /* cannot happen */
5561 {
56− luaL_verror("internal error at %s:%d: bad opcode %d at %d in tf=%p",
57− xFILE, xLINE,op,(int)(p-code),tf);
62+ luaL_verror("[%s:%d] bad opcode %d at pc=%d" IN,
63+ xFILE,xLINE,op,(int)(p-code),INLOC);
5864 return 0;
5965 }
60− else
66+ else /* ordinary opcode */
6167 {
6268 OP=Info[op];
63− if (op==SETLIST || op==CLOSURE || op==CALLFUNC)
69+ switch (OP.args)
6470 {
65− OP.arg=p[1];
66− OP.arg2=p[2];
71+ case ARGS_NONE: size=1;
72+ break;
73+ case ARGS_B: size=2; OP.arg=p[1];
74+ break;
75+ case ARGS_W: size=3; OP.arg=(p[1]<<8)+p[2];
76+ break;
77+ case ARGS_BB: size=3; OP.arg=p[1]; OP.arg2=p[2];
78+ break;
79+ case ARGS_WB: size=4; OP.arg=(p[1]<<8)+p[2]; OP.arg2=p[3];
80+ break;
81+ default: /* cannot happen */
82+ luaL_verror("[%s:%d] bad args %d for %s at pc=%d" IN,
83+ __FILE__,__LINE__,OP.args,OP.name,(int)(p-code),INLOC);
84+ break;
6785 }
68− else if (OP.size==2) OP.arg=p[1];
69− else if (OP.size>=3) OP.arg=(p[1]<<8)+p[2];
70− if (op==SETLISTW || op==CLOSUREW) OP.arg2=p[3];
7186 }
7287 *I=OP;
73− return OP.size;
88+ return size;
7489 }
7590
76−int CodeSize(TProtoFunc* tf)
91+int luaU_codesize(TProtoFunc* tf)
7792 {
7893 Byte* code=tf->code;
7994 Byte* p=code;
80− while (1)
95+ for (;;)
8196 {
8297 Opcode OP;
8398 p+=INFO(tf,p,&OP);
src/luac/opcode.h+66−130
@@ -1,134 +1,70 @@
11 /*
2−** $Id: opcode.h,v 1.3 1998/06/25 15:50:09 lhf Exp $
2+** $Id: opcode.h,v 1.1 1999/03/25 13:43:05 lhf Exp $
33 ** opcode info to be #included into opcode.c
4−** extracted automatically from lopcodes.h by mkopcodeh
4+** extracted automatically from lopcodes.h by mkopcodeh -- DO NOT EDIT
55 ** See Copyright Notice in lua.h
66 */
7−{ "ENDCODE", 1, ENDCODE, ENDCODE, ENDCODE-ENDCODE-1, 0 },
8−{ "PUSHNIL", 2, PUSHNIL, PUSHNIL, PUSHNIL-PUSHNIL-1, 0 },
9−{ "PUSHNIL0", 1, PUSHNIL0, PUSHNIL, PUSHNIL0-PUSHNIL-1, 0 },
10−{ "PUSHNUMBER", 2, PUSHNUMBER, PUSHNUMBER, PUSHNUMBER-PUSHNUMBER-1, 0 },
11−{ "PUSHNUMBER0", 1, PUSHNUMBER0, PUSHNUMBER, PUSHNUMBER0-PUSHNUMBER-1, 0 },
12−{ "PUSHNUMBER1", 1, PUSHNUMBER1, PUSHNUMBER, PUSHNUMBER1-PUSHNUMBER-1, 0 },
13−{ "PUSHNUMBER2", 1, PUSHNUMBER2, PUSHNUMBER, PUSHNUMBER2-PUSHNUMBER-1, 0 },
14−{ "PUSHNUMBERW", 3, PUSHNUMBERW, PUSHNUMBER, PUSHNUMBERW-PUSHNUMBER-1, 0 },
15−{ "PUSHCONSTANT", 2, PUSHCONSTANT, PUSHCONSTANT, PUSHCONSTANT-PUSHCONSTANT-1, 0 },
16−{ "PUSHCONSTANT0", 1, PUSHCONSTANT0, PUSHCONSTANT, PUSHCONSTANT0-PUSHCONSTANT-1, 0 },
17−{ "PUSHCONSTANT1", 1, PUSHCONSTANT1, PUSHCONSTANT, PUSHCONSTANT1-PUSHCONSTANT-1, 0 },
18−{ "PUSHCONSTANT2", 1, PUSHCONSTANT2, PUSHCONSTANT, PUSHCONSTANT2-PUSHCONSTANT-1, 0 },
19−{ "PUSHCONSTANT3", 1, PUSHCONSTANT3, PUSHCONSTANT, PUSHCONSTANT3-PUSHCONSTANT-1, 0 },
20−{ "PUSHCONSTANT4", 1, PUSHCONSTANT4, PUSHCONSTANT, PUSHCONSTANT4-PUSHCONSTANT-1, 0 },
21−{ "PUSHCONSTANT5", 1, PUSHCONSTANT5, PUSHCONSTANT, PUSHCONSTANT5-PUSHCONSTANT-1, 0 },
22−{ "PUSHCONSTANT6", 1, PUSHCONSTANT6, PUSHCONSTANT, PUSHCONSTANT6-PUSHCONSTANT-1, 0 },
23−{ "PUSHCONSTANT7", 1, PUSHCONSTANT7, PUSHCONSTANT, PUSHCONSTANT7-PUSHCONSTANT-1, 0 },
24−{ "PUSHCONSTANTW", 3, PUSHCONSTANTW, PUSHCONSTANT, PUSHCONSTANTW-PUSHCONSTANT-1, 0 },
25−{ "PUSHUPVALUE", 2, PUSHUPVALUE, PUSHUPVALUE, PUSHUPVALUE-PUSHUPVALUE-1, 0 },
26−{ "PUSHUPVALUE0", 1, PUSHUPVALUE0, PUSHUPVALUE, PUSHUPVALUE0-PUSHUPVALUE-1, 0 },
27−{ "PUSHUPVALUE1", 1, PUSHUPVALUE1, PUSHUPVALUE, PUSHUPVALUE1-PUSHUPVALUE-1, 0 },
28−{ "PUSHLOCAL", 2, PUSHLOCAL, PUSHLOCAL, PUSHLOCAL-PUSHLOCAL-1, 0 },
29−{ "PUSHLOCAL0", 1, PUSHLOCAL0, PUSHLOCAL, PUSHLOCAL0-PUSHLOCAL-1, 0 },
30−{ "PUSHLOCAL1", 1, PUSHLOCAL1, PUSHLOCAL, PUSHLOCAL1-PUSHLOCAL-1, 0 },
31−{ "PUSHLOCAL2", 1, PUSHLOCAL2, PUSHLOCAL, PUSHLOCAL2-PUSHLOCAL-1, 0 },
32−{ "PUSHLOCAL3", 1, PUSHLOCAL3, PUSHLOCAL, PUSHLOCAL3-PUSHLOCAL-1, 0 },
33−{ "PUSHLOCAL4", 1, PUSHLOCAL4, PUSHLOCAL, PUSHLOCAL4-PUSHLOCAL-1, 0 },
34−{ "PUSHLOCAL5", 1, PUSHLOCAL5, PUSHLOCAL, PUSHLOCAL5-PUSHLOCAL-1, 0 },
35−{ "PUSHLOCAL6", 1, PUSHLOCAL6, PUSHLOCAL, PUSHLOCAL6-PUSHLOCAL-1, 0 },
36−{ "PUSHLOCAL7", 1, PUSHLOCAL7, PUSHLOCAL, PUSHLOCAL7-PUSHLOCAL-1, 0 },
37−{ "GETGLOBAL", 2, GETGLOBAL, GETGLOBAL, GETGLOBAL-GETGLOBAL-1, 0 },
38−{ "GETGLOBAL0", 1, GETGLOBAL0, GETGLOBAL, GETGLOBAL0-GETGLOBAL-1, 0 },
39−{ "GETGLOBAL1", 1, GETGLOBAL1, GETGLOBAL, GETGLOBAL1-GETGLOBAL-1, 0 },
40−{ "GETGLOBAL2", 1, GETGLOBAL2, GETGLOBAL, GETGLOBAL2-GETGLOBAL-1, 0 },
41−{ "GETGLOBAL3", 1, GETGLOBAL3, GETGLOBAL, GETGLOBAL3-GETGLOBAL-1, 0 },
42−{ "GETGLOBAL4", 1, GETGLOBAL4, GETGLOBAL, GETGLOBAL4-GETGLOBAL-1, 0 },
43−{ "GETGLOBAL5", 1, GETGLOBAL5, GETGLOBAL, GETGLOBAL5-GETGLOBAL-1, 0 },
44−{ "GETGLOBAL6", 1, GETGLOBAL6, GETGLOBAL, GETGLOBAL6-GETGLOBAL-1, 0 },
45−{ "GETGLOBAL7", 1, GETGLOBAL7, GETGLOBAL, GETGLOBAL7-GETGLOBAL-1, 0 },
46−{ "GETGLOBALW", 3, GETGLOBALW, GETGLOBAL, GETGLOBALW-GETGLOBAL-1, 0 },
47−{ "GETTABLE", 1, GETTABLE, GETTABLE, GETTABLE-GETTABLE-1, 0 },
48−{ "GETDOTTED", 2, GETDOTTED, GETDOTTED, GETDOTTED-GETDOTTED-1, 0 },
49−{ "GETDOTTED0", 1, GETDOTTED0, GETDOTTED, GETDOTTED0-GETDOTTED-1, 0 },
50−{ "GETDOTTED1", 1, GETDOTTED1, GETDOTTED, GETDOTTED1-GETDOTTED-1, 0 },
51−{ "GETDOTTED2", 1, GETDOTTED2, GETDOTTED, GETDOTTED2-GETDOTTED-1, 0 },
52−{ "GETDOTTED3", 1, GETDOTTED3, GETDOTTED, GETDOTTED3-GETDOTTED-1, 0 },
53−{ "GETDOTTED4", 1, GETDOTTED4, GETDOTTED, GETDOTTED4-GETDOTTED-1, 0 },
54−{ "GETDOTTED5", 1, GETDOTTED5, GETDOTTED, GETDOTTED5-GETDOTTED-1, 0 },
55−{ "GETDOTTED6", 1, GETDOTTED6, GETDOTTED, GETDOTTED6-GETDOTTED-1, 0 },
56−{ "GETDOTTED7", 1, GETDOTTED7, GETDOTTED, GETDOTTED7-GETDOTTED-1, 0 },
57−{ "GETDOTTEDW", 3, GETDOTTEDW, GETDOTTED, GETDOTTEDW-GETDOTTED-1, 0 },
58−{ "PUSHSELF", 2, PUSHSELF, PUSHSELF, PUSHSELF-PUSHSELF-1, 0 },
59−{ "PUSHSELF0", 1, PUSHSELF0, PUSHSELF, PUSHSELF0-PUSHSELF-1, 0 },
60−{ "PUSHSELF1", 1, PUSHSELF1, PUSHSELF, PUSHSELF1-PUSHSELF-1, 0 },
61−{ "PUSHSELF2", 1, PUSHSELF2, PUSHSELF, PUSHSELF2-PUSHSELF-1, 0 },
62−{ "PUSHSELF3", 1, PUSHSELF3, PUSHSELF, PUSHSELF3-PUSHSELF-1, 0 },
63−{ "PUSHSELF4", 1, PUSHSELF4, PUSHSELF, PUSHSELF4-PUSHSELF-1, 0 },
64−{ "PUSHSELF5", 1, PUSHSELF5, PUSHSELF, PUSHSELF5-PUSHSELF-1, 0 },
65−{ "PUSHSELF6", 1, PUSHSELF6, PUSHSELF, PUSHSELF6-PUSHSELF-1, 0 },
66−{ "PUSHSELF7", 1, PUSHSELF7, PUSHSELF, PUSHSELF7-PUSHSELF-1, 0 },
67−{ "PUSHSELFW", 3, PUSHSELFW, PUSHSELF, PUSHSELFW-PUSHSELF-1, 0 },
68−{ "CREATEARRAY", 2, CREATEARRAY, CREATEARRAY, CREATEARRAY-CREATEARRAY-1, 0 },
69−{ "CREATEARRAY0", 1, CREATEARRAY0, CREATEARRAY, CREATEARRAY0-CREATEARRAY-1, 0 },
70−{ "CREATEARRAY1", 1, CREATEARRAY1, CREATEARRAY, CREATEARRAY1-CREATEARRAY-1, 0 },
71−{ "CREATEARRAYW", 3, CREATEARRAYW, CREATEARRAY, CREATEARRAYW-CREATEARRAY-1, 0 },
72−{ "SETLOCAL", 2, SETLOCAL, SETLOCAL, SETLOCAL-SETLOCAL-1, 0 },
73−{ "SETLOCAL0", 1, SETLOCAL0, SETLOCAL, SETLOCAL0-SETLOCAL-1, 0 },
74−{ "SETLOCAL1", 1, SETLOCAL1, SETLOCAL, SETLOCAL1-SETLOCAL-1, 0 },
75−{ "SETLOCAL2", 1, SETLOCAL2, SETLOCAL, SETLOCAL2-SETLOCAL-1, 0 },
76−{ "SETLOCAL3", 1, SETLOCAL3, SETLOCAL, SETLOCAL3-SETLOCAL-1, 0 },
77−{ "SETLOCAL4", 1, SETLOCAL4, SETLOCAL, SETLOCAL4-SETLOCAL-1, 0 },
78−{ "SETLOCAL5", 1, SETLOCAL5, SETLOCAL, SETLOCAL5-SETLOCAL-1, 0 },
79−{ "SETLOCAL6", 1, SETLOCAL6, SETLOCAL, SETLOCAL6-SETLOCAL-1, 0 },
80−{ "SETLOCAL7", 1, SETLOCAL7, SETLOCAL, SETLOCAL7-SETLOCAL-1, 0 },
81−{ "SETGLOBAL", 2, SETGLOBAL, SETGLOBAL, SETGLOBAL-SETGLOBAL-1, 0 },
82−{ "SETGLOBAL0", 1, SETGLOBAL0, SETGLOBAL, SETGLOBAL0-SETGLOBAL-1, 0 },
83−{ "SETGLOBAL1", 1, SETGLOBAL1, SETGLOBAL, SETGLOBAL1-SETGLOBAL-1, 0 },
84−{ "SETGLOBAL2", 1, SETGLOBAL2, SETGLOBAL, SETGLOBAL2-SETGLOBAL-1, 0 },
85−{ "SETGLOBAL3", 1, SETGLOBAL3, SETGLOBAL, SETGLOBAL3-SETGLOBAL-1, 0 },
86−{ "SETGLOBAL4", 1, SETGLOBAL4, SETGLOBAL, SETGLOBAL4-SETGLOBAL-1, 0 },
87−{ "SETGLOBAL5", 1, SETGLOBAL5, SETGLOBAL, SETGLOBAL5-SETGLOBAL-1, 0 },
88−{ "SETGLOBAL6", 1, SETGLOBAL6, SETGLOBAL, SETGLOBAL6-SETGLOBAL-1, 0 },
89−{ "SETGLOBAL7", 1, SETGLOBAL7, SETGLOBAL, SETGLOBAL7-SETGLOBAL-1, 0 },
90−{ "SETGLOBALW", 3, SETGLOBALW, SETGLOBAL, SETGLOBALW-SETGLOBAL-1, 0 },
91−{ "SETTABLE0", 1, SETTABLE0, SETTABLE0, SETTABLE0-SETTABLE0-1, 0 },
92−{ "SETTABLE", 2, SETTABLE, SETTABLE, SETTABLE-SETTABLE-1, 0 },
93−{ "SETLIST", 3, SETLIST, SETLIST, SETLIST-SETLIST-1, 0 },
94−{ "SETLIST0", 2, SETLIST0, SETLIST, SETLIST0-SETLIST-1, 0 },
95−{ "SETLISTW", 4, SETLISTW, SETLIST, SETLISTW-SETLIST-1, 0 },
96−{ "SETMAP", 2, SETMAP, SETMAP, SETMAP-SETMAP-1, 0 },
97−{ "SETMAP0", 1, SETMAP0, SETMAP, SETMAP0-SETMAP-1, 0 },
98−{ "EQOP", 1, EQOP, EQOP, EQOP-EQOP-1, 0 },
99−{ "NEQOP", 1, NEQOP, NEQOP, NEQOP-NEQOP-1, 0 },
100−{ "LTOP", 1, LTOP, LTOP, LTOP-LTOP-1, 0 },
101−{ "LEOP", 1, LEOP, LEOP, LEOP-LEOP-1, 0 },
102−{ "GTOP", 1, GTOP, GTOP, GTOP-GTOP-1, 0 },
103−{ "GEOP", 1, GEOP, GEOP, GEOP-GEOP-1, 0 },
104−{ "ADDOP", 1, ADDOP, ADDOP, ADDOP-ADDOP-1, 0 },
105−{ "SUBOP", 1, SUBOP, SUBOP, SUBOP-SUBOP-1, 0 },
106−{ "MULTOP", 1, MULTOP, MULTOP, MULTOP-MULTOP-1, 0 },
107−{ "DIVOP", 1, DIVOP, DIVOP, DIVOP-DIVOP-1, 0 },
108−{ "POWOP", 1, POWOP, POWOP, POWOP-POWOP-1, 0 },
109−{ "CONCOP", 1, CONCOP, CONCOP, CONCOP-CONCOP-1, 0 },
110−{ "MINUSOP", 1, MINUSOP, MINUSOP, MINUSOP-MINUSOP-1, 0 },
111−{ "NOTOP", 1, NOTOP, NOTOP, NOTOP-NOTOP-1, 0 },
112−{ "ONTJMP", 2, ONTJMP, ONTJMP, ONTJMP-ONTJMP-1, 0 },
113−{ "ONTJMPW", 3, ONTJMPW, ONTJMP, ONTJMPW-ONTJMP-1, 0 },
114−{ "ONFJMP", 2, ONFJMP, ONFJMP, ONFJMP-ONFJMP-1, 0 },
115−{ "ONFJMPW", 3, ONFJMPW, ONFJMP, ONFJMPW-ONFJMP-1, 0 },
116−{ "JMP", 2, JMP, JMP, JMP-JMP-1, 0 },
117−{ "JMPW", 3, JMPW, JMP, JMPW-JMP-1, 0 },
118−{ "IFFJMP", 2, IFFJMP, IFFJMP, IFFJMP-IFFJMP-1, 0 },
119−{ "IFFJMPW", 3, IFFJMPW, IFFJMP, IFFJMPW-IFFJMP-1, 0 },
120−{ "IFTUPJMP", 2, IFTUPJMP, IFTUPJMP, IFTUPJMP-IFTUPJMP-1, 0 },
121−{ "IFTUPJMPW", 3, IFTUPJMPW, IFTUPJMP, IFTUPJMPW-IFTUPJMP-1, 0 },
122−{ "IFFUPJMP", 2, IFFUPJMP, IFFUPJMP, IFFUPJMP-IFFUPJMP-1, 0 },
123−{ "IFFUPJMPW", 3, IFFUPJMPW, IFFUPJMP, IFFUPJMPW-IFFUPJMP-1, 0 },
124−{ "CLOSURE", 3, CLOSURE, CLOSURE, CLOSURE-CLOSURE-1, 0 },
125−{ "CLOSUREW", 4, CLOSUREW, CLOSURE, CLOSUREW-CLOSURE-1, 0 },
126−{ "CALLFUNC", 3, CALLFUNC, CALLFUNC, CALLFUNC-CALLFUNC-1, 0 },
127−{ "CALLFUNC0", 2, CALLFUNC0, CALLFUNC, CALLFUNC0-CALLFUNC-1, 0 },
128−{ "CALLFUNC1", 2, CALLFUNC1, CALLFUNC, CALLFUNC1-CALLFUNC-1, 0 },
129−{ "RETCODE", 2, RETCODE, RETCODE, RETCODE-RETCODE-1, 0 },
130−{ "SETLINE", 2, SETLINE, SETLINE, SETLINE-SETLINE-1, 0 },
131−{ "SETLINEW", 3, SETLINEW, SETLINE, SETLINEW-SETLINE-1, 0 },
132−{ "POP", 2, POP, POP, POP-POP-1, 0 },
133−{ "POP0", 1, POP0, POP, POP0-POP-1, 0 },
134−{ "POP1", 1, POP1, POP, POP1-POP-1, 0 },
7+{ "ENDCODE", ENDCODE, ENDCODE, ARGS_NONE, -1, -1 },
8+{ "RETCODE", RETCODE, RETCODE, ARGS_B, -1, -1 },
9+{ "CALL", CALL, CALL, ARGS_BB, -1, -1 },
10+{ "TAILCALL", TAILCALL, TAILCALL, ARGS_BB, -1, -1 },
11+{ "PUSHNIL", PUSHNIL, PUSHNIL, ARGS_B, -1, -1 },
12+{ "POP", POP, POP, ARGS_B, -1, -1 },
13+{ "PUSHNUMBERW", PUSHNUMBERW, PUSHNUMBER, ARGS_W, -1, -1 },
14+{ "PUSHNUMBER", PUSHNUMBER, PUSHNUMBER, ARGS_B, -1, -1 },
15+{ "PUSHNUMBERNEGW", PUSHNUMBERNEGW, PUSHNUMBERNEG, ARGS_W, -1, -1 },
16+{ "PUSHNUMBERNEG", PUSHNUMBERNEG, PUSHNUMBERNEG, ARGS_B, -1, -1 },
17+{ "PUSHCONSTANTW", PUSHCONSTANTW, PUSHCONSTANT, ARGS_W, -1, -1 },
18+{ "PUSHCONSTANT", PUSHCONSTANT, PUSHCONSTANT, ARGS_B, -1, -1 },
19+{ "PUSHUPVALUE", PUSHUPVALUE, PUSHUPVALUE, ARGS_B, -1, -1 },
20+{ "PUSHLOCAL", PUSHLOCAL, PUSHLOCAL, ARGS_B, -1, -1 },
21+{ "GETGLOBALW", GETGLOBALW, GETGLOBAL, ARGS_W, -1, -1 },
22+{ "GETGLOBAL", GETGLOBAL, GETGLOBAL, ARGS_B, -1, -1 },
23+{ "GETTABLE", GETTABLE, GETTABLE, ARGS_NONE, -1, -1 },
24+{ "GETDOTTEDW", GETDOTTEDW, GETDOTTED, ARGS_W, -1, -1 },
25+{ "GETDOTTED", GETDOTTED, GETDOTTED, ARGS_B, -1, -1 },
26+{ "PUSHSELFW", PUSHSELFW, PUSHSELF, ARGS_W, -1, -1 },
27+{ "PUSHSELF", PUSHSELF, PUSHSELF, ARGS_B, -1, -1 },
28+{ "CREATEARRAYW", CREATEARRAYW, CREATEARRAY, ARGS_W, -1, -1 },
29+{ "CREATEARRAY", CREATEARRAY, CREATEARRAY, ARGS_B, -1, -1 },
30+{ "SETLOCAL", SETLOCAL, SETLOCAL, ARGS_B, -1, -1 },
31+{ "SETGLOBALW", SETGLOBALW, SETGLOBAL, ARGS_W, -1, -1 },
32+{ "SETGLOBAL", SETGLOBAL, SETGLOBAL, ARGS_B, -1, -1 },
33+{ "SETTABLEPOP", SETTABLEPOP, SETTABLEPOP, ARGS_NONE, -1, -1 },
34+{ "SETTABLE", SETTABLE, SETTABLE, ARGS_B, -1, -1 },
35+{ "SETLISTW", SETLISTW, SETLIST, ARGS_WB, -1, -1 },
36+{ "SETLIST", SETLIST, SETLIST, ARGS_BB, -1, -1 },
37+{ "SETMAP", SETMAP, SETMAP, ARGS_B, -1, -1 },
38+{ "NEQOP", NEQOP, NEQOP, ARGS_NONE, -1, -1 },
39+{ "EQOP", EQOP, EQOP, ARGS_NONE, -1, -1 },
40+{ "LTOP", LTOP, LTOP, ARGS_NONE, -1, -1 },
41+{ "LEOP", LEOP, LEOP, ARGS_NONE, -1, -1 },
42+{ "GTOP", GTOP, GTOP, ARGS_NONE, -1, -1 },
43+{ "GEOP", GEOP, GEOP, ARGS_NONE, -1, -1 },
44+{ "ADDOP", ADDOP, ADDOP, ARGS_NONE, -1, -1 },
45+{ "SUBOP", SUBOP, SUBOP, ARGS_NONE, -1, -1 },
46+{ "MULTOP", MULTOP, MULTOP, ARGS_NONE, -1, -1 },
47+{ "DIVOP", DIVOP, DIVOP, ARGS_NONE, -1, -1 },
48+{ "POWOP", POWOP, POWOP, ARGS_NONE, -1, -1 },
49+{ "CONCOP", CONCOP, CONCOP, ARGS_NONE, -1, -1 },
50+{ "MINUSOP", MINUSOP, MINUSOP, ARGS_NONE, -1, -1 },
51+{ "NOTOP", NOTOP, NOTOP, ARGS_NONE, -1, -1 },
52+{ "ONTJMPW", ONTJMPW, ONTJMP, ARGS_W, -1, -1 },
53+{ "ONTJMP", ONTJMP, ONTJMP, ARGS_B, -1, -1 },
54+{ "ONFJMPW", ONFJMPW, ONFJMP, ARGS_W, -1, -1 },
55+{ "ONFJMP", ONFJMP, ONFJMP, ARGS_B, -1, -1 },
56+{ "JMPW", JMPW, JMP, ARGS_W, -1, -1 },
57+{ "JMP", JMP, JMP, ARGS_B, -1, -1 },
58+{ "IFFJMPW", IFFJMPW, IFFJMP, ARGS_W, -1, -1 },
59+{ "IFFJMP", IFFJMP, IFFJMP, ARGS_B, -1, -1 },
60+{ "IFTUPJMPW", IFTUPJMPW, IFTUPJMP, ARGS_W, -1, -1 },
61+{ "IFTUPJMP", IFTUPJMP, IFTUPJMP, ARGS_B, -1, -1 },
62+{ "IFFUPJMPW", IFFUPJMPW, IFFUPJMP, ARGS_W, -1, -1 },
63+{ "IFFUPJMP", IFFUPJMP, IFFUPJMP, ARGS_B, -1, -1 },
64+{ "CLOSUREW", CLOSUREW, CLOSURE, ARGS_WB, -1, -1 },
65+{ "CLOSURE", CLOSURE, CLOSURE, ARGS_BB, -1, -1 },
66+{ "SETLINEW", SETLINEW, SETLINE, ARGS_W, -1, -1 },
67+{ "SETLINE", SETLINE, SETLINE, ARGS_B, -1, -1 },
68+{ "LONGARGW", LONGARGW, LONGARG, ARGS_W, -1, -1 },
69+{ "LONGARG", LONGARG, LONGARG, ARGS_B, -1, -1 },
70+{ "CHECKSTACK", CHECKSTACK, CHECKSTACK, ARGS_B, -1, -1 },
src/luac/opt.c+147−94
@@ -1,70 +1,126 @@
11 /*
2−** $Id: opt.c,v 1.4 1998/04/02 20:44:08 lhf Exp $
2+** $Id: opt.c,v 1.12 1999/07/02 19:34:26 lhf Exp $
33 ** optimize bytecodes
44 ** See Copyright Notice in lua.h
55 */
66
77 #include <stdio.h>
88 #include <stdlib.h>
9+#include <string.h>
910 #include "luac.h"
10−#include "lmem.h"
11+
12+static void FixArg(Byte* p, int i, int j, int isconst)
13+{
14+ if (j==i)
15+ ;
16+ else if (i<=MAX_BYTE) /* j<i, so j fits where i did */
17+ p[1]=j;
18+ else if (i<=MAX_WORD)
19+ {
20+ if (isconst && j<=MAX_BYTE) /* may use byte variant instead */
21+ {
22+ p[0]++; /* byte variant follows word variant */
23+ p[1]=j;
24+ p[2]=NOP;
25+ }
26+ else /* stuck with word variant */
27+ {
28+ p[1]=j>>8;
29+ p[2]=j;
30+ }
31+ }
32+ else /* previous instruction must've been LONGARG */
33+ {
34+ if (isconst && j<=MAX_WORD) p[-2]=p[-1]=NOP; else p[-1]=j>>16;
35+ p[1]=j>>8;
36+ p[2]=j;
37+ }
38+}
1139
1240 static void FixConstants(TProtoFunc* tf, int* C)
1341 {
1442 Byte* code=tf->code;
1543 Byte* p=code;
16− while (1)
44+ int longarg=0;
45+ for (;;)
1746 {
1847 Opcode OP;
1948 int n=INFO(tf,p,&OP);
2049 int op=OP.class;
21− int i=OP.arg;
22− if (op==ENDCODE) break;
23− if ( op==PUSHCONSTANT || op==GETDOTTED || op==PUSHSELF ||
24− op==GETGLOBAL || op==SETGLOBAL)
50+ int i=OP.arg+longarg;
51+ longarg=0;
52+ if (op==PUSHCONSTANT || op==GETGLOBAL || op==GETDOTTED ||
53+ op==PUSHSELF || op==SETGLOBAL || op==CLOSURE)
54+ FixArg(p,i,C[i],1);
55+ else if (op==LONGARG) longarg=i<<16;
56+ else if (op==ENDCODE) break;
57+ p+=n;
58+ }
59+}
60+
61+#define UNREF 1 /* "type" of unused constants */
62+#define BIAS 128 /* mark for used constants */
63+
64+static void NoUnrefs(TProtoFunc* tf)
65+{
66+ int i,n=tf->nconsts;
67+ Byte* code=tf->code;
68+ Byte* p=code;
69+ int longarg=0;
70+ for (;;) /* mark all used constants */
71+ {
72+ Opcode OP;
73+ int n=INFO(tf,p,&OP);
74+ int op=OP.class;
75+ int i=OP.arg+longarg;
76+ longarg=0;
77+ if (op==PUSHCONSTANT || op==GETGLOBAL || op==GETDOTTED ||
78+ op==PUSHSELF || op==SETGLOBAL || op==CLOSURE)
2579 {
26− int j=C[i];
27− if (j==i)
28− ;
29− else if (n==1)
30− {
31− p[0]=op+j+1;
32− }
33− else if (n==2)
34− {
35− if (j<8) { p[0]=op+j+1; p[1]=NOP; } else p[1]=j;
36− }
37− else
38− {
39− if (j<=255)
40− {
41− p[0]=op;
42− p[1]=j;
43− p[2]=NOP;
44− }
45− else
46− {
47− p[1]= 0x0000FF & (j>>8);
48− p[2]= 0x0000FF & j;
49− }
50− }
80+ TObject* o=tf->consts+i;
81+ if (ttype(o)<=0) ttype(o)+=BIAS; /* mark as used */
5182 }
83+ else if (op==LONGARG) longarg=i<<16;
84+ else if (op==ENDCODE) break;
5285 p+=n;
5386 }
87+ for (i=0; i<n; i++) /* mark all unused constants */
88+ {
89+ TObject* o=tf->consts+i;
90+ if (ttype(o)<=0)
91+ ttype(o)=UNREF; /* mark as unused */
92+ else
93+ ttype(o)-=BIAS; /* unmark used constant */
94+ }
5495 }
5596
56−static TProtoFunc* TF;
97+#define CMP(oa,ob,f) memcmp(&f(oa),&f(ob),sizeof(f(oa)))
5798
58−static int compare(const void* a, const void *b)
99+static int compare(TProtoFunc* tf, int ia, int ib)
100+{
101+ TObject* oa=tf->consts+ia;
102+ TObject* ob=tf->consts+ib;
103+ int t=ttype(oa)-ttype(ob);
104+ if (t) return t;
105+ switch (ttype(oa))
106+ {
107+ case LUA_T_NUMBER: return CMP(oa,ob,nvalue);
108+ case LUA_T_STRING: return CMP(oa,ob,tsvalue);
109+ case LUA_T_PROTO: return CMP(oa,ob,tfvalue);
110+ case LUA_T_NIL: return 0;
111+ case UNREF: return 0;
112+ default: return ia-ib; /* cannot happen */
113+ }
114+}
115+
116+static TProtoFunc* TF; /* for sort */
117+
118+static int compare1(const void* a, const void* b)
59119 {
60120 int ia=*(int*)a;
61121 int ib=*(int*)b;
62− int t;
63− TObject* oa=TF->consts+ia;
64− TObject* ob=TF->consts+ib;
65− t=ttype(oa)-ttype(ob); if (t) return t;
66− t=oa->value.i-ob->value.i; if (t) return t;
67− return ia-ib;
122+ int t=compare(TF,ia,ib);
123+ return (t) ? t : ia-ib;
68124 }
69125
70126 static void OptConstants(TProtoFunc* tf)
@@ -74,43 +130,60 @@ static void OptConstants(TProtoFunc* tf) · 3 unmodified lines
74130 int i,k;
75131 int n=tf->nconsts;
76132 if (n==0) return;
77− C=luaM_reallocvector(C,n,int);
78− D=luaM_reallocvector(D,n,int);
133+ luaM_reallocvector(C,n,int);
134+ luaM_reallocvector(D,n,int);
135+ NoUnrefs(tf);
79136 for (i=0; i<n; i++) C[i]=D[i]=i; /* group duplicates */
80− TF=tf; qsort(C,n,sizeof(C[0]),compare);
137+ TF=tf; qsort(C,n,sizeof(C[0]),compare1);
81138 k=C[0]; /* build duplicate table */
82139 for (i=1; i<n; i++)
83140 {
84141 int j=C[i];
85− TObject* oa=tf->consts+k;
86− TObject* ob=tf->consts+j;
87− if (ttype(oa)==ttype(ob) && oa->value.i==ob->value.i) D[j]=k; else k=j;
142+ if (compare(tf,k,j)==0) D[j]=k; else k=j;
88143 }
89144 k=0; /* build rename map & pack constants */
90145 for (i=0; i<n; i++)
91146 {
92− if (D[i]==i) { tf->consts[k]=tf->consts[i]; C[i]=k++; } else C[i]=C[D[i]];
147+ if (D[i]==i) /* new value */
148+ {
149+ TObject* o=tf->consts+i;
150+ if (ttype(o)!=UNREF)
151+ {
152+ tf->consts[k]=tf->consts[i];
153+ C[i]=k++;
154+ }
155+ }
156+ else C[i]=C[D[i]];
157+ }
158+ if (k<n)
159+ {
160+printf("\t" SOURCE " reduced constants from %d to %d\n",
161+ tf->source->str,tf->lineDefined,n,k);
162+ FixConstants(tf,C);
163+ tf->nconsts=k;
93164 }
94− if (k>=n) return;
95−printf("\t\"%s\":%d reduced constants from %d to %d\n",
96− tf->fileName->str,tf->lineDefined,n,k);
97− tf->nconsts=k;
98− FixConstants(tf,C);
99165 }
100166
101167 static int NoDebug(TProtoFunc* tf)
102168 {
103169 Byte* code=tf->code;
104170 Byte* p=code;
171+ int lop=NOP; /* last opcode */
105172 int nop=0;
106− while (1) /* change SETLINE to NOP */
173+ for (;;) /* change SETLINE to NOP */
107174 {
108175 Opcode OP;
109176 int n=INFO(tf,p,&OP);
110177 int op=OP.class;
111− if (op==ENDCODE) break;
112178 if (op==NOP) ++nop;
113− if (op==SETLINE) { nop+=n; memset(p,NOP,n); }
179+ else if (op==SETLINE)
180+ {
181+ int m;
182+ if (lop==LONGARG) m=2; else if (lop==LONGARGW) m=3; else m=0;
183+ nop+=n+m; memset(p-m,NOP,n+m);
184+ }
185+ else if (op==ENDCODE) break;
186+ lop=OP.op;
114187 p+=n;
115188 }
116189 return nop;
@@ -125,8 +198,8 @@ static int FixJump(TProtoFunc* tf, Byte* a, Byte* b) · 8 unmodified lines
125198 Opcode OP;
126199 int n=INFO(tf,p,&OP);
127200 int op=OP.class;
128− if (op==ENDCODE) break;
129201 if (op==NOP) ++nop;
202+ else if (op==ENDCODE) break;
130203 p+=n;
131204 }
132205 return nop;
@@ -136,42 +209,22 @@ static void FixJumps(TProtoFunc* tf) · 3 unmodified lines
136209 {
137210 Byte* code=tf->code;
138211 Byte* p=code;
139− while (1)
212+ int longarg=0;
213+ for (;;)
140214 {
141215 Opcode OP;
142216 int n=INFO(tf,p,&OP);
143217 int op=OP.class;
144− int i=OP.arg;
145− int nop;
218+ int i=OP.arg+longarg;
219+ int nop=0;
220+ longarg=0;
146221 if (op==ENDCODE) break;
147− nop=0;
148− if (op==IFTUPJMP || op==IFFUPJMP) nop=FixJump(tf,p-i+n,p); else
149− if (op==ONTJMP || op==ONFJMP || op==JMP || op==IFFJMP) nop=FixJump(tf,p,p+i+n);
150− if (nop>0)
151− {
152− int j=i-nop;
153− if (n==2)
154− p[1]=j;
155− else
156−#if 0
157− {
158− if (j<=255) /* does NOT work for nested loops */
159− {
160− if (op==IFTUPJMP || op==IFFUPJMP) --j;
161− p[0]=OP.op-1; /* *JMP and *JMPW are consecutive */
162− p[1]=j;
163− p[2]=NOP;
164− }
165− else
166−#endif
167− {
168− p[1]= 0x0000FF & (j>>8);
169− p[2]= 0x0000FF & j;
170− }
171−#if 0
172− }
173−#endif
174− }
222+ else if (op==IFTUPJMP || op==IFFUPJMP)
223+ nop=FixJump(tf,p-i+n,p);
224+ else if (op==ONTJMP || op==ONFJMP || op==JMP || op==IFFJMP)
225+ nop=FixJump(tf,p,p+i+n);
226+ else if (op==LONGARG) longarg=i<<16;
227+ if (nop>0) FixArg(p,i,i-nop,0);
175228 p+=n;
176229 }
177230 }
@@ -181,7 +234,7 @@ static void PackCode(TProtoFunc* tf) · 3 unmodified lines
181234 Byte* code=tf->code;
182235 Byte* p=code;
183236 Byte* q=code;
184− while (1)
237+ for (;;)
185238 {
186239 Opcode OP;
187240 int n=INFO(tf,p,&OP);
@@ -190,14 +243,13 @@ static void PackCode(TProtoFunc* tf) · 2 unmodified lines
190243 p+=n;
191244 if (op==ENDCODE) break;
192245 }
193−printf("\t\"%s\":%d reduced code from %d to %d\n",
194− tf->fileName->str,tf->lineDefined,(int)(p-code),(int)(q-code));
246+printf("\t" SOURCE " reduced code from %d to %d\n",
247+ tf->source->str,tf->lineDefined,(int)(p-code),(int)(q-code));
195248 }
196249
197250 static void OptCode(TProtoFunc* tf)
198251 {
199− int nop=NoDebug(tf);
200− if (nop==0) return; /* cannot improve code */
252+ if (NoDebug(tf)==0) return; /* cannot improve code */
201253 FixJumps(tf);
202254 PackCode(tf);
203255 }
@@ -216,13 +268,14 @@ static void OptFunctions(TProtoFunc* tf) · 12 unmodified lines
216268
217269 static void OptFunction(TProtoFunc* tf)
218270 {
219− tf->locvars=NULL; /* remove local variables table */
220271 OptConstants(tf);
221272 OptCode(tf);
222273 OptFunctions(tf);
274+ tf->source=luaS_new("");
275+ tf->locvars=NULL;
223276 }
224277
225−void OptChunk(TProtoFunc* Main)
278+void luaU_optchunk(TProtoFunc* Main)
226279 {
227280 OptFunction(Main);
228281 }
src/luac/print.c+86−96
@@ -1,5 +1,5 @@
11 /*
2−** $Id: print.c,v 1.13 1998/07/12 00:17:37 lhf Exp $
2+** $Id: print.c,v 1.21 1999/05/25 19:58:55 lhf Exp $
33 ** print bytecodes
44 ** See Copyright Notice in lua.h
55 */
@@ -9,88 +9,81 @@ · 3 unmodified lines
99 #include "luac.h"
1010
1111 #ifdef DEBUG
12−void PrintConstant1(TProtoFunc* tf, int i)
13−{
14− TObject* o=tf->consts+i;
15− printf("%6d ",i);
16− if (i<0 || i>=tf->nconsts)
17− printf("(bad constant #%d: max=%d)",i,tf->nconsts);
18− else
19− switch (ttype(o))
20− {
21− case LUA_T_NUMBER:
22− printf("N " NUMBER_FMT "\n",nvalue(o)); /* LUA_NUMBER */
23− break;
24− case LUA_T_STRING:
25− printf("S %p\t\"%s\"\n",(void*)tsvalue(o),svalue(o));
26− break;
27− case LUA_T_PROTO:
28− printf("F %p\n",(void*)tfvalue(o));
29− break;
30− default: /* cannot happen */
31− printf("? %d\n",ttype(o));
32− break;
33− }
34−}
35−
3612 static void PrintConstants(TProtoFunc* tf)
3713 {
3814 int i,n=tf->nconsts;
39− printf("constants (%d):\n",n);
40− for (i=0; i<n; i++) PrintConstant1(tf,i);
41−}
42−#endif
43−
44−static void PrintConstant(TProtoFunc* tf, int i)
45−{
46− if (i<0 || i>=tf->nconsts)
47− printf("(bad constant #%d: max=%d)",i,tf->nconsts);
48− else
15+ printf("constants (%d) for %p:\n",n,tf);
16+ for (i=0; i<n; i++)
4917 {
5018 TObject* o=tf->consts+i;
19+ printf("%6d ",i);
5120 switch (ttype(o))
5221 {
5322 case LUA_T_NUMBER:
54− printf(NUMBER_FMT,nvalue(o)); /* LUA_NUMBER */
23+ printf("N " NUMBER_FMT "\n",(double)nvalue(o));
5524 break;
5625 case LUA_T_STRING:
57− printf("\"%s\"",svalue(o));
26+ printf("S %p\t\"%s\"\n",tsvalue(o),svalue(o));
5827 break;
5928 case LUA_T_PROTO:
60− printf("function at %p",(void*)tfvalue(o));
29+ printf("F %p\n",tfvalue(o));
6130 break;
6231 case LUA_T_NIL:
63− printf("(nil)");
32+ printf("nil\n");
6433 break;
6534 default: /* cannot happen */
66− printf("(bad constant #%d: type=%d [%s])\n",i,ttype(o),luaO_typename(o));
35+ printf("? type=%d\n",ttype(o));
6736 break;
6837 }
6938 }
7039 }
40+#endif
7141
72−#define VarStr(i) svalue(tf->consts+i)
42+static void PrintConstant(TProtoFunc* tf, int i, int at)
43+{
44+ TObject* o=luaU_getconstant(tf,i,at);
45+ switch (ttype(o))
46+ {
47+ case LUA_T_NUMBER:
48+ printf(NUMBER_FMT,(double)nvalue(o));
49+ break;
50+ case LUA_T_STRING:
51+ printf("\"%s\"",svalue(o));
52+ break;
53+ case LUA_T_PROTO:
54+ printf("function at %p",(void*)tfvalue(o));
55+ break;
56+ case LUA_T_NIL:
57+ printf("(nil)");
58+ break;
59+ default: /* cannot happen */
60+ luaU_badconstant("print",i,o,tf);
61+ break;
62+ }
63+}
7364
7465 static void PrintCode(TProtoFunc* tf)
7566 {
7667 Byte* code=tf->code;
7768 Byte* p=code;
7869 int line=0;
79− while (1)
70+ int longarg=0;
71+ for (;;)
8072 {
8173 Opcode OP;
8274 int n=INFO(tf,p,&OP);
83− int op=OP.op;
84− int i=OP.arg;
85− printf("%6d ",(int)(p-code));
75+ int i=OP.arg+longarg;
76+ int at=p-code;
77+ longarg=0;
78+ printf("%6d ",at);
8679 {
8780 Byte* q=p;
8881 int j=n;
8982 while (j--) printf("%02X",*q++);
9083 }
91− printf("%*s%-13s",2*(5-n),"",OP.name);
92−
93− if (n!=1 || op<0) printf("\t%d",i); else if (i>=0) printf("\t");
84+ printf("%*s%-14s ",2*(5-n),"",OP.name);
85+ if (OP.arg >=0) printf("%d",i);
86+ if (OP.arg2>=0) printf(" %d",OP.arg2);
9487
9588 switch (OP.class)
9689 {
@@ -99,13 +92,14 @@ static void PrintCode(TProtoFunc* tf) · 2 unmodified lines
9992 printf("\n");
10093 return;
10194
102− case CLOSURE:
103− printf(" %d",OP.arg2);
10495 case PUSHCONSTANT:
96+ case GETGLOBAL:
97+ case SETGLOBAL:
10598 case GETDOTTED:
10699 case PUSHSELF:
100+ case CLOSURE:
107101 printf("\t; ");
108− PrintConstant(tf,i);
102+ PrintConstant(tf,i,at);
109103 break;
110104
111105 case PUSHLOCAL:
@@ -116,29 +110,24 @@ static void PrintCode(TProtoFunc* tf) · 4 unmodified lines
116110 break;
117111 }
118112
119− case GETGLOBAL:
120− case SETGLOBAL:
121− printf("\t; %s",VarStr(i));
122− break;
123−
124− case SETLIST:
125− case CALLFUNC:
126− if (n>=3) printf(" %d",OP.arg2);
113+ case SETLINE:
114+ printf("\t; " SOURCE,tf->source->str,line=i);
127115 break;
128116
129− case SETLINE:
130− printf("\t; \"%s\":%d",fileName(tf),line=i);
117+ case LONGARG:
118+ longarg=i<<16;
131119 break;
132120
133121 /* suggested by Norman Ramsey <nr@cs.virginia.edu> */
134− case IFTUPJMP:
135− case IFFUPJMP:
136− i=-i;
137122 case ONTJMP:
138123 case ONFJMP:
139124 case JMP:
140125 case IFFJMP:
141− printf("\t; to %d",(int)(p-code)+i+n);
126+ printf("\t; to %d",at+i+n);
127+ break;
128+ case IFTUPJMP:
129+ case IFFUPJMP:
130+ printf("\t; to %d",at-i+n);
142131 break;
143132
144133 }
@@ -150,47 +139,44 @@ static void PrintCode(TProtoFunc* tf) · 5 unmodified lines
150139 static void PrintLocals(TProtoFunc* tf)
151140 {
152141 LocVar* v=tf->locvars;
153− int n,i=0;
154− if (v==NULL || v->varname==NULL) return;
142+ int n,i;
143+ if (v==NULL || v->line<0) return;
155144 n=tf->code[1]; if (n>=ZEROVARARG) n-=ZEROVARARG;
156−
157145 printf("locals:");
158− if (n>0)
159− {
160− for (i=0; i<n; v++,i++) printf(" %s",v->varname->str);
161− }
162− if (v->varname!=NULL)
146+ for (i=0; i<n; v++,i++) /* arguments */
147+ printf(" %s",v->varname->str);
148+ for (; v->line>=0; v++)
163149 {
164− for (; v->line>=0; v++)
150+ if (v->varname==NULL)
165151 {
166− if (v->varname==NULL)
167− {
168− printf(")"); --i;
169− }
170− else
171− {
172− printf(" (%s",v->varname->str); i++;
173− }
152+ --i; if (i<0) luaL_verror("bad locvars[%d]",v-tf->locvars); else printf(")");
153+ }
154+ else
155+ {
156+ ++i; printf(" (%s",v->varname->str);
174157 }
175− i-=n;
176− while (i--) printf(")");
177158 }
159+ i-=n;
160+ while (i--) printf(")");
178161 printf("\n");
179162 }
180163
164+#define IsMain(tf) (tf->lineDefined==0)
165+
181166 static void PrintHeader(TProtoFunc* tf, TProtoFunc* Main, int at)
182167 {
183− int size=CodeSize(tf);
168+ int size=luaU_codesize(tf);
184169 if (IsMain(tf))
185− printf("\nmain of \"%s\" (%d bytes at %p)\n",fileName(tf),size,(void*)tf);
186− else if (Main)
170+ printf("\nmain " SOURCE " (%d bytes at %p)\n",
171+ tf->source->str,tf->lineDefined,size,tf);
172+ else
187173 {
188− printf("\nfunction defined at \"%s\":%d (%d bytes at %p); used at ",
189− fileName(tf),tf->lineDefined,size,(void*)tf);
190− if (IsMain(Main))
174+ printf("\nfunction " SOURCE " (%d bytes at %p); used at ",
175+ tf->source->str,tf->lineDefined,size,tf);
176+ if (Main && IsMain(Main))
191177 printf("main");
192178 else
193− printf("%p",(void*)Main);
179+ printf("%p",Main);
194180 printf("+%d\n",at);
195181 }
196182 }
@@ -201,17 +187,21 @@ static void PrintFunctions(TProtoFunc* Main) · 4 unmodified lines
201187 {
202188 Byte* code=Main->code;
203189 Byte* p=code;
204− while (1)
190+ int longarg=0;
191+ for (;;)
205192 {
206193 Opcode OP;
207194 int n=INFO(Main,p,&OP);
208− if (OP.class==ENDCODE) break;
209− if (OP.class==PUSHCONSTANT || OP.class==CLOSURE)
195+ int op=OP.class;
196+ int i=OP.arg+longarg;
197+ longarg=0;
198+ if (op==PUSHCONSTANT || op==CLOSURE)
210199 {
211− int i=OP.arg;
212200 TObject* o=Main->consts+i;
213201 if (ttype(o)==LUA_T_PROTO) PrintFunction(tfvalue(o),Main,(int)(p-code));
214202 }
203+ else if (op==LONGARG) longarg=i<<16;
204+ else if (op==ENDCODE) break;
215205 p+=n;
216206 }
217207 }
@@ -227,7 +217,7 @@ static void PrintFunction(TProtoFunc* tf, TProtoFunc* Main, int at) · 9 unmodified lines
227217 PrintFunctions(tf);
228218 }
229219
230−void PrintChunk(TProtoFunc* Main)
220+void luaU_printchunk(TProtoFunc* Main)
231221 {
232222 PrintFunction(Main,0,0);
233223 }
src/luac/stubs.c+72−19
@@ -1,9 +1,17 @@
11 /*
2−** $Id: stubs.c,v 1.8 1998/07/12 00:17:37 lhf Exp $
2+** $Id: stubs.c,v 1.11 1999/03/11 17:09:10 lhf Exp $
33 ** avoid runtime modules in luac
44 ** See Copyright Notice in lua.h
55 */
66
7+#ifdef NOSTUBS
8+
9+/* according to gcc, ANSI C forbids an empty source file */
10+void luaU_dummy(void);
11+void luaU_dummy(void){}
12+
13+#else
14+
715 #include <stdarg.h>
816 #include <stdio.h>
917 #include <stdlib.h>
@@ -22,32 +30,34 @@ void lua_error(char* s) · 12 unmodified lines
2230 }
2331
2432 /* copied from lauxlib.c */
25−void luaL_verror(char* fmt, ...)
33+void luaL_verror (char *fmt, ...)
2634 {
27− char buff[500];
28− va_list argp;
29− va_start(argp,fmt);
30− vsprintf(buff,fmt,argp);
31− va_end(argp);
32− lua_error(buff);
35+ char buff[500];
36+ va_list argp;
37+ va_start(argp, fmt);
38+ vsprintf(buff, fmt, argp);
39+ va_end(argp);
40+ lua_error(buff);
3341 }
3442
3543 /* copied from lauxlib.c */
36−int luaL_findstring (char* name, char* list[])
37−{
38− int i;
39− for (i=0; list[i]; i++)
40− if (strcmp(list[i], name) == 0)
41− return i;
42− return -1;
44+void luaL_filesource (char *out, char *filename, int len) {
45+ if (filename == NULL) filename = "(stdin)";
46+ sprintf(out, "@%.*s", len-2, filename); /* -2 for '@' and '\0' */
4347 }
4448
4549 /* avoid runtime modules in lstate.c */
50+
51+#include "lbuiltin.h"
52+#include "ldo.h"
53+#include "lgc.h"
54+#include "ltable.h"
55+#include "ltm.h"
56+
4657 void luaB_predefine(void){}
4758 void luaC_hashcallIM(Hash *l){}
4859 void luaC_strcallIM(TaggedString *l){}
4960 void luaD_gcIM(TObject *o){}
50−void luaD_init(void){}
5161 void luaH_free(Hash *frees){}
5262 void luaT_init(void){}
5363
@@ -59,10 +69,53 @@ void luaT_init(void){} · 5 unmodified lines
5969
6070 #ifdef NOPARSER
6171
62−int lua_debug=0;
72+#include "llex.h"
73+#include "lparser.h"
6374
6475 void luaX_init(void){}
65−void luaY_init(void){}
66−void luaY_parser(void) { lua_error("parser not loaded"); }
76+void luaD_init(void){}
77+
78+TProtoFunc* luaY_parser(ZIO *z) {
79+ lua_error("parser not loaded");
80+ return NULL;
81+}
82+
83+#else
6784
85+/* copied from lauxlib.c */
86+int luaL_findstring (char *name, char *list[]) {
87+ int i;
88+ for (i=0; list[i]; i++)
89+ if (strcmp(list[i], name) == 0)
90+ return i;
91+ return -1; /* name not found */
92+}
93+
94+/* copied from lauxlib.c */
95+void luaL_chunkid (char *out, char *source, int len) {
96+ len -= 13; /* 13 = strlen("string ''...\0") */
97+ if (*source == '@')
98+ sprintf(out, "file `%.*s'", len, source+1);
99+ else if (*source == '(')
100+ strcpy(out, "(C code)");
101+ else {
102+ char *b = strchr(source , '\n'); /* stop string at first new line */
103+ int lim = (b && (b-source)<len) ? b-source : len;
104+ sprintf(out, "string `%.*s'", lim, source);
105+ strcpy(out+lim+(13-5), "...'"); /* 5 = strlen("...'\0") */
106+ }
107+}
108+
109+void luaD_checkstack(int n){}
110+
111+#define STACK_UNIT 128
112+
113+/* copied from ldo.c */
114+void luaD_init (void) {
115+ L->stack.stack = luaM_newvector(STACK_UNIT, TObject);
116+ L->stack.top = L->stack.stack;
117+ L->stack.last = L->stack.stack+(STACK_UNIT-1);
118+}
119+
120+#endif
68121 #endif
src/luac/test.c+253−0
@@ -0,0 +1,253 @@
1+/*
2+** $Id: test.c,v 1.10 1999/07/02 19:34:26 lhf Exp $
3+** test integrity
4+** See Copyright Notice in lua.h
5+*/
6+
7+#include <stdio.h>
8+#include <stdlib.h>
9+#include <string.h>
10+#include "luac.h"
11+
12+#define AT "pc=%d"
13+#define ATLOC 0)
14+#define UNSAFE(s) \
15+ luaL_verror("unsafe code at " AT IN "\n " s,at,INLOC
16+
17+TObject* luaU_getconstant(TProtoFunc* tf, int i, int at)
18+{
19+ if (i>=tf->nconsts) UNSAFE("bad constant #%d (max=%d)"),i,tf->nconsts-1,ATLOC;
20+ return tf->consts+i;
21+}
22+
23+static int check(int n, TProtoFunc* tf, int at, int sp, int ss)
24+{
25+ if (n==0) return sp;
26+ sp+=n;
27+ if (sp<00) UNSAFE("stack underflow (sp=%d)"),sp,ATLOC;
28+ if (sp>ss) UNSAFE("stack overflow (sp=%d ss=%d)"),sp,ss,ATLOC;
29+ return sp;
30+}
31+
32+#define CHECK(before,after) \
33+ sp=check(-(before),tf,at,sp,ss), sp=check(after,tf,at,sp,ss)
34+
35+static int jmpok(TProtoFunc* tf, int size, int at, int d)
36+{
37+ int to=at+d;
38+ if (to<2 || to>=size)
39+ UNSAFE("invalid jump to %d (valid range is 2..%d)"),to,size-1,ATLOC;
40+ return to;
41+}
42+
43+static void TestStack(TProtoFunc* tf, int size, int* SP, int* JP)
44+{
45+ Byte* code=tf->code;
46+ Byte* p=code;
47+ int longarg=0;
48+ int ss=0;
49+ int sp=0;
50+ for (;;)
51+ {
52+ Opcode OP;
53+ int n=INFO(tf,p,&OP);
54+ int op=OP.class;
55+ int i=OP.arg+longarg;
56+ int at=p-code;
57+ longarg=0;
58+ switch (op) /* test sanity of operands */
59+ {
60+ case PUSHCONSTANT:
61+ case GETGLOBAL:
62+ case GETDOTTED:
63+ case PUSHSELF:
64+ case SETGLOBAL:
65+ case CLOSURE:
66+ {
67+ TObject* o=luaU_getconstant(tf,i,at);
68+ if ((op==CLOSURE && ttype(o)!=LUA_T_PROTO)
69+ || (op==GETGLOBAL && ttype(o)!=LUA_T_STRING)
70+ || (op==SETGLOBAL && ttype(o)!=LUA_T_STRING))
71+ UNSAFE("bad operand to %s"),OP.name,ATLOC;
72+ break;
73+ }
74+ case PUSHLOCAL:
75+ if (i>=sp) UNSAFE("bad local #%d (max=%d)"),i,sp-1,ATLOC;
76+ break;
77+ case SETLOCAL:
78+ if (i>=(sp-1)) UNSAFE("bad local #%d (max=%d)"),i,sp-2,ATLOC;
79+ break;
80+ case ONTJMP:
81+ case ONFJMP: /* negate to remember ON?JMP */
82+ JP[at]=-jmpok(tf,size,at,i+n);
83+ break;
84+ case JMP: /* remember JMP targets */
85+ case IFFJMP:
86+ JP[at]= jmpok(tf,size,at,i+n);
87+ break;
88+ case IFTUPJMP:
89+ case IFFUPJMP:
90+ JP[at]= jmpok(tf,size,at,-i+n);
91+ break;
92+ }
93+
94+ SP[at]=sp; /* remember depth before instruction */
95+
96+ switch (op)
97+ {
98+ case STACK: ss=i; break;
99+ case ARGS: CHECK(0,i); break;
100+ case VARARGS: break;
101+ case ENDCODE: return;
102+ case RETCODE: CHECK(i,0); sp=i; break;
103+ case CALL: CHECK(OP.arg2+1,i); break;
104+ case TAILCALL: CHECK(OP.arg2,0); sp=i; break;
105+ case PUSHNIL: CHECK(0,i+1); break;
106+ case POP: CHECK(0,-i); break;
107+ case PUSHNUMBER:
108+ case PUSHNUMBERNEG:
109+ case PUSHCONSTANT:
110+ case PUSHUPVALUE:
111+ case PUSHLOCAL:
112+ case GETGLOBAL: CHECK(0,1); break;
113+ case GETTABLE: CHECK(2,1); break;
114+ case GETDOTTED: CHECK(1,1); break;
115+ case PUSHSELF: CHECK(1,2); break;
116+ case CREATEARRAY: CHECK(0,1); break;
117+ case SETLOCAL: CHECK(1,0); break;
118+ case SETGLOBAL: CHECK(1,0); break;
119+ case SETTABLEPOP: CHECK(3,0); break;
120+ case SETTABLE: CHECK(i+3,i+2); break;
121+ case SETLIST: CHECK(OP.arg2+1,1); break;
122+ case SETMAP: CHECK(2*(i+1)+1,1); break;
123+ case NEQOP:
124+ case EQOP:
125+ case LTOP:
126+ case LEOP:
127+ case GTOP:
128+ case GEOP:
129+ case ADDOP:
130+ case SUBOP:
131+ case MULTOP:
132+ case DIVOP:
133+ case POWOP:
134+ case CONCOP: CHECK(2,1); break;
135+ case MINUSOP:
136+ case NOTOP: CHECK(1,1); break;
137+ case ONTJMP:
138+ case ONFJMP:
139+ case IFFJMP:
140+ case IFTUPJMP:
141+ case IFFUPJMP: CHECK(1,0); break;
142+ case JMP: break;
143+ case CLOSURE: CHECK(OP.arg2,1); break;
144+ case SETLINE: break;
145+ case LONGARG:
146+ longarg=i<<16;
147+ if (longarg<0) UNSAFE("longarg overflow"),ATLOC;
148+ break;
149+ case CHECKSTACK: break;
150+ default: /* cannot happen */
151+ UNSAFE("cannot test opcode %d [%s]"),OP.op,OP.name,ATLOC;
152+ break;
153+ }
154+ p+=n;
155+ }
156+}
157+
158+static void TestJumps(TProtoFunc* tf, int size, int* SP, int* JP)
159+{
160+ int i;
161+ for (i=0; i<size; i++)
162+ {
163+ int to=JP[i];
164+ if (to!=0)
165+ {
166+ int at=i; /* for ATLOC */
167+ int a,b,j;
168+ int on=(to<0); /* ON?JMP */
169+ if (on) to=-to;
170+ a=SP[to];
171+ if (a<0)
172+ UNSAFE("invalid jump to %d (not an instruction)"),to,ATLOC;
173+ for (j=i; SP[++j]<0; ) /* find next instruction */
174+ ;
175+ b=SP[j]+on;
176+ if (a!=b)
177+ UNSAFE("stack inconsistency in jump to %d (expected %d, found %d)"),
178+ to,a,b,ATLOC;
179+ }
180+ }
181+}
182+
183+static void TestCode(TProtoFunc* tf)
184+{
185+ static int* SP=NULL;
186+ static int* JP=NULL;
187+ int size=luaU_codesize(tf);
188+ luaM_reallocvector(SP,size,int); memset(SP,-1,size*sizeof(int));
189+ luaM_reallocvector(JP,size,int); memset(JP, 0,size*sizeof(int));
190+ TestStack(tf,size,SP,JP);
191+ TestJumps(tf,size,SP,JP);
192+}
193+
194+#undef AT
195+#define AT "locvars[%d]"
196+static void TestLocals(TProtoFunc* tf)
197+{
198+ LocVar* v;
199+ int l=1;
200+ int d=0;
201+ if (tf->locvars==NULL) return;
202+ for (v=tf->locvars; v->line>=0; v++)
203+ {
204+ int at=v-tf->locvars; /* for ATLOC */
205+ if (l>v->line)
206+ UNSAFE("bad line number %d; expected at least %d"),v->line,l,ATLOC;
207+ l=v->line;
208+ if (v->varname==NULL)
209+ {
210+ if (--d<0) UNSAFE("no scope to close"),ATLOC;
211+ }
212+ else
213+ ++d;
214+ }
215+}
216+
217+static void TestFunction(TProtoFunc* tf);
218+
219+static void TestConstants(TProtoFunc* tf)
220+{
221+ int i,n=tf->nconsts;
222+ for (i=0; i<n; i++)
223+ {
224+ TObject* o=tf->consts+i;
225+ switch (ttype(o))
226+ {
227+ case LUA_T_NUMBER:
228+ break;
229+ case LUA_T_STRING:
230+ break;
231+ case LUA_T_PROTO:
232+ TestFunction(tfvalue(o));
233+ break;
234+ case LUA_T_NIL:
235+ break;
236+ default: /* cannot happen */
237+ luaU_badconstant("print",i,o,tf);
238+ break;
239+ }
240+ }
241+}
242+
243+static void TestFunction(TProtoFunc* tf)
244+{
245+ TestCode(tf);
246+ TestLocals(tf);
247+ TestConstants(tf);
248+}
249+
250+void luaU_testchunk(TProtoFunc* Main)
251+{
252+ TestFunction(Main);
253+}
src/lundump.c+91−80
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lundump.c,v 1.12 1998/07/12 01:46:59 lhf Exp $
2+** $Id: lundump.c,v 1.21 1999/07/02 19:34:26 lhf Exp $
33 ** load bytecodes from files
44 ** See Copyright Notice in lua.h
55 */
@@ -9,99 +9,96 @@ · 3 unmodified lines
99 #include "lauxlib.h"
1010 #include "lfunc.h"
1111 #include "lmem.h"
12+#include "lopcodes.h"
1213 #include "lstring.h"
1314 #include "lundump.h"
1415
1516 #define LoadBlock(b,size,Z) ezread(Z,b,size)
16−#define LoadNative(t,Z) LoadBlock(&t,sizeof(t),Z)
1717
18−#if ID_NUMBER==ID_NATIVE
19− #define doLoadNumber(f,Z) LoadNative(f,Z)
20−#else
21− #define doLoadNumber(f,Z) f=LoadNumber(Z)
22−#endif
23−
24−static void unexpectedEOZ(ZIO* Z)
18+static void unexpectedEOZ (ZIO* Z)
2519 {
2620 luaL_verror("unexpected end of file in %s",zname(Z));
2721 }
2822
29−static int ezgetc(ZIO* Z)
23+static int ezgetc (ZIO* Z)
3024 {
3125 int c=zgetc(Z);
3226 if (c==EOZ) unexpectedEOZ(Z);
3327 return c;
3428 }
3529
36−static void ezread(ZIO* Z, void* b, int n)
30+static void ezread (ZIO* Z, void* b, int n)
3731 {
3832 int r=zread(Z,b,n);
3933 if (r!=0) unexpectedEOZ(Z);
4034 }
4135
42−static unsigned int LoadWord(ZIO* Z)
36+static unsigned int LoadWord (ZIO* Z)
4337 {
4438 unsigned int hi=ezgetc(Z);
4539 unsigned int lo=ezgetc(Z);
4640 return (hi<<8)|lo;
4741 }
4842
49−static unsigned long LoadLong(ZIO* Z)
43+static unsigned long LoadLong (ZIO* Z)
5044 {
5145 unsigned long hi=LoadWord(Z);
5246 unsigned long lo=LoadWord(Z);
5347 return (hi<<16)|lo;
5448 }
5549
56−#if ID_NUMBER==ID_REAL4
57−/* LUA_NUMBER */
58−/* assumes sizeof(long)==4 and sizeof(float)==4 (IEEE) */
59−static float LoadFloat(ZIO* Z)
50+/*
51+* convert number from text
52+*/
53+double luaU_str2d (char* b, char* where)
6054 {
61− unsigned long l=LoadLong(Z);
62− float f;
63− memcpy(&f,&l,sizeof(f));
64− return f;
55+ int negative=(b[0]=='-');
56+ double x=luaO_str2d(b+negative);
57+ if (x<0) luaL_verror("cannot convert number '%s' in %s",b,where);
58+ return negative ? -x : x;
6559 }
66−#endif
6760
68−#if ID_NUMBER==ID_REAL8
69−/* LUA_NUMBER */
70−/* assumes sizeof(long)==4 and sizeof(double)==8 (IEEE) */
71−static double LoadDouble(ZIO* Z)
61+static real LoadNumber (ZIO* Z, int native)
7262 {
73− unsigned long l[2];
74− double f;
75− int x=1;
76− if (*(char*)&x==1) /* little-endian */
63+ real x;
64+ if (native)
7765 {
78− l[1]=LoadLong(Z);
79− l[0]=LoadLong(Z);
66+ LoadBlock(&x,sizeof(x),Z);
67+ return x;
8068 }
81− else /* big-endian */
69+ else
8270 {
83− l[0]=LoadLong(Z);
84− l[1]=LoadLong(Z);
71+ char b[256];
72+ int size=ezgetc(Z);
73+ LoadBlock(b,size,Z);
74+ b[size]=0;
75+ return luaU_str2d(b,zname(Z));
8576 }
86− memcpy(&f,l,sizeof(f));
87− return f;
8877 }
89−#endif
9078
91−static Byte* LoadCode(ZIO* Z)
79+static int LoadInt (ZIO* Z, char* message)
9280 {
93− unsigned long size=LoadLong(Z);
94− unsigned int s=size;
95− void* b;
96− if (s!=size) luaL_verror("code too long (%ld bytes) in %s",size,zname(Z));
97− b=luaM_malloc(size);
81+ unsigned long l=LoadLong(Z);
82+ unsigned int i=l;
83+ if (i!=l) luaL_verror(message,l,zname(Z));
84+ return i;
85+}
86+
87+#define PAD 5 /* two word operands plus opcode */
88+
89+static Byte* LoadCode (ZIO* Z)
90+{
91+ int size=LoadInt(Z,"code too long (%ld bytes) in %s");
92+ Byte* b=luaM_malloc(size+PAD);
9893 LoadBlock(b,size,Z);
94+ if (b[size-1]!=ENDCODE) luaL_verror("bad code in %s",zname(Z));
95+ memset(b+size,ENDCODE,PAD); /* pad code for safety */
9996 return b;
10097 }
10198
102−static TaggedString* LoadTString(ZIO* Z)
99+static TaggedString* LoadTString (ZIO* Z)
103100 {
104− int size=LoadWord(Z);
101+ long size=LoadLong(Z);
105102 if (size==0)
106103 return NULL;
107104 else
@@ -112,65 +109,65 @@ static TaggedString* LoadTString(ZIO* Z) · 4 unmodified lines
112109 }
113110 }
114111
115−static void LoadLocals(TProtoFunc* tf, ZIO* Z)
112+static void LoadLocals (TProtoFunc* tf, ZIO* Z)
116113 {
117− int i,n=LoadWord(Z);
114+ int i,n=LoadInt(Z,"too many locals (%ld) in %s");
118115 if (n==0) return;
119116 tf->locvars=luaM_newvector(n+1,LocVar);
120117 for (i=0; i<n; i++)
121118 {
122− tf->locvars[i].line=LoadWord(Z);
119+ tf->locvars[i].line=LoadInt(Z,"too many lines (%ld) in %s");
123120 tf->locvars[i].varname=LoadTString(Z);
124121 }
125122 tf->locvars[i].line=-1; /* flag end of vector */
126123 tf->locvars[i].varname=NULL;
127124 }
128125
129−static TProtoFunc* LoadFunction(ZIO* Z);
126+static TProtoFunc* LoadFunction (ZIO* Z, int native);
130127
131−static void LoadConstants(TProtoFunc* tf, ZIO* Z)
128+static void LoadConstants (TProtoFunc* tf, ZIO* Z, int native)
132129 {
133− int i,n=LoadWord(Z);
130+ int i,n=LoadInt(Z,"too many constants (%ld) in %s");
134131 tf->nconsts=n;
135132 if (n==0) return;
136133 tf->consts=luaM_newvector(n,TObject);
137134 for (i=0; i<n; i++)
138135 {
139136 TObject* o=tf->consts+i;
140− ttype(o)=-ezgetc(Z);
137+ ttype(o)=-ezgetc(Z); /* ttype(o) is negative - ORDER LUA_T */
141138 switch (ttype(o))
142139 {
143140 case LUA_T_NUMBER:
144− doLoadNumber(nvalue(o),Z);
141+ nvalue(o)=LoadNumber(Z,native);
145142 break;
146143 case LUA_T_STRING:
147144 tsvalue(o)=LoadTString(Z);
148145 break;
149146 case LUA_T_PROTO:
150− tfvalue(o)=LoadFunction(Z);
147+ tfvalue(o)=LoadFunction(Z,native);
151148 break;
152149 case LUA_T_NIL:
153150 break;
154− default:
155− luaL_verror("bad constant #%d in %s: type=%d [%s]",
156− i,zname(Z),ttype(o),luaO_typename(o));
151+ default: /* cannot happen */
152+ luaU_badconstant("load",i,o,tf);
157153 break;
158154 }
159155 }
160156 }
161157
162−static TProtoFunc* LoadFunction(ZIO* Z)
158+static TProtoFunc* LoadFunction (ZIO* Z, int native)
163159 {
164160 TProtoFunc* tf=luaF_newproto();
165− tf->lineDefined=LoadWord(Z);
166− tf->fileName=LoadTString(Z);
161+ tf->lineDefined=LoadInt(Z,"lineDefined too large (%ld) in %s");
162+ tf->source=LoadTString(Z);
163+ if (tf->source==NULL) tf->source=luaS_new(zname(Z));
167164 tf->code=LoadCode(Z);
168165 LoadLocals(tf,Z);
169− LoadConstants(tf,Z);
166+ LoadConstants(tf,Z,native);
170167 return tf;
171168 }
172169
173−static void LoadSignature(ZIO* Z)
170+static void LoadSignature (ZIO* Z)
174171 {
175172 char* s=SIGNATURE;
176173 while (*s!=0 && ezgetc(Z)==*s)
@@ -178,10 +175,10 @@ static void LoadSignature(ZIO* Z) · 1 unmodified line
178175 if (*s!=0) luaL_verror("bad signature in %s",zname(Z));
179176 }
180177
181−static void LoadHeader(ZIO* Z)
178+static int LoadHeader (ZIO* Z)
182179 {
183− int version,id,sizeofR;
184− real f=-TEST_NUMBER,tf=TEST_NUMBER;
180+ int version,sizeofR;
181+ int native;
185182 LoadSignature(Z);
186183 version=ezgetc(Z);
187184 if (version>VERSION)
@@ -192,32 +189,36 @@ static void LoadHeader(ZIO* Z) · 4 unmodified lines
192189 luaL_verror(
193190 "%s too old: version=0x%02x; expected at least 0x%02x",
194191 zname(Z),version,VERSION0);
195− id=ezgetc(Z); /* test number representation */
196192 sizeofR=ezgetc(Z);
197− if (id!=ID_NUMBER || sizeofR!=sizeof(real))
193+ native=(sizeofR!=0);
194+ if (native) /* test number representation */
198195 {
199− luaL_verror("unknown number signature in %s: "
200− "read 0x%02x%02x; expected 0x%02x%02x",
201− zname(Z),id,sizeofR,ID_NUMBER,sizeof(real));
196+ if (sizeofR!=sizeof(real))
197+ luaL_verror("unknown number size in %s: read %d; expected %d",
198+ zname(Z),sizeofR,sizeof(real));
199+ else
200+ {
201+ real tf=TEST_NUMBER;
202+ real f=LoadNumber(Z,native);
203+ if ((long)f!=(long)tf)
204+ luaL_verror("unknown number format in %s: "
205+ "read " NUMBER_FMT "; expected " NUMBER_FMT,
206+ zname(Z),f,tf);
207+ }
202208 }
203− doLoadNumber(f,Z);
204− if (f!=tf)
205− luaL_verror("unknown number representation in %s: "
206− "read " NUMBER_FMT "; expected " NUMBER_FMT, /* LUA_NUMBER */
207− zname(Z),f,tf);
209+ return native;
208210 }
209211
210−static TProtoFunc* LoadChunk(ZIO* Z)
212+static TProtoFunc* LoadChunk (ZIO* Z)
211213 {
212− LoadHeader(Z);
213− return LoadFunction(Z);
214+ return LoadFunction(Z,LoadHeader(Z));
214215 }
215216
216217 /*
217218 ** load one chunk from a file or buffer
218219 ** return main if ok and NULL at EOF
219220 */
220−TProtoFunc* luaU_undump1(ZIO* Z)
221+TProtoFunc* luaU_undump1 (ZIO* Z)
221222 {
222223 int c=zgetc(Z);
223224 if (c==ID_CHUNK)
@@ -226,3 +227,13 @@ TProtoFunc* luaU_undump1(ZIO* Z) · 2 unmodified lines
226227 luaL_verror("%s is not a Lua binary file",zname(Z));
227228 return NULL;
228229 }
230+
231+/*
232+* handle constants that cannot happen
233+*/
234+void luaU_badconstant (char* s, int i, TObject* o, TProtoFunc* tf)
235+{
236+ int t=ttype(o);
237+ char* name= (t>0 || t<LUA_T_LINE) ? "?" : luaO_typenames[-t];
238+ luaL_verror("cannot %s constant #%d: type=%d [%s]" IN,s,i,t,name,INLOC);
239+}
src/lundump.h+24−63
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lundump.h,v 1.9 1998/07/12 00:17:37 lhf Exp $
2+** $Id: lundump.h,v 1.15 1999/07/02 19:34:26 lhf Exp $
33 ** load pre-compiled Lua chunks
44 ** See Copyright Notice in lua.h
55 */
@@ -10,69 +10,30 @@ · 4 unmodified lines
1010 #include "lobject.h"
1111 #include "lzio.h"
1212
13−TProtoFunc* luaU_undump1(ZIO* Z); /* load one chunk */
14−
15−#define SIGNATURE "Lua"
16−#define VERSION 0x31 /* last format change was in 3.1 */
17−#define VERSION0 0x31 /* last major change was in 3.1 */
18−#define ID_CHUNK 27 /* ESC */
19−
20−#define IsMain(f) (f->lineDefined==0)
21−#define luaO_typename(o) luaO_typenames[-ttype(o)]
22−
23−/* number representation */
24−#define ID_INT4 'l' /* 4-byte integers */
25−#define ID_REAL4 'f' /* 4-byte reals */
26−#define ID_REAL8 'd' /* 8-byte reals */
27−#define ID_NATIVE '?' /* whatever your machine uses */
28−
29−/*
30−* use a multiple of PI for testing number representation.
31−* multiplying by 1E8 gives notrivial integer values.
32−*/
33−#define TEST_NUMBER 3.14159265358979323846E8
34−
35−/* LUA_NUMBER
36−* choose one below for the number representation in precompiled chunks.
37−* the default is ID_REAL8 because the default for LUA_NUM_TYPE is double.
38−* if your machine does not use IEEE 754, use ID_NATIVE.
39−* the next version will support conversion to/from IEEE 754.
40−*
41−* if you change LUA_NUM_TYPE, make sure you set ID_NUMBER accordingly,
42−* specially if sizeof(long)!=4.
43−* for types other than the ones listed below, you'll have to write your own
44−* dump and undump routines.
45−*/
46−
47−#ifndef ID_NUMBER
48−#define ID_NUMBER ID_REAL8
13+TProtoFunc* luaU_undump1 (ZIO* Z); /* load one chunk */
14+void luaU_badconstant (char* s, int i, TObject* o, TProtoFunc* tf);
15+ /* handle cases that cannot happen */
16+double luaU_str2d (char* b, char* where);
17+ /* convert number from text */
18+
19+/* definitions for headers of binary files */
20+#define VERSION 0x32 /* last format change was in 3.2 */
21+#define VERSION0 0x32 /* last major change was in 3.2 */
22+#define ID_CHUNK 27 /* binary files start with ESC... */
23+#define SIGNATURE "Lua" /* ...followed by this signature */
24+
25+/* formats for error messages */
26+#define SOURCE "<%s:%d>"
27+#define IN " in %p " SOURCE
28+#define INLOC tf,tf->source->str,tf->lineDefined
29+
30+/* format for numbers in listings and error messages */
31+#ifndef NUMBER_FMT
32+#define NUMBER_FMT "%.16g" /* LUA_NUMBER */
4933 #endif
5034
51−#if 0
52−#define ID_NUMBER ID_INT4
53−#define ID_NUMBER ID_REAL4
54−#define ID_NUMBER ID_REAL8
55−#define ID_NUMBER ID_NATIVE
56−#endif
57−
58−#endif
35+/* a multiple of PI for testing native format */
36+/* multiplying by 1E8 gives non-trivial integer values */
37+#define TEST_NUMBER 3.14159265358979323846E8
5938
60−#if ID_NUMBER==ID_REAL4
61− #define DumpNumber DumpFloat
62− #define LoadNumber LoadFloat
63− #define SIZEOF_NUMBER 4
64−#elif ID_NUMBER==ID_REAL8
65− #define DumpNumber DumpDouble
66− #define LoadNumber LoadDouble
67− #define SIZEOF_NUMBER 8
68−#elif ID_NUMBER==ID_INT4
69− #define DumpNumber DumpLong
70− #define LoadNumber LoadLong
71− #define SIZEOF_NUMBER 4
72−#elif ID_NUMBER==ID_NATIVE
73− #define DumpNumber DumpNative
74− #define LoadNumber LoadNative
75− #define SIZEOF_NUMBER sizeof(real)
76−#else
77− #error bad ID_NUMBER
7839 #endif
src/lvm.c+234−336
@@ -1,11 +1,14 @@
11 /*
2−** $Id: lvm.c,v 1.30 1998/06/11 18:21:37 roberto Exp $
2+** $Id: lvm.c,v 1.58 1999/06/22 20:37:23 roberto Exp $
33 ** Lua virtual machine
44 ** See Copyright Notice in lua.h
55 */
66
77
8+#include <ctype.h>
9+#include <limits.h>
810 #include <stdio.h>
11+#include <stdlib.h>
912 #include <string.h>
1013
1114 #include "lauxlib.h"
@@ -13,6 +16,7 @@ · 1 unmodified line
1316 #include "lfunc.h"
1417 #include "lgc.h"
1518 #include "lmem.h"
19+#include "lobject.h"
1620 #include "lopcodes.h"
1721 #include "lstate.h"
1822 #include "lstring.h"
@@ -27,9 +31,7 @@ · 8 unmodified lines
2731 #endif
2832
2933
30−#define skip_word(pc) (pc+=2)
31−#define get_word(pc) ((*(pc)<<8)+(*((pc)+1)))
32−#define next_word(pc) (pc+=2, get_word(pc-2))
34+#define highbyte(x) ((x)<<8)
3335
3436
3537 /* Extra stack size to run a function: LUA_T_LINE(1), TM calls(2), ... */
@@ -37,45 +39,47 @@ · 1 unmodified line
3739
3840
3941
40−static TaggedString *strconc (TaggedString *l, TaggedString *r)
41−{
42− size_t nl = l->u.s.len;
43− size_t nr = r->u.s.len;
44− char *buffer = luaL_openspace(nl+nr+1);
42+static TaggedString *strconc (TaggedString *l, TaggedString *r) {
43+ long nl = l->u.s.len;
44+ long nr = r->u.s.len;
45+ char *buffer = luaL_openspace(nl+nr);
4546 memcpy(buffer, l->str, nl);
4647 memcpy(buffer+nl, r->str, nr);
4748 return luaS_newlstr(buffer, nl+nr);
4849 }
4950
5051
51−int luaV_tonumber (TObject *obj)
52−{ /* LUA_NUMBER */
53− double t;
54− char c;
52+int luaV_tonumber (TObject *obj) { /* LUA_NUMBER */
5553 if (ttype(obj) != LUA_T_STRING)
5654 return 1;
57− else if (sscanf(svalue(obj), "%lf %c",&t, &c) == 1) {
58− nvalue(obj) = (real)t;
55+ else {
56+ double t;
57+ char *e = svalue(obj);
58+ int sig = 1;
59+ while (isspace((unsigned char)*e)) e++;
60+ if (*e == '-') {
61+ e++;
62+ sig = -1;
63+ }
64+ else if (*e == '+') e++;
65+ /* no digit before or after decimal point? */
66+ if (!isdigit((unsigned char)*e) && !isdigit((unsigned char)*(e+1)))
67+ return 2;
68+ t = luaO_str2d(e);
69+ if (t<0) return 2;
70+ nvalue(obj) = (real)t*sig;
5971 ttype(obj) = LUA_T_NUMBER;
6072 return 0;
6173 }
62− else
63− return 2;
6474 }
6575
6676
67−int luaV_tostring (TObject *obj)
68−{ /* LUA_NUMBER */
77+int luaV_tostring (TObject *obj) { /* LUA_NUMBER */
6978 if (ttype(obj) != LUA_T_NUMBER)
7079 return 1;
7180 else {
72− char s[60];
73− real f = nvalue(obj);
74− int i;
75− if ((real)(-MAX_INT) <= f && f <= (real)MAX_INT && (real)(i=(int)f) == f)
76− sprintf (s, "%d", i);
77− else
78− sprintf (s, NUMBER_FMT, nvalue(obj));
81+ char s[32]; /* 16 digits, signal, point and \0 (+ some extra...) */
82+ sprintf(s, "%.16g", (double)nvalue(obj));
7983 tsvalue(obj) = luaS_new(s);
8084 ttype(obj) = LUA_T_STRING;
8185 return 0;
@@ -83,8 +87,15 @@ int luaV_tostring (TObject *obj) · 1 unmodified line
8387 }
8488
8589
86−void luaV_closure (int nelems)
87−{
90+void luaV_setn (Hash *t, int val) {
91+ TObject index, value;
92+ ttype(&index) = LUA_T_STRING; tsvalue(&index) = luaS_new("n");
93+ ttype(&value) = LUA_T_NUMBER; nvalue(&value) = val;
94+ luaH_set(t, &index, &value);
95+}
96+
97+
98+void luaV_closure (int nelems) {
8899 if (nelems > 0) {
89100 struct Stack *S = &L->stack;
90101 Closure *c = luaF_newclosure(nelems);
@@ -101,99 +112,110 @@ void luaV_closure (int nelems) · 10 unmodified lines
101112 ** Function to index a table.
102113 ** Receives the table at top-2 and the index at top-1.
103114 */
104−void luaV_gettable (void)
105−{
106− struct Stack *S = &L->stack;
115+void luaV_gettable (void) {
116+ TObject *table = L->stack.top-2;
107117 TObject *im;
108− if (ttype(S->top-2) != LUA_T_ARRAY) /* not a table, get "gettable" method */
109− im = luaT_getimbyObj(S->top-2, IM_GETTABLE);
118+ if (ttype(table) != LUA_T_ARRAY) { /* not a table, get gettable method */
119+ im = luaT_getimbyObj(table, IM_GETTABLE);
120+ if (ttype(im) == LUA_T_NIL)
121+ lua_error("indexed expression not a table");
122+ }
110123 else { /* object is a table... */
111− int tg = (S->top-2)->value.a->htag;
124+ int tg = table->value.a->htag;
112125 im = luaT_getim(tg, IM_GETTABLE);
113126 if (ttype(im) == LUA_T_NIL) { /* and does not have a "gettable" method */
114− TObject *h = luaH_get(avalue(S->top-2), S->top-1);
115− if (h != NULL && ttype(h) != LUA_T_NIL) {
116− --S->top;
117− *(S->top-1) = *h;
127+ TObject *h = luaH_get(avalue(table), table+1);
128+ if (ttype(h) == LUA_T_NIL &&
129+ (ttype(im=luaT_getim(tg, IM_INDEX)) != LUA_T_NIL)) {
130+ /* result is nil and there is an "index" tag method */
131+ luaD_callTM(im, 2, 1); /* calls it */
118132 }
119− else if (ttype(im=luaT_getim(tg, IM_INDEX)) != LUA_T_NIL)
120− luaD_callTM(im, 2, 1);
121133 else {
122− --S->top;
123− ttype(S->top-1) = LUA_T_NIL;
134+ L->stack.top--;
135+ *table = *h; /* "push" result into table position */
124136 }
125137 return;
126138 }
127139 /* else it has a "gettable" method, go through to next command */
128140 }
129141 /* object is not a table, or it has a "gettable" method */
130− if (ttype(im) != LUA_T_NIL)
131− luaD_callTM(im, 2, 1);
132− else
133− lua_error("indexed expression not a table");
142+ luaD_callTM(im, 2, 1);
134143 }
135144
136145
137146 /*
138−** Function to store indexed based on values at the stack.top
139−** mode = 0: raw store (without tag methods)
140−** mode = 1: normal store (with tag methods)
141−** mode = 2: "deep L->stack.stack" store (with tag methods)
147+** Receives table at *t, index at *(t+1) and value at top.
142148 */
143−void luaV_settable (TObject *t, int mode)
144−{
149+void luaV_settable (TObject *t) {
145150 struct Stack *S = &L->stack;
146− TObject *im = (mode == 0) ? NULL : luaT_getimbyObj(t, IM_SETTABLE);
147− if (ttype(t) == LUA_T_ARRAY && (im == NULL || ttype(im) == LUA_T_NIL)) {
148− TObject *h = luaH_set(avalue(t), t+1);
149− *h = *(S->top-1);
150− S->top -= (mode == 2) ? 1 : 3;
151+ TObject *im;
152+ if (ttype(t) != LUA_T_ARRAY) { /* not a table, get "settable" method */
153+ im = luaT_getimbyObj(t, IM_SETTABLE);
154+ if (ttype(im) == LUA_T_NIL)
155+ lua_error("indexed expression not a table");
151156 }
152− else { /* object is not a table, and/or has a specific "settable" method */
153− if (im && ttype(im) != LUA_T_NIL) {
154− if (mode == 2) {
155− *(S->top+1) = *(L->stack.top-1);
156− *(S->top) = *(t+1);
157− *(S->top-1) = *t;
158− S->top += 2; /* WARNING: caller must assure stack space */
159− }
160− luaD_callTM(im, 3, 0);
157+ else { /* object is a table... */
158+ im = luaT_getim(avalue(t)->htag, IM_SETTABLE);
159+ if (ttype(im) == LUA_T_NIL) { /* and does not have a "settable" method */
160+ luaH_set(avalue(t), t+1, S->top-1);
161+ S->top--; /* pop value */
162+ return;
161163 }
162− else
163− lua_error("indexed expression not a table");
164+ /* else it has a "settable" method, go through to next command */
164165 }
166+ /* object is not a table, or it has a "settable" method */
167+ /* prepare arguments and call the tag method */
168+ *(S->top+1) = *(L->stack.top-1);
169+ *(S->top) = *(t+1);
170+ *(S->top-1) = *t;
171+ S->top += 2; /* WARNING: caller must assure stack space */
172+ luaD_callTM(im, 3, 0);
165173 }
166174
167175
168−void luaV_getglobal (TaggedString *ts)
169−{
170− /* WARNING: caller must assure stack space */
171− TObject *value = &ts->u.s.globalval;
172− TObject *im = luaT_getimbyObj(value, IM_GETGLOBAL);
173− if (ttype(im) == LUA_T_NIL) { /* default behavior */
174− *L->stack.top++ = *value;
175− }
176+void luaV_rawsettable (TObject *t) {
177+ if (ttype(t) != LUA_T_ARRAY)
178+ lua_error("indexed expression not a table");
176179 else {
177180 struct Stack *S = &L->stack;
178− ttype(S->top) = LUA_T_STRING;
179− tsvalue(S->top) = ts;
180− S->top++;
181− *S->top++ = *value;
182− luaD_callTM(im, 2, 1);
181+ luaH_set(avalue(t), t+1, S->top-1);
182+ S->top -= 3;
183183 }
184184 }
185185
186186
187−void luaV_setglobal (TaggedString *ts)
188−{
187+void luaV_getglobal (TaggedString *ts) {
188+ /* WARNING: caller must assure stack space */
189+ /* only userdata, tables and nil can have getglobal tag methods */
190+ static char valid_getglobals[] = {1, 0, 0, 1, 0, 0, 1, 0}; /* ORDER LUA_T */
191+ TObject *value = &ts->u.s.globalval;
192+ if (valid_getglobals[-ttype(value)]) {
193+ TObject *im = luaT_getimbyObj(value, IM_GETGLOBAL);
194+ if (ttype(im) != LUA_T_NIL) { /* is there a tag method? */
195+ struct Stack *S = &L->stack;
196+ ttype(S->top) = LUA_T_STRING;
197+ tsvalue(S->top) = ts;
198+ S->top++;
199+ *S->top++ = *value;
200+ luaD_callTM(im, 2, 1);
201+ return;
202+ }
203+ /* else no tag method: go through to default behavior */
204+ }
205+ *L->stack.top++ = *value; /* default behavior */
206+}
207+
208+
209+void luaV_setglobal (TaggedString *ts) {
189210 TObject *oldvalue = &ts->u.s.globalval;
190211 TObject *im = luaT_getimbyObj(oldvalue, IM_SETGLOBAL);
191− if (ttype(im) == LUA_T_NIL) /* default behavior */
212+ if (ttype(im) == LUA_T_NIL) /* is there a tag method? */
192213 luaS_rawsetglobal(ts, --L->stack.top);
193214 else {
194215 /* WARNING: caller must assure stack space */
195216 struct Stack *S = &L->stack;
196− TObject newvalue = *(S->top-1);
217+ TObject newvalue;
218+ newvalue = *(S->top-1);
197219 ttype(S->top-1) = LUA_T_STRING;
198220 tsvalue(S->top-1) = ts;
199221 *S->top++ = *oldvalue;
@@ -225,7 +247,7 @@ static void call_arith (IMS event) · 25 unmodified lines
225247 }
226248
227249
228−static int strcomp (char *l, long ll, char *r, long lr)
250+static int luaV_strcomp (char *l, long ll, char *r, long lr)
229251 {
230252 for (;;) {
231253 long temp = strcoll(l, r);
@@ -242,18 +264,17 @@ static int strcomp (char *l, long ll, char *r, long lr) · 10 unmodified lines
242264 }
243265 }
244266
245−static void comparison (lua_Type ttype_less, lua_Type ttype_equal,
246− lua_Type ttype_great, IMS op)
247−{
267+void luaV_comparison (lua_Type ttype_less, lua_Type ttype_equal,
268+ lua_Type ttype_great, IMS op) {
248269 struct Stack *S = &L->stack;
249270 TObject *l = S->top-2;
250271 TObject *r = S->top-1;
251− int result;
272+ real result;
252273 if (ttype(l) == LUA_T_NUMBER && ttype(r) == LUA_T_NUMBER)
253− result = (nvalue(l) < nvalue(r)) ? -1 : (nvalue(l) == nvalue(r)) ? 0 : 1;
274+ result = nvalue(l)-nvalue(r);
254275 else if (ttype(l) == LUA_T_STRING && ttype(r) == LUA_T_STRING)
255− result = strcomp(svalue(l), tsvalue(l)->u.s.len,
256− svalue(r), tsvalue(r)->u.s.len);
276+ result = luaV_strcomp(svalue(l), tsvalue(l)->u.s.len,
277+ svalue(r), tsvalue(r)->u.s.len);
257278 else {
258279 call_binTM(op, "unexpected type in comparison");
259280 return;
@@ -265,27 +286,16 @@ static void comparison (lua_Type ttype_less, lua_Type ttype_equal, · 5 unmodified lines
265286 }
266287
267288
268−void luaV_pack (StkId firstel, int nvararg, TObject *tab)
269−{
289+void luaV_pack (StkId firstel, int nvararg, TObject *tab) {
270290 TObject *firstelem = L->stack.stack+firstel;
271291 int i;
292+ Hash *htab;
272293 if (nvararg < 0) nvararg = 0;
273− avalue(tab) = luaH_new(nvararg+1); /* +1 for field 'n' */
294+ htab = avalue(tab) = luaH_new(nvararg+1); /* +1 for field 'n' */
274295 ttype(tab) = LUA_T_ARRAY;
275− for (i=0; i<nvararg; i++) {
276− TObject index;
277− ttype(&index) = LUA_T_NUMBER;
278− nvalue(&index) = i+1;
279− *(luaH_set(avalue(tab), &index)) = *(firstelem+i);
280− }
281− /* store counter in field "n" */ {
282− TObject index, extra;
283− ttype(&index) = LUA_T_STRING;
284− tsvalue(&index) = luaS_new("n");
285− ttype(&extra) = LUA_T_NUMBER;
286− nvalue(&extra) = nvararg;
287− *(luaH_set(avalue(tab), &index)) = extra;
288− }
296+ for (i=0; i<nvararg; i++)
297+ luaH_setint(htab, i+1, firstelem+i);
298+ luaV_setn(htab, nvararg); /* store counter in field "n" */
289299 }
290300
291301
@@ -305,12 +315,11 @@ static void adjust_varargs (StkId first_extra_arg) · 13 unmodified lines
305315 ** [stack+base,top). Returns n such that the the results are between
306316 ** [stack+n,top).
307317 */
308−StkId luaV_execute (Closure *cl, TProtoFunc *tf, StkId base)
309−{
318+StkId luaV_execute (Closure *cl, TProtoFunc *tf, StkId base) {
310319 struct Stack *S = &L->stack; /* to optimize */
311− Byte *pc = tf->code;
320+ register Byte *pc = tf->code;
312321 TObject *consts = tf->consts;
313− if (lua_callhook)
322+ if (L->callhook)
314323 luaD_callHook(base, tf, 0);
315324 luaD_checkstack((*pc++)+EXTRA_STACK);
316325 if (*pc < ZEROVARARG)
@@ -319,228 +328,159 @@ StkId luaV_execute (Closure *cl, TProtoFunc *tf, StkId base) · 2 unmodified lines
319328 luaC_checkGC();
320329 adjust_varargs(base+(*pc++)-ZEROVARARG);
321330 }
322− while (1) {
323− int aux;
324− switch ((OpCode)(aux = *pc++)) {
331+ for (;;) {
332+ register int aux = 0;
333+ switchentry:
334+ switch ((OpCode)*pc++) {
335+
336+ case ENDCODE:
337+ S->top = S->stack + base;
338+ goto ret;
339+
340+ case RETCODE:
341+ base += *pc++;
342+ goto ret;
325343
326− case PUSHNIL0:
327− ttype(S->top++) = LUA_T_NIL;
344+ case CALL: aux = *pc++;
345+ luaD_calln(*pc++, aux);
328346 break;
329347
330− case PUSHNIL:
331− aux = *pc++;
348+ case TAILCALL: aux = *pc++;
349+ luaD_calln(*pc++, MULT_RET);
350+ base += aux;
351+ goto ret;
352+
353+ case PUSHNIL: aux = *pc++;
332354 do {
333355 ttype(S->top++) = LUA_T_NIL;
334356 } while (aux--);
335357 break;
336358
337− case PUSHNUMBER:
338− aux = *pc++; goto pushnumber;
339−
340− case PUSHNUMBERW:
341− aux = next_word(pc); goto pushnumber;
359+ case POP: aux = *pc++;
360+ S->top -= aux;
361+ break;
342362
343− case PUSHNUMBER0: case PUSHNUMBER1: case PUSHNUMBER2:
344− aux -= PUSHNUMBER0;
345− pushnumber:
363+ case PUSHNUMBERW: aux += highbyte(*pc++);
364+ case PUSHNUMBER: aux += *pc++;
346365 ttype(S->top) = LUA_T_NUMBER;
347366 nvalue(S->top) = aux;
348367 S->top++;
349368 break;
350369
351− case PUSHLOCAL:
352− aux = *pc++; goto pushlocal;
370+ case PUSHNUMBERNEGW: aux += highbyte(*pc++);
371+ case PUSHNUMBERNEG: aux += *pc++;
372+ ttype(S->top) = LUA_T_NUMBER;
373+ nvalue(S->top) = -aux;
374+ S->top++;
375+ break;
353376
354− case PUSHLOCAL0: case PUSHLOCAL1: case PUSHLOCAL2: case PUSHLOCAL3:
355− case PUSHLOCAL4: case PUSHLOCAL5: case PUSHLOCAL6: case PUSHLOCAL7:
356− aux -= PUSHLOCAL0;
357− pushlocal:
358− *S->top++ = *((S->stack+base) + aux);
377+ case PUSHCONSTANTW: aux += highbyte(*pc++);
378+ case PUSHCONSTANT: aux += *pc++;
379+ *S->top++ = consts[aux];
359380 break;
360381
361− case GETGLOBALW:
362− aux = next_word(pc); goto getglobal;
382+ case PUSHUPVALUE: aux = *pc++;
383+ *S->top++ = cl->consts[aux+1];
384+ break;
363385
364− case GETGLOBAL:
365− aux = *pc++; goto getglobal;
386+ case PUSHLOCAL: aux = *pc++;
387+ *S->top++ = *((S->stack+base) + aux);
388+ break;
366389
367− case GETGLOBAL0: case GETGLOBAL1: case GETGLOBAL2: case GETGLOBAL3:
368− case GETGLOBAL4: case GETGLOBAL5: case GETGLOBAL6: case GETGLOBAL7:
369− aux -= GETGLOBAL0;
370− getglobal:
390+ case GETGLOBALW: aux += highbyte(*pc++);
391+ case GETGLOBAL: aux += *pc++;
371392 luaV_getglobal(tsvalue(&consts[aux]));
372393 break;
373394
374395 case GETTABLE:
375− luaV_gettable();
376− break;
377−
378− case GETDOTTEDW:
379− aux = next_word(pc); goto getdotted;
380−
381− case GETDOTTED:
382− aux = *pc++; goto getdotted;
396+ luaV_gettable();
397+ break;
383398
384− case GETDOTTED0: case GETDOTTED1: case GETDOTTED2: case GETDOTTED3:
385− case GETDOTTED4: case GETDOTTED5: case GETDOTTED6: case GETDOTTED7:
386− aux -= GETDOTTED0;
387− getdotted:
399+ case GETDOTTEDW: aux += highbyte(*pc++);
400+ case GETDOTTED: aux += *pc++;
388401 *S->top++ = consts[aux];
389402 luaV_gettable();
390403 break;
391404
392− case PUSHSELFW:
393− aux = next_word(pc); goto pushself;
394−
395− case PUSHSELF:
396− aux = *pc++; goto pushself;
397−
398− case PUSHSELF0: case PUSHSELF1: case PUSHSELF2: case PUSHSELF3:
399− case PUSHSELF4: case PUSHSELF5: case PUSHSELF6: case PUSHSELF7:
400− aux -= PUSHSELF0;
401− pushself: {
402− TObject receiver = *(S->top-1);
405+ case PUSHSELFW: aux += highbyte(*pc++);
406+ case PUSHSELF: aux += *pc++; {
407+ TObject receiver;
408+ receiver = *(S->top-1);
403409 *S->top++ = consts[aux];
404410 luaV_gettable();
405411 *S->top++ = receiver;
406412 break;
407413 }
408414
409− case PUSHCONSTANTW:
410− aux = next_word(pc); goto pushconstant;
411−
412− case PUSHCONSTANT:
413− aux = *pc++; goto pushconstant;
414−
415− case PUSHCONSTANT0: case PUSHCONSTANT1: case PUSHCONSTANT2:
416− case PUSHCONSTANT3: case PUSHCONSTANT4: case PUSHCONSTANT5:
417− case PUSHCONSTANT6: case PUSHCONSTANT7:
418− aux -= PUSHCONSTANT0;
419− pushconstant:
420− *S->top++ = consts[aux];
421− break;
422−
423− case PUSHUPVALUE:
424− aux = *pc++; goto pushupvalue;
425−
426− case PUSHUPVALUE0: case PUSHUPVALUE1:
427− aux -= PUSHUPVALUE0;
428− pushupvalue:
429− *S->top++ = cl->consts[aux+1];
415+ case CREATEARRAYW: aux += highbyte(*pc++);
416+ case CREATEARRAY: aux += *pc++;
417+ luaC_checkGC();
418+ avalue(S->top) = luaH_new(aux);
419+ ttype(S->top) = LUA_T_ARRAY;
420+ S->top++;
430421 break;
431422
432− case SETLOCAL:
433− aux = *pc++; goto setlocal;
434−
435− case SETLOCAL0: case SETLOCAL1: case SETLOCAL2: case SETLOCAL3:
436− case SETLOCAL4: case SETLOCAL5: case SETLOCAL6: case SETLOCAL7:
437− aux -= SETLOCAL0;
438− setlocal:
423+ case SETLOCAL: aux = *pc++;
439424 *((S->stack+base) + aux) = *(--S->top);
440425 break;
441426
442− case SETGLOBALW:
443− aux = next_word(pc); goto setglobal;
444−
445− case SETGLOBAL:
446− aux = *pc++; goto setglobal;
447−
448− case SETGLOBAL0: case SETGLOBAL1: case SETGLOBAL2: case SETGLOBAL3:
449− case SETGLOBAL4: case SETGLOBAL5: case SETGLOBAL6: case SETGLOBAL7:
450− aux -= SETGLOBAL0;
451− setglobal:
427+ case SETGLOBALW: aux += highbyte(*pc++);
428+ case SETGLOBAL: aux += *pc++;
452429 luaV_setglobal(tsvalue(&consts[aux]));
453430 break;
454431
455− case SETTABLE0:
456− luaV_settable(S->top-3, 1);
457− break;
432+ case SETTABLEPOP:
433+ luaV_settable(S->top-3);
434+ S->top -= 2; /* pop table and index */
435+ break;
458436
459437 case SETTABLE:
460− luaV_settable(S->top-3-(*pc++), 2);
438+ luaV_settable(S->top-3-(*pc++));
461439 break;
462440
463− case SETLISTW:
464− aux = next_word(pc); aux *= LFIELDS_PER_FLUSH; goto setlist;
465−
466− case SETLIST:
467− aux = *(pc++) * LFIELDS_PER_FLUSH; goto setlist;
468−
469− case SETLIST0:
470− aux = 0;
471− setlist: {
441+ case SETLISTW: aux += highbyte(*pc++);
442+ case SETLIST: aux += *pc++; {
472443 int n = *(pc++);
473− TObject *arr = S->top-n-1;
474− for (; n; n--) {
475− ttype(S->top) = LUA_T_NUMBER;
476− nvalue(S->top) = n+aux;
477− *(luaH_set(avalue(arr), S->top)) = *(S->top-1);
478− S->top--;
479− }
444+ Hash *arr = avalue(S->top-n-1);
445+ aux *= LFIELDS_PER_FLUSH;
446+ for (; n; n--)
447+ luaH_setint(arr, n+aux, --S->top);
480448 break;
481449 }
482450
483− case SETMAP0:
484− aux = 0; goto setmap;
485−
486− case SETMAP:
487− aux = *pc++;
488− setmap: {
489− TObject *arr = S->top-(2*aux)-3;
451+ case SETMAP: aux = *pc++; {
452+ Hash *arr = avalue(S->top-(2*aux)-3);
490453 do {
491− *(luaH_set(avalue(arr), S->top-2)) = *(S->top-1);
454+ luaH_set(arr, S->top-2, S->top-1);
492455 S->top-=2;
493456 } while (aux--);
494457 break;
495458 }
496459
497− case POP:
498− aux = *pc++; goto pop;
499−
500− case POP0: case POP1:
501− aux -= POP0;
502− pop:
503− S->top -= (aux+1);
504− break;
505−
506− case CREATEARRAYW:
507− aux = next_word(pc); goto createarray;
508−
509− case CREATEARRAY0: case CREATEARRAY1:
510− aux -= CREATEARRAY0; goto createarray;
511−
512− case CREATEARRAY:
513− aux = *pc++;
514− createarray:
515− luaC_checkGC();
516− avalue(S->top) = luaH_new(aux);
517− ttype(S->top) = LUA_T_ARRAY;
518− S->top++;
519− break;
520−
521− case EQOP: case NEQOP: {
460+ case NEQOP: aux = 1;
461+ case EQOP: {
522462 int res = luaO_equalObj(S->top-2, S->top-1);
463+ if (aux) res = !res;
523464 S->top--;
524− if (aux == NEQOP) res = !res;
525465 ttype(S->top-1) = res ? LUA_T_NUMBER : LUA_T_NIL;
526466 nvalue(S->top-1) = 1;
527467 break;
528468 }
529469
530470 case LTOP:
531− comparison(LUA_T_NUMBER, LUA_T_NIL, LUA_T_NIL, IM_LT);
471+ luaV_comparison(LUA_T_NUMBER, LUA_T_NIL, LUA_T_NIL, IM_LT);
532472 break;
533473
534474 case LEOP:
535− comparison(LUA_T_NUMBER, LUA_T_NUMBER, LUA_T_NIL, IM_LE);
475+ luaV_comparison(LUA_T_NUMBER, LUA_T_NUMBER, LUA_T_NIL, IM_LE);
536476 break;
537477
538478 case GTOP:
539− comparison(LUA_T_NIL, LUA_T_NIL, LUA_T_NUMBER, IM_GT);
479+ luaV_comparison(LUA_T_NIL, LUA_T_NIL, LUA_T_NUMBER, IM_GT);
540480 break;
541481
542482 case GEOP:
543− comparison(LUA_T_NIL, LUA_T_NUMBER, LUA_T_NUMBER, IM_GE);
483+ luaV_comparison(LUA_T_NIL, LUA_T_NUMBER, LUA_T_NUMBER, IM_GE);
544484 break;
545485
546486 case ADDOP: {
@@ -624,98 +564,47 @@ StkId luaV_execute (Closure *cl, TProtoFunc *tf, StkId base) · 77 unmodified lines
624564 nvalue(S->top-1) = 1;
625565 break;
626566
627− case ONTJMPW:
628− aux = next_word(pc); goto ontjmp;
629−
630− case ONTJMP:
631− aux = *pc++;
632− ontjmp:
567+ case ONTJMPW: aux += highbyte(*pc++);
568+ case ONTJMP: aux += *pc++;
633569 if (ttype(S->top-1) != LUA_T_NIL) pc += aux;
634570 else S->top--;
635571 break;
636572
637− case ONFJMPW:
638− aux = next_word(pc); goto onfjmp;
639−
640− case ONFJMP:
641− aux = *pc++;
642− onfjmp:
573+ case ONFJMPW: aux += highbyte(*pc++);
574+ case ONFJMP: aux += *pc++;
643575 if (ttype(S->top-1) == LUA_T_NIL) pc += aux;
644576 else S->top--;
645577 break;
646578
647− case JMPW:
648− aux = next_word(pc); goto jmp;
649−
650− case JMP:
651− aux = *pc++;
652− jmp:
579+ case JMPW: aux += highbyte(*pc++);
580+ case JMP: aux += *pc++;
653581 pc += aux;
654582 break;
655583
656− case IFFJMPW:
657− aux = next_word(pc); goto iffjmp;
658−
659− case IFFJMP:
660− aux = *pc++;
661− iffjmp:
584+ case IFFJMPW: aux += highbyte(*pc++);
585+ case IFFJMP: aux += *pc++;
662586 if (ttype(--S->top) == LUA_T_NIL) pc += aux;
663587 break;
664588
665− case IFTUPJMPW:
666− aux = next_word(pc); goto iftupjmp;
667−
668− case IFTUPJMP:
669− aux = *pc++;
670− iftupjmp:
589+ case IFTUPJMPW: aux += highbyte(*pc++);
590+ case IFTUPJMP: aux += *pc++;
671591 if (ttype(--S->top) != LUA_T_NIL) pc -= aux;
672592 break;
673593
674− case IFFUPJMPW:
675− aux = next_word(pc); goto iffupjmp;
676−
677− case IFFUPJMP:
678− aux = *pc++;
679− iffupjmp:
594+ case IFFUPJMPW: aux += highbyte(*pc++);
595+ case IFFUPJMP: aux += *pc++;
680596 if (ttype(--S->top) == LUA_T_NIL) pc -= aux;
681597 break;
682598
683− case CLOSUREW:
684− aux = next_word(pc); goto closure;
685−
686− case CLOSURE:
687− aux = *pc++;
688− closure:
599+ case CLOSUREW: aux += highbyte(*pc++);
600+ case CLOSURE: aux += *pc++;
689601 *S->top++ = consts[aux];
690602 luaV_closure(*pc++);
691603 luaC_checkGC();
692604 break;
693605
694− case CALLFUNC:
695− aux = *pc++; goto callfunc;
696−
697− case CALLFUNC0: case CALLFUNC1:
698− aux -= CALLFUNC0;
699− callfunc: {
700− StkId newBase = (S->top-S->stack)-(*pc++);
701− luaD_call(newBase, aux);
702− break;
703− }
704−
705− case ENDCODE:
706− S->top = S->stack + base;
707− /* goes through */
708− case RETCODE:
709− if (lua_callhook)
710− luaD_callHook(base, NULL, 1);
711− return (base + ((aux==RETCODE) ? *pc : 0));
712−
713− case SETLINEW:
714− aux = next_word(pc); goto setline;
715−
716− case SETLINE:
717− aux = *pc++;
718− setline:
606+ case SETLINEW: aux += highbyte(*pc++);
607+ case SETLINE: aux += *pc++;
719608 if ((S->stack+base-1)->ttype != LUA_T_LINE) {
720609 /* open space for LINE value */
721610 luaD_openstack((S->top-S->stack)-base);
@@ -723,15 +612,24 @@ StkId luaV_execute (Closure *cl, TProtoFunc *tf, StkId base) · 1 unmodified line
723612 (S->stack+base-1)->ttype = LUA_T_LINE;
724613 }
725614 (S->stack+base-1)->value.i = aux;
726− if (lua_linehook)
615+ if (L->linehook)
727616 luaD_lineHook(aux);
728617 break;
729618
730−#ifdef DEBUG
731− default:
732− LUA_INTERNALERROR("opcode doesn't match");
733−#endif
619+ case LONGARGW: aux += highbyte(*pc++);
620+ case LONGARG: aux += *pc++;
621+ aux = highbyte(highbyte(aux));
622+ goto switchentry; /* do not reset "aux" */
623+
624+ case CHECKSTACK: aux = *pc++;
625+ LUA_ASSERT((S->top-S->stack)-base == aux && S->last >= S->top,
626+ "wrong stack size");
627+ break;
628+
734629 }
735− }
630+ } ret:
631+ if (L->callhook)
632+ luaD_callHook(0, NULL, 1);
633+ return base;
736634 }
737635
src/lvm.h+7−2
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lvm.h,v 1.4 1997/12/15 16:17:20 roberto Exp $
2+** $Id: lvm.h,v 1.8 1999/02/08 17:07:59 roberto Exp $
33 ** Lua virtual machine
44 ** See Copyright Notice in lua.h
55 */
@@ -10,6 +10,7 @@ · 4 unmodified lines
1010
1111 #include "ldo.h"
1212 #include "lobject.h"
13+#include "ltm.h"
1314
1415
1516 #define tonumber(o) ((ttype(o) != LUA_T_NUMBER) && (luaV_tonumber(o) != 0))
@@ -19,11 +20,15 @@ · 3 unmodified lines
1920 void luaV_pack (StkId firstel, int nvararg, TObject *tab);
2021 int luaV_tonumber (TObject *obj);
2122 int luaV_tostring (TObject *obj);
23+void luaV_setn (Hash *t, int val);
2224 void luaV_gettable (void);
23−void luaV_settable (TObject *t, int mode);
25+void luaV_settable (TObject *t);
26+void luaV_rawsettable (TObject *t);
2427 void luaV_getglobal (TaggedString *ts);
2528 void luaV_setglobal (TaggedString *ts);
2629 StkId luaV_execute (Closure *cl, TProtoFunc *tf, StkId base);
2730 void luaV_closure (int nelems);
31+void luaV_comparison (lua_Type ttype_less, lua_Type ttype_equal,
32+ lua_Type ttype_great, IMS op);
2833
2934 #endif
src/lzio.c+11−11
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lzio.c,v 1.3 1997/12/22 20:57:18 roberto Exp $
2+** $Id: lzio.c,v 1.7 1999/03/05 13:15:50 roberto Exp $
33 ** a generic input stream interface
44 ** See Copyright Notice in lua.h
55 */
@@ -15,11 +15,11 @@ · 9 unmodified lines
1515
1616 /* ----------------------------------------------------- memory buffers --- */
1717
18−static int zmfilbuf (ZIO* z)
19−{
18+static int zmfilbuf (ZIO* z) {
2019 return EOZ;
2120 }
2221
22+
2323 ZIO* zmopen (ZIO* z, char* b, int size, char *name)
2424 {
2525 if (b==NULL) return NULL;
@@ -41,9 +41,10 @@ ZIO* zsopen (ZIO* z, char* s, char *name) · 15 unmodified lines
4141
4242 /* -------------------------------------------------------------- FILEs --- */
4343
44−static int zffilbuf (ZIO* z)
45−{
46− int n=fread(z->buffer,1,ZBSIZE,z->u);
44+static int zffilbuf (ZIO* z) {
45+ int n;
46+ if (feof((FILE *)z->u)) return EOZ;
47+ n=fread(z->buffer,1,ZBSIZE,z->u);
4748 if (n==0) return EOZ;
4849 z->n=n-1;
4950 z->p=z->buffer;
@@ -64,16 +65,15 @@ ZIO* zFopen (ZIO* z, FILE* f, char *name) · 14 unmodified lines
6465
6566
6667 /* --------------------------------------------------------------- read --- */
67−int zread (ZIO *z, void *b, int n)
68−{
68+int zread (ZIO *z, void *b, int n) {
6969 while (n) {
7070 int m;
7171 if (z->n == 0) {
7272 if (z->filbuf(z) == EOZ)
73− return n; /* retorna quantos faltaram ler */
74− zungetc(z); /* poe o resultado de filbuf no buffer */
73+ return n; /* return number of missing bytes */
74+ zungetc(z); /* put result from 'filbuf' in the buffer */
7575 }
76− m = (n <= z->n) ? n : z->n; /* minimo de n e z->n */
76+ m = (n <= z->n) ? n : z->n; /* min. between n and z->n */
7777 memcpy(b, z->p, m);
7878 z->n -= m;
7979 z->p += m;

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t