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
4Lua is free and non-proprietary.4Lua is free and non-proprietary.
5It can be used for both academic and commercial purposes at absolutely no cost.5It can be used for both academic and commercial purposes at absolutely no cost.
6There are no royalties or GNU-like "copyleft" restrictions.6There are no royalties or GNU-like "copyleft" restrictions.
7On the other hand, Lua is not in the public domain; TeCGraf keeps its copyright.7Lua (probably) qualifies as Open Source software.
8If you use Lua, please give us credit, but we would appreciate *not* receiving8Nevertheless, Lua is not in the public domain and TeCGraf keeps its copyright.
9
10If you use Lua, please give us credit (a nice way to do this is to include a
11logo in a web page for your product), but we would appreciate *not* receiving
9lengthy legal documents to sign.12lengthy legal documents to sign.
10The legal details are below.13
14The legal details are below.
11 15
12===============================================================================16===============================================================================
13 17
14Copyright (c) 1994-1998 TeCGraf, PUC-Rio. All rights reserved.18Copyright (c) 1994-1999 TeCGraf, PUC-Rio. All rights reserved.
15 19
16Permission is hereby granted, without written agreement and without license20Permission is hereby granted, without written agreement and without license
17or royalty fees, to use, copy, modify, and distribute this software and its21or royalty fees, to use, copy, modify, and distribute this software and its
HISTORY+18−1
@@ -1,6 +1,18 @@
1This is version 3.1.1This 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".
2 13
3* Changes from version 3.0 to 3.114* Changes from version 3.0 to 3.1
15 -------------------------------
4 + NEW FEATURE: anonymous functions with closures (via "upvalues").16 + NEW FEATURE: anonymous functions with closures (via "upvalues").
5 + new syntax:17 + new syntax:
6 - local variables in chunks.18 - local variables in chunks.
@@ -23,6 +35,7 @@ This is version 3.1. · 16 unmodified lines
23 handles control-C interruptions gracefully.35 handles control-C interruptions gracefully.
24 36
25* Changes from version 2.5 to 3.037* Changes from version 2.5 to 3.0
38 -------------------------------
26 + NEW CONCEPT: "tag methods".39 + NEW CONCEPT: "tag methods".
27 Tag methods replace fallbacks as the meta-mechanism for extending the40 Tag methods replace fallbacks as the meta-mechanism for extending the
28 semantics of Lua. Whereas fallbacks had a global nature, tag methods41 semantics of Lua. Whereas fallbacks had a global nature, tag methods
@@ -37,6 +50,7 @@ This is version 3.1. · 8 unmodified lines
37 + luac can now also undump.50 + luac can now also undump.
38 51
39* Changes from version 2.4 to 2.552* Changes from version 2.4 to 2.5
53 -------------------------------
40 + io and string libraries are now based on pattern matching;54 + io and string libraries are now based on pattern matching;
41 the old libraries are still available for compatibility55 the old libraries are still available for compatibility
42 + dofile and dostring can now return values (via return statement)56 + dofile and dostring can now return values (via return statement)
@@ -44,6 +58,7 @@ This is version 3.1. · 1 unmodified line
44 + expanded documentation, with more examples58 + expanded documentation, with more examples
45 59
46* Changes from version 2.2 to 2.460* Changes from version 2.2 to 2.4
61 -------------------------------
47 + external compiler creates portable binary files that can be loaded faster62 + external compiler creates portable binary files that can be loaded faster
48 + interface for debugging and profiling63 + interface for debugging and profiling
49 + new "getglobal" fallback64 + new "getglobal" fallback
@@ -53,11 +68,13 @@ This is version 3.1. · 3 unmodified lines
53 + expanded documentation, with more examples68 + expanded documentation, with more examples
54 69
55* Changes from version 2.1 to 2.270* Changes from version 2.1 to 2.2
71 -------------------------------
56 + functions now may be declared with any "lvalue" as a name72 + functions now may be declared with any "lvalue" as a name
57 + garbage collection of functions73 + garbage collection of functions
58 + support for pipes74 + support for pipes
59 75
60* Changes from version 1.1 to 2.176* Changes from version 1.1 to 2.1
77 -------------------------------
61 + object-oriented support78 + object-oriented support
62 + fallbacks79 + fallbacks
63 + simplified syntax for tables80 + simplified syntax for tables
INSTALL+24−12
@@ -1,5 +1,7 @@
1* Installation1This is Lua 3.2
2 2
3* Installation
4 ------------
3 Building Lua on a Unix system should be very easy:5 Building Lua on a Unix system should be very easy:
4 6
5 1. Edit "config" to suit your platform, if at all necessary.7 1. Edit "config" to suit your platform, if at all necessary.
@@ -8,7 +10,7 @@ · 2 unmodified lines
8 See below for instructions for Windows and Macintosh.10 See below for instructions for Windows and Macintosh.
9 11
10* What you get12* What you get
11 13 ------------
12 If "make" succeeds, you get:14 If "make" succeeds, you get:
13 * an interpreter in ./bin/lua and a compiler in ./bin/luac;15 * an interpreter in ./bin/lua and a compiler in ./bin/luac;
14 * libraries in ./lib;16 * libraries in ./lib;
@@ -19,26 +21,36 @@ · 4 unmodified lines
19 and some useful stuff in ./etc.21 and some useful stuff in ./etc.
20 You don't need these directories for development.22 You don't need these directories for development.
21 23
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.
23 26
27* If you have problems (and solutions!)
28 -------------------------------------
24 If "make" fails, please let us know (lua@tecgraf.puc-rio.br).29 If "make" fails, please let us know (lua@tecgraf.puc-rio.br).
25 If you make changes to "config", please send them to us.30 If you make changes to "config", please send them to us.
26 31
27* Shared libraries32* Shared libraries
28 33 ----------------
29 If you are running SunOs 4.x, type the following after "make" succeeds:34 If you are running SunOs 4.x, type the following after "make" succeeds:
30 ld -o lib/liblua.so.3.1 src/*.o35 ld -o lib/liblua.so.3.2 src/*.o
31 ld -o lib/liblualib.so.3.1 src/lib/*.o36 ld -o lib/liblualib.so.3.2 src/lib/*.o
32 37
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:
34 rm bin/lua46 rm bin/lua
35 cd src/lua; make47 cd src/lua; make
48 You may need to include lib/ in the LD_LIBRAY_PATH environment variable.
36 49
37 For AIX, the OpenGL clone Mesa includes a script for making shared libraries.50 Building shared libraries in other systems is similar but details differ.
38 For other systems, please tell us how!
39 51
40* Installation on Windows or Macintosh52* Installation on Windows or Macintosh
41 53 ------------------------------------
42 The instructions for building Lua on a Mac or Windows machine depend on54 The instructions for building Lua on a Mac or Windows machine depend on
43 the particular compiler you are using.55 the particular compiler you are using.
44 The simplest way is to create a folder with all .c and .h files.56 The simplest way is to create a folder with all .c and .h files.
@@ -49,11 +61,11 @@ · 4 unmodified lines
49 llex.c lmem.c lobject.c lparser.c lstate.c lstring.c ltable.c61 llex.c lmem.c lobject.c lparser.c lstate.c lstring.c ltable.c
50 ltm.c lundump.c lvm.c lzio.c62 ltm.c lundump.c lvm.c lzio.c
51 63
52 standard lib: liolib.c lmathlib.c lstrlib.c64 standard lib: linit.c ldblib.c liolib.c lmathlib.c lstrlib.c
53 65
54 interpreter: basic lib, standard lib, lua.c66 interpreter: basic lib, standard lib, lua.c
55 67
56 compiler: basic lib, dump.c luac.c print.c stubs.c opcode.c opt.c68 compiler: basic lib, dump.c luac.c opcode.c opt.c print.c stubs.c test.c
57 69
58 Of course, to use Lua as a library, you'll have to know how to create70 Of course, to use Lua as a library, you'll have to know how to create
59 and use libraries with your compiler.71 and use libraries with your compiler.
MANIFEST+5−1
@@ -1,4 +1,4 @@
1MANIFEST contents of Lua 3.1 distribution on Sat Jul 11 22:48:43 EST 19981MANIFEST contents of Lua 3.2 distribution on Thu Jul 8 10:34:45 EST 1999
2lua2lua
3lua/COPYRIGHT3lua/COPYRIGHT
4lua/HISTORY4lua/HISTORY
@@ -14,6 +14,7 @@ lua/doc/index.html · 9 unmodified lines
14lua/doc/luac.html14lua/doc/luac.html
15lua/doc/luac.man15lua/doc/luac.man
16lua/doc/manual.html16lua/doc/manual.html
17lua/doc/readme.html
17lua/etc18lua/etc
18lua/etc/Makefile19lua/etc/Makefile
19lua/etc/README20lua/etc/README
@@ -45,6 +46,8 @@ lua/src/lgc.h · 25 unmodified lines
45lua/src/lib46lua/src/lib
46lua/src/lib/Makefile47lua/src/lib/Makefile
47lua/src/lib/README48lua/src/lib/README
49lua/src/lib/ldblib.c
50lua/src/lib/linit.c
48lua/src/lib/liolib.c51lua/src/lib/liolib.c
49lua/src/lib/lmathlib.c52lua/src/lib/lmathlib.c
50lua/src/lib/lstrlib.c53lua/src/lib/lstrlib.c
@@ -80,6 +83,7 @@ lua/src/luac/opcode.h · 29 unmodified lines
80lua/src/luac/opt.c83lua/src/luac/opt.c
81lua/src/luac/print.c84lua/src/luac/print.c
82lua/src/luac/stubs.c85lua/src/luac/stubs.c
86lua/src/luac/test.c
83lua/src/lundump.c87lua/src/lundump.c
84lua/src/lundump.h88lua/src/lundump.h
85lua/src/lvm.c89lua/src/lvm.c
Makefile+8−5
@@ -1,8 +1,11 @@
1# makefile for lua hierarchy1# makefile for lua hierarchy
2 2
3all co clean klean:3all co clean klean:
4 cd include; make $@4 cd include; $(MAKE) $@
5 cd src; make $@5 cd src; $(MAKE) $@
6 cd src/luac; make $@6 cd src/luac; $(MAKE) $@
7 cd src/lib; make $@7 cd src/lib; $(MAKE) $@
8 cd src/lua; make $@8 cd src/lua; $(MAKE) $@
9
10strip:
11 strip bin/lua*
README+11−3
@@ -1,4 +1,7 @@
1This is Lua 3.2
2
1* What is Lua?3* What is Lua?
4 ------------
2 Lua is a programming language originally designed for extending applications,5 Lua is a programming language originally designed for extending applications,
3 but also frequently used as a general-purpose, stand-alone language.6 but also frequently used as a general-purpose, stand-alone language.
4 Lua combines simple procedural syntax (similar to Pascal) with powerful7 Lua combines simple procedural syntax (similar to Pascal) with powerful
@@ -11,12 +14,13 @@ · 6 unmodified lines
11 and compiles unmodified in all known platforms. The implementation goals14 and compiles unmodified in all known platforms. The implementation goals
12 are simplicity, efficiency, portability, and low embedding cost.15 are simplicity, efficiency, portability, and low embedding cost.
13 16
14 Lua has been awarded the first prize (technological category) in the Second17 Lua was awarded the first prize (technological category) in the Second Compaq
15 Compaq Award for Research and Development in Computer Science. This award18 Award for Research and Development in Computer Science in 1997. This award
16 is a joint venture of Compaq Computer in Brazil, the Brazilian Ministry of19 is a joint venture of Compaq Computer in Brazil, the Brazilian Ministry of
17 Science and Technology, and the Brazilian Academy of Sciences.20 Science and Technology, and the Brazilian Academy of Sciences.
18 21
19* Availability22* Availability
23 ------------
20 Lua is freely available for both academic and commercial purposes and24 Lua is freely available for both academic and commercial purposes and
21 can be downloaded from the sites below. See COPYRIGHT for details.25 can be downloaded from the sites below. See COPYRIGHT for details.
22 26
@@ -24,19 +28,23 @@ · 1 unmodified line
24 http://csg.uwaterloo.ca/~lhf/lua/28 http://csg.uwaterloo.ca/~lhf/lua/
25 In Brazil: ftp://ftp.tecgraf.puc-rio.br/pub/lua/lua.tar.gz29 In Brazil: ftp://ftp.tecgraf.puc-rio.br/pub/lua/lua.tar.gz
26 In Canada: ftp://csg.uwaterloo.ca/pub/lhf/lua/lua.tar.gz30 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
27 In Germany: ftp://ftp.uni-trier.de/pub/languages/lua/lua.tar.gz32 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
28 In Greece: ftp://ftp.ntua.gr/pub/lang/lua/lua.tar.gz34 In Greece: ftp://ftp.ntua.gr/pub/lang/lua/lua.tar.gz
29 35
30* Installation36* Installation
37 ------------
31 See INSTALL.38 See INSTALL.
32 39
33* Contacting the authors40* Contacting the authors
41 ----------------------
34 Lua has been designed and implemented by Waldemar Celes,42 Lua has been designed and implemented by Waldemar Celes,
35 Roberto Ierusalimschy and Luiz Henrique de Figueiredo.43 Roberto Ierusalimschy and Luiz Henrique de Figueiredo.
36 They can be contacted by email at lua@tecgraf.puc-rio.br. 44 They can be contacted by email at lua@tecgraf.puc-rio.br.
37 45
38 Send your comments, bug reports and anything else to lua@tecgraf.puc-rio.br.46 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.br47 For reporting bugs, try also the mailing list: lua-l@tecgraf.puc-rio.br.
40 To subscribe to this list, send "subscribe lua-l YOUR-NAME" to48 To subscribe to this list, send "subscribe lua-l YOUR-NAME" to
41 listproc@tecgraf.puc-rio.br in the body of the message (not in the subject).49 listproc@tecgraf.puc-rio.br in the body of the message (not in the subject).
42 50
config+31−17
@@ -1,54 +1,68 @@
1# configuration file for making Lua1# configuration file for making Lua
2 2
3# == CHANGE THE SETTINGS BELOW TO SUIT YOUR ENVIRONMENT ======================3# == CHANGE THE SETTINGS BELOW TO SUIT YOUR ENVIRONMENT =======================
4 4
5# you need an ANSI C compiler. gcc is a popular one.5# ------------------------------------------------------------------ Lua
6CC= gcc
7WARN= -ansi -Wall
8
9# on SGI's, cc is ANSI.
10#CC= cc
11#WARN= -ansi -fullwarn
12 6
13# if you need compatibility with version 2.5 or older, uncomment the line below.7# if you need compatibility with version 2.5 or older, uncomment the line below.
14#COMPAT= -DLUA_COMPAT2_58#COMPAT= -DLUA_COMPAT2_5
15 9
16# Lua uses double for numbers. To change this, uncomment one of the lines below.10# Lua uses double for numbers. To change this, uncomment one of the lines below.
11#NUMBER= -DLUA_NUM_TYPE=double
17#NUMBER= -DLUA_NUM_TYPE=float12#NUMBER= -DLUA_NUM_TYPE=float
18#NUMBER= -DLUA_NUM_TYPE=long13#NUMBER= -DLUA_NUM_TYPE=long
19 14
20# if you want support for pipes, uncomment the following line.15# if you want support for pipes, uncomment the following line.
21#POPEN= -DPOPEN16#POPEN= -DPOPEN
22 17
18# ------------------------------------------------------------------ C compiler
19
20# you need an ANSI C compiler. gcc is a popular one.
21CC= gcc
22WARN= -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
23# if your C library is not POSIX compliant, comment the following line.34# if your C library is not POSIX compliant, comment the following line.
24POSIX= -D_POSIX_SOURCE35POSIX= -D_POSIX_SOURCE
25 36
26# if your C library does not have the newer ANSI functions memmove, strerror,37# 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.
28#OLD_ANSI= -DOLD_ANSI39#OLD_ANSI= -DOLD_ANSI
29 40
30# in SunOs 4.1.x, standard headers in /usr/include are not ANSI,41# in SunOs 4.1.x, standard headers in /usr/include are not ANSI,
31# so uncomment the following line to avoid prototypes warnings.42# so uncomment the following line to avoid prototypes warnings.
32#EXTRA_INCS= -I/usr/5include43#EXTRA_INCS= -I/usr/5include
33 44
34# if your system doesn't have (or need) ranlib, change "ranlib" to "true".45# ------------------------------------------------------------------ librarian
35# on some systems, "ar s" does it.
36RANLIB= ranlib
37#RANLIB= ar s
38#RANLIB= true
39 46
40# this should work in all unix systems.47# this should work in all unix systems.
41AR= ar rcu48AR= ar rcu
42 49
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.
52RANLIB= ranlib
53#RANLIB= ar s
54#RANLIB= true
55
56# == END OF USER SETTINGS. DO NOT CHANGE ANYTHING BELOW THIS LINE =============
44 57
45VERSION= 3.158VERSION= 3.2
46 59
47INC= $(LUA)/include60INC= $(LUA)/include
48LIB= $(LUA)/lib61LIB= $(LUA)/lib
49BIN= $(LUA)/bin62BIN= $(LUA)/bin
50 63
51INCS= -I$(INC) $(EXTRA_INCS)64INCS= -I$(INC) $(EXTRA_INCS)
52DEFS= $(COMPAT) $(NUMBER) $(OLD_ANSI) $(EXTRA_DEFS)65DEFS= $(COMPAT) $(NUMBER) $(OLD_ANSI) $(EXTRALIB) $(EXTRA_DEFS)
53 66
54CFLAGS= -O2 $(WARN) $(INCS) $(DEFS)67CFLAGS= -O2 $(WARN) $(INCS) $(DEFS)
68
doc/idx.html+26−6
@@ -1,9 +1,9 @@
1<HTML>1<HTML>
2<HEAD>2<HEAD>
3<TITLE>Lua 3.1 Reference Manual - Word Index</TITLE>3<TITLE>Lua 3.2 Reference Manual - Word Index</TITLE>
4</HEAD>4</HEAD>
5 5
6<BODY>6<BODY BGCOLOR="#FFFFFF">
7 7
8<H1>Index</H1>8<H1>Index</H1>
9 9
@@ -28,10 +28,10 @@ · 18 unmodified lines
28<A HREF="manual.html#Operator precedence">Operator precedence</A><BR>28<A HREF="manual.html#Operator precedence">Operator precedence</A><BR>
29<A HREF="manual.html#PI">PI</A><BR>29<A HREF="manual.html#PI">PI</A><BR>
30<A HREF="manual.html#Pre-processor">Pre-processor</A><BR>30<A HREF="manual.html#Pre-processor">Pre-processor</A><BR>
31<A HREF="manual.html#Tag Methods">Tag Methods</A><BR>
32<A HREF="manual.html#Types and Tags">Types and Tags</A><BR>31<A HREF="manual.html#Types and Tags">Types and Tags</A><BR>
33<A HREF="manual.html#Upvalues">Upvalues</A><BR>32<A HREF="manual.html#Upvalues">Upvalues</A><BR>
34<A HREF="manual.html#Visibility">Visibility</A><BR>33<A HREF="manual.html#Visibility">Visibility</A><BR>
34<A HREF="manual.html#_ERRORMESSAGE">_ERRORMESSAGE</A><BR>
35<A HREF="manual.html#_INPUT">_INPUT</A><BR>35<A HREF="manual.html#_INPUT">_INPUT</A><BR>
36<A HREF="manual.html#_OUTPUT">_OUTPUT</A><BR>36<A HREF="manual.html#_OUTPUT">_OUTPUT</A><BR>
37<A HREF="manual.html#_STDERR">_STDERR</A><BR>37<A HREF="manual.html#_STDERR">_STDERR</A><BR>
@@ -40,6 +40,7 @@ · 2 unmodified lines
40<A HREF="manual.html#abs">abs</A><BR>40<A HREF="manual.html#abs">abs</A><BR>
41<A HREF="manual.html#acos">acos</A><BR>41<A HREF="manual.html#acos">acos</A><BR>
42<A HREF="manual.html#add event">add event</A><BR>42<A HREF="manual.html#add event">add event</A><BR>
43<A HREF="manual.html#alert">alert</A><BR>
43<A HREF="manual.html#and">and</A><BR>44<A HREF="manual.html#and">and</A><BR>
44<A HREF="manual.html#appendto">appendto</A><BR>45<A HREF="manual.html#appendto">appendto</A><BR>
45<A HREF="manual.html#arguments">arguments</A><BR>46<A HREF="manual.html#arguments">arguments</A><BR>
@@ -59,6 +60,7 @@ · 13 unmodified lines
59<A HREF="manual.html#character class">character class</A><BR>60<A HREF="manual.html#character class">character class</A><BR>
60<A HREF="manual.html#chunk">chunk</A><BR>61<A HREF="manual.html#chunk">chunk</A><BR>
61<A HREF="manual.html#clock">clock</A><BR>62<A HREF="manual.html#clock">clock</A><BR>
63<A HREF="manual.html#closefile">closefile</A><BR>
62<A HREF="manual.html#closing a file">closing a file</A><BR>64<A HREF="manual.html#closing a file">closing a file</A><BR>
63<A HREF="manual.html#collectgarbage">collectgarbage</A><BR>65<A HREF="manual.html#collectgarbage">collectgarbage</A><BR>
64<A HREF="manual.html#concatenation event">concatenation event</A><BR>66<A HREF="manual.html#concatenation event">concatenation event</A><BR>
@@ -74,7 +76,6 @@ · 9 unmodified lines
74<A HREF="manual.html#dofile">dofile</A><BR>76<A HREF="manual.html#dofile">dofile</A><BR>
75<A HREF="manual.html#dostring">dostring</A><BR>77<A HREF="manual.html#dostring">dostring</A><BR>
76<A HREF="manual.html#eight-bit clean">eight-bit clean</A><BR>78<A HREF="manual.html#eight-bit clean">eight-bit clean</A><BR>
77<A HREF="manual.html#error method">error method</A><BR>
78<A HREF="manual.html#error">error</A><BR>79<A HREF="manual.html#error">error</A><BR>
79<A HREF="manual.html#event">event</A><BR>80<A HREF="manual.html#event">event</A><BR>
80<A HREF="manual.html#execute">execute</A><BR>81<A HREF="manual.html#execute">execute</A><BR>
@@ -82,10 +83,13 @@ · 1 unmodified line
82<A HREF="manual.html#exponentiation">exponentiation</A><BR>83<A HREF="manual.html#exponentiation">exponentiation</A><BR>
83<A HREF="manual.html#file handles">file handles</A><BR>84<A HREF="manual.html#file handles">file handles</A><BR>
84<A HREF="manual.html#floor">floor</A><BR>85<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>
85<A HREF="manual.html#foreachvar">foreachvar</A><BR>88<A HREF="manual.html#foreachvar">foreachvar</A><BR>
86<A HREF="manual.html#foreach">foreach</A><BR>89<A HREF="manual.html#foreach">foreach</A><BR>
87<A HREF="manual.html#format">format</A><BR>90<A HREF="manual.html#format">format</A><BR>
88<A HREF="manual.html#frexp">frexp</A><BR>91<A HREF="manual.html#frexp">frexp</A><BR>
92<A HREF="manual.html#funcinfo">funcinfo</A><BR>
89<A HREF="manual.html#function call">function call</A><BR>93<A HREF="manual.html#function call">function call</A><BR>
90<A HREF="manual.html#function event">function event</A><BR>94<A HREF="manual.html#function event">function event</A><BR>
91<A HREF="manual.html#function">function</A><BR>95<A HREF="manual.html#function">function</A><BR>
@@ -94,6 +98,9 @@ · 2 unmodified lines
94<A HREF="manual.html#getenv">getenv</A><BR>98<A HREF="manual.html#getenv">getenv</A><BR>
95<A HREF="manual.html#getglobal event">getglobal event</A><BR>99<A HREF="manual.html#getglobal event">getglobal event</A><BR>
96<A HREF="manual.html#getglobal">getglobal</A><BR>100<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>
97<A HREF="manual.html#gettable event">gettable event</A><BR>104<A HREF="manual.html#gettable event">gettable event</A><BR>
98<A HREF="manual.html#gettagmethod">gettagmethod</A><BR>105<A HREF="manual.html#gettagmethod">gettagmethod</A><BR>
99<A HREF="manual.html#gettagmethod">gettagmethod</A><BR>106<A HREF="manual.html#gettagmethod">gettagmethod</A><BR>
@@ -158,7 +165,6 @@ · 58 unmodified lines
158<A HREF="manual.html#lua_rawsettable">lua_rawsettable</A><BR>165<A HREF="manual.html#lua_rawsettable">lua_rawsettable</A><BR>
159<A HREF="manual.html#lua_ref">lua_ref</A><BR>166<A HREF="manual.html#lua_ref">lua_ref</A><BR>
160<A HREF="manual.html#lua_register">lua_register</A><BR>167<A HREF="manual.html#lua_register">lua_register</A><BR>
161<A HREF="manual.html#lua_seterrormethod">lua_seterrormethod</A><BR>
162<A HREF="manual.html#lua_setglobal">lua_setglobal</A><BR>168<A HREF="manual.html#lua_setglobal">lua_setglobal</A><BR>
163<A HREF="manual.html#lua_setstate">lua_setstate</A><BR>169<A HREF="manual.html#lua_setstate">lua_setstate</A><BR>
164<A HREF="manual.html#lua_settable">lua_settable</A><BR>170<A HREF="manual.html#lua_settable">lua_settable</A><BR>
@@ -183,6 +189,7 @@ · 18 unmodified lines
183<A HREF="manual.html#nil">nil</A><BR>189<A HREF="manual.html#nil">nil</A><BR>
184<A HREF="manual.html#not">not</A><BR>190<A HREF="manual.html#not">not</A><BR>
185<A HREF="manual.html#number">number</A><BR>191<A HREF="manual.html#number">number</A><BR>
192<A HREF="manual.html#openfile">openfile</A><BR>
186<A HREF="manual.html#or">or</A><BR>193<A HREF="manual.html#or">or</A><BR>
187<A HREF="manual.html#packed results">packed results</A><BR>194<A HREF="manual.html#packed results">packed results</A><BR>
188<A HREF="manual.html#pattern item">pattern item</A><BR>195<A HREF="manual.html#pattern item">pattern item</A><BR>
@@ -216,10 +223,14 @@ · 27 unmodified lines
216<A HREF="manual.html#reserved words">reserved words</A><BR>223<A HREF="manual.html#reserved words">reserved words</A><BR>
217<A HREF="manual.html#return statement">return statement</A><BR>224<A HREF="manual.html#return statement">return statement</A><BR>
218<A HREF="manual.html#return">return</A><BR>225<A HREF="manual.html#return">return</A><BR>
226<A HREF="manual.html#seek">seek</A><BR>
219<A HREF="manual.html#self">self</A><BR>227<A HREF="manual.html#self">self</A><BR>
228<A HREF="manual.html#setcallhook">setcallhook</A><BR>
220<A HREF="manual.html#setglobal event">setglobal event</A><BR>229<A HREF="manual.html#setglobal event">setglobal event</A><BR>
221<A HREF="manual.html#setglobal">setglobal</A><BR>230<A HREF="manual.html#setglobal">setglobal</A><BR>
231<A HREF="manual.html#setlinehook">setlinehook</A><BR>
222<A HREF="manual.html#setlocale">setlocale</A><BR>232<A HREF="manual.html#setlocale">setlocale</A><BR>
233<A HREF="manual.html#setlocal">setlocal</A><BR>
223<A HREF="manual.html#settable event">settable event</A><BR>234<A HREF="manual.html#settable event">settable event</A><BR>
224<A HREF="manual.html#settagmethod">settagmethod</A><BR>235<A HREF="manual.html#settagmethod">settagmethod</A><BR>
225<A HREF="manual.html#settagmethod">settagmethod</A><BR>236<A HREF="manual.html#settagmethod">settagmethod</A><BR>
@@ -227,8 +238,10 @@ · 1 unmodified line
227<A HREF="manual.html#short-cut evaluation">short-cut evaluation</A><BR>238<A HREF="manual.html#short-cut evaluation">short-cut evaluation</A><BR>
228<A HREF="manual.html#sin">sin</A><BR>239<A HREF="manual.html#sin">sin</A><BR>
229<A HREF="manual.html#skips">skips</A><BR>240<A HREF="manual.html#skips">skips</A><BR>
241<A HREF="manual.html#sort">sort</A><BR>
230<A HREF="manual.html#sqrt">sqrt</A><BR>242<A HREF="manual.html#sqrt">sqrt</A><BR>
231<A HREF="manual.html#statements">statements</A><BR>243<A HREF="manual.html#statements">statements</A><BR>
244<A HREF="manual.html#stderr">stderr</A><BR>
232<A HREF="manual.html#strbyte">strbyte</A><BR>245<A HREF="manual.html#strbyte">strbyte</A><BR>
233<A HREF="manual.html#strchar">strchar</A><BR>246<A HREF="manual.html#strchar">strchar</A><BR>
234<A HREF="manual.html#strfind">strfind</A><BR>247<A HREF="manual.html#strfind">strfind</A><BR>
@@ -240,25 +253,32 @@ · 5 unmodified lines
240<A HREF="manual.html#strupper">strupper</A><BR>253<A HREF="manual.html#strupper">strupper</A><BR>
241<A HREF="manual.html#sub event">sub event</A><BR>254<A HREF="manual.html#sub event">sub event</A><BR>
242<A HREF="manual.html#table">table</A><BR>255<A HREF="manual.html#table">table</A><BR>
256<A HREF="manual.html#tag methods">tag methods</A><BR>
243<A HREF="manual.html#tag">tag</A><BR>257<A HREF="manual.html#tag">tag</A><BR>
244<A HREF="manual.html#tag">tag</A><BR>258<A HREF="manual.html#tag">tag</A><BR>
245<A HREF="manual.html#tan">tan</A><BR>259<A HREF="manual.html#tan">tan</A><BR>
260<A HREF="manual.html#tinsert">tinsert</A><BR>
246<A HREF="manual.html#tmpname">tmpname</A><BR>261<A HREF="manual.html#tmpname">tmpname</A><BR>
247<A HREF="manual.html#tokens">tokens</A><BR>262<A HREF="manual.html#tokens">tokens</A><BR>
248<A HREF="manual.html#tonumber">tonumber</A><BR>263<A HREF="manual.html#tonumber">tonumber</A><BR>
249<A HREF="manual.html#tostring">tostring</A><BR>264<A HREF="manual.html#tostring">tostring</A><BR>
265<A HREF="manual.html#tremove">tremove</A><BR>
250<A HREF="manual.html#type">type</A><BR>266<A HREF="manual.html#type">type</A><BR>
251<A HREF="manual.html#unm event">unm event</A><BR>267<A HREF="manual.html#unm event">unm event</A><BR>
252<A HREF="manual.html#userdata">userdata</A><BR>268<A HREF="manual.html#userdata">userdata</A><BR>
253<A HREF="manual.html#vararg">vararg</A><BR>269<A HREF="manual.html#vararg">vararg</A><BR>
254<A HREF="manual.html#version 3.0">version 3.0</A><BR>270<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>
255<A HREF="manual.html#while-do">while-do</A><BR>272<A HREF="manual.html#while-do">while-do</A><BR>
256<A HREF="manual.html#writeto">writeto</A><BR>273<A HREF="manual.html#writeto">writeto</A><BR>
257<A HREF="manual.html#write">write</A><BR>274<A HREF="manual.html#write">write</A><BR>
258 275
259<HR>276<HR>
277<SMALL>
260Last update:278Last update:
261Fri Jul 10 15:10:14 EST 1998279Wed Jul 7 13:36:24 EST 1999
262by <A HREF="http://www.tecgraf.puc-rio.br/~lhf/">lhf</A>.280by <A HREF="http://www.tecgraf.puc-rio.br/~lhf/">lhf</A>.
281</SMALL>
282
263</BODY>283</BODY>
264</HTML>284</HTML>
doc/index.html+15−6
@@ -1,16 +1,17 @@
1<HTML>1<HTML>
2<HEAD>2<HEAD>
3<TITLE>Lua 3.1 Reference Manual - Contents</TITLE>3<TITLE>Lua 3.2 Reference Manual - Contents</TITLE>
4</HEAD>4</HEAD>
5 5
6<BODY>6<BODY BGCOLOR="#FFFFFF">
7 7
8<HR>
8<H1>Reference Manual of the Programming Language9<H1>Reference Manual of the Programming Language
9<A HREF="http://www.tecgraf.puc-rio.br/lua/">Lua</A>10<A HREF="http://www.tecgraf.puc-rio.br/lua/">Lua</A>
103.1</H1>113.2</H1>
11<P>12<P>
12<A HREF="http://www.inf.puc-rio.br/~roberto/">Roberto Ierusalimschy</A>,13<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>,
14<A HREF="http://www.tecgraf.puc-rio.br/~celes/">Waldemar Celes</A>15<A HREF="http://www.tecgraf.puc-rio.br/~celes/">Waldemar Celes</A>
15<BR>16<BR>
16<A HREF="mailto:lua@tecgraf.puc-rio.br">lua@tecgraf.puc-rio.br</A><BR>17<A HREF="mailto:lua@tecgraf.puc-rio.br">lua@tecgraf.puc-rio.br</A><BR>
@@ -26,7 +27,11 @@ · 9 unmodified lines
26|27|
27<A HREF="idx.html">index</A>28<A HREF="idx.html">index</A>
28|29|
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>
30]35]
31<HR>36<HR>
32<A NAME="contents"></A>37<A NAME="contents"></A>
@@ -69,6 +74,7 @@ · 36 unmodified lines
69 <LI><A HREF="manual.html#7.1">7.1 - Stack and Function Information</A>74 <LI><A HREF="manual.html#7.1">7.1 - Stack and Function Information</A>
70 <LI><A HREF="manual.html#7.2">7.2 - Manipulating Local Variables</A>75 <LI><A HREF="manual.html#7.2">7.2 - Manipulating Local Variables</A>
71 <LI><A HREF="manual.html#7.3">7.3 - Hooks</A>76 <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>
72 </UL>78 </UL>
73<LI><A HREF="manual.html#8.">8 - Lua Stand-alone</A> 79<LI><A HREF="manual.html#8.">8 - Lua Stand-alone</A>
74<LI><A HREF="manual.html#Acknowledgments">Acknowledgments</A>80<LI><A HREF="manual.html#Acknowledgments">Acknowledgments</A>
@@ -77,8 +83,11 @@ · 2 unmodified lines
77</UL>83</UL>
78 84
79<HR>85<HR>
86<SMALL>
80Last update:87Last update:
81Fri Jul 10 15:10:14 EST 199888Wed Jul 7 13:36:24 EST 1999
82by <A HREF="http://www.tecgraf.puc-rio.br/~lhf/">lhf</A>.89by <A HREF="http://www.tecgraf.puc-rio.br/~lhf/">lhf</A>.
90</SMALL>
91
83</BODY>92</BODY>
84</HTML>93</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 $ -->1<!-- luac.man,v 1.17 1999/07/07 16:02:07 lhf Exp -->
2<TITLE>LUAC 1 "06 February 1998"</TITLE>2<HTML>
3<HEAD>
4<TITLE>LUAC man page</TITLE>
5</HEAD>
6
7<BODY BGCOLOR="#FFFFFF">
8
3<H1>NAME</H1>9<H1>NAME</H1>
4luac - Lua compiler10luac - Lua compiler
5<H1>SYNOPSIS</H1>11<H1>SYNOPSIS</H1>
6<B>luac</B>12<B>luac</B>
7[13[
8<B>-c</B>14<I>options</I>
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>
23] [15] [
24<B>-p</B>16<I>filenames</I>
25] [
26<B>-q</B>
27] [
28<B>-v</B>
29] [
30<B>-V</B>
31]17]
32<I>sourcefile </I>...
33<H1>DESCRIPTION</H1>18<H1>DESCRIPTION</H1>
34<B>luac</B>19<B>luac</B>
35is the Lua compiler.20is the Lua compiler.
@@ -43,10 +28,16 @@ in Lua. · 7 unmodified lines
43The main advantages of pre-compiling chunks are:28The main advantages of pre-compiling chunks are:
44faster loading,29faster loading,
45protecting source code from user changes,30protecting source code from user changes,
31and
46off-line syntax error detection.32off-line syntax error detection.
47The binary files created by33The binary files created by
48<B>luac</B>34<B>luac</B>
49are portable to all known architectures.35are portable to all architectures.
36<P>
37Pre-compiling does not imply faster execution
38because in Lua chunks are always compiled into bytecodes before being executed.
39<B>luac</B>
40simply allows those bytecodes to be saved in a file for later execution.
50<P>41<P>
51<B>luac</B>42<B>luac</B>
52produces a single output file containing the bytecodes43produces a single output file containing the bytecodes
@@ -71,16 +62,26 @@ option. · 18 unmodified lines
71<P>62<P>
72Binary files produced by differents runs of63Binary files produced by differents runs of
73<B>luac</B>64<B>luac</B>
65(even in different machines)
74can be combined into one large file,66can be combined into one large file,
75using 67using
76<B>cat</B>(1).68<B>cat</B>(1).
77The result is still a valid binary file,69The result is still a valid binary file
78and can be loaded with a single call to70and can be loaded with a single call to
79<B>lua_dofile</B>71<B>lua_dofile</B>
80or 72or
81<B>dofile</B>.73<B>dofile</B>.
82<P>74<P>
75The internal format of the binary files produced by
76<B>luac</B>
77may change when a new version of Lua is released.
78We try to maintain compatibility even for binary files,
79but sometimes it cannot be done.
80So,
81save the source files of all Lua programs that you precompile.
82<P>
83<H1>OPTIONS</H1>83<H1>OPTIONS</H1>
84Options must be separate.
84<P>85<P>
85<B>-c</B>86<B>-c</B>
86compile (this is the default).87compile (this is the default).
@@ -89,26 +90,44 @@ compile (this is the default). · 2 unmodified lines
89undump, i.e., load and list the given binary files.90undump, i.e., load and list the given binary files.
90If no files are given, then luac undumps91If no files are given, then luac undumps
91<B>luac.out</B>.92<B>luac.out</B>.
92<P>93Listing a binary file is useful to learn Lua's virtual machine.
93<B>-D "</B><I>name"</I>94Listing is also useful to test the integrity of binary files:
94predefine symbol95corrupted files will probably generate errors when undumped.
95<I>name</I>96To test without listing, use
96for conditional compilation.97<B>-q</B>.
98For a thourough integrity test,
99use
100<B>-t</B>.
97<P>101<P>
98<B>-d</B>102<B>-d</B>
99turn debugging on.103turn debugging on.
100Individual chunks may104Individual chunks may
101still control the generation of debug information with105still control the generation of debug information with
102$debug and $nodebug.106$debug and $nodebug.
107If debugging is on, then listings show the names of the local variables.
108<P>
109<B>-D "</B><I>name"</I>
110predefine symbol
111<I>name</I>
112for conditional compilation.
113By default,
114<B>luac</B>
115does
116<I>not</I>
117predefine any symbols,
118not even the built-in functions.
103<P>119<P>
104<B>-l</B>120<B>-l</B>
105produce a listing of the compiled bytecode for Lua's virtual machine.121produce a listing of the compiled bytecode for Lua's virtual machine.
106This is the default when undumping.122This is the default when undumping.
107<P>123<P>
108<B>-O</B>124<B>-n</B>
109optimize code.125Save numbers in native format.
110Debug information is removed,126By default,
111duplicate constants are coalesced.127numbers are saved in text form,
128for maximum portability.
129Binary files with numbers in native format are slightly faster to load,
130but are not completely portable.
112<P>131<P>
113<B>-o "</B><I>filename"</I>132<B>-o "</B><I>filename"</I>
114output to133output to
@@ -117,14 +136,33 @@ instead of the default · 2 unmodified lines
117<B>luac.out</B>.136<B>luac.out</B>.
118The output file cannot be a source file.137The output file cannot be a source file.
119<P>138<P>
139<B>-O</B>
140optimize.
141Debug information is removed
142and
143duplicate constants are coalesced.
144<P>
120<B>-p</B>145<B>-p</B>
121parse sources files but does not generate any output file.146parse sources files but do not generate any output file.
122Used mainly for syntax checking.147Used mainly for syntax checking.
123<P>148<P>
124<B>-q</B>149<B>-q</B>
125quiet; produces no listing.150quiet; produces no listing.
126This is the default when compiling.151This is the default when compiling.
127<P>152<P>
153<B>-t</B>
154perform a thourough integrity test when undumping.
155Code that passes this test is completely safe,
156in the sense that it will not break the interpreter.
157However,
158there 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>
162undefine symbol
163<I>name</I>
164for conditional compilation.
165<P>
128<B>-v</B>166<B>-v</B>
129print version information.167print version information.
130<P>168<P>
@@ -135,7 +173,7 @@ print the names of the source files as they are processed. · 4 unmodified lines
135<P>173<P>
136<B>luac.out</B>174<B>luac.out</B>
137default output file175default output file
138<H1>"SEE ALSO"</H1>176<H1>SEE ALSO</H1>
139<B>lua</B>(1)177<B>lua</B>(1)
140<BR>178<BR>
141<I>"Reference Manual of the Programming Language Lua"</I>179<I>"Reference Manual of the Programming Language Lua"</I>
@@ -148,11 +186,9 @@ default output file · 6 unmodified lines
148#6 (1996) 635-652.186#6 (1996) 635-652.
149<H1>DIAGNOSTICS</H1>187<H1>DIAGNOSTICS</H1>
150Error messages should be self explanatory.188Error messages should be self explanatory.
151<H1>BUGS</H1>
152Inherits any bugs from Lua,
153but Lua has no bugs...
154<H1>AUTHORS</H1>189<H1>AUTHORS</H1>
155L. H. de Figueiredo,190L. H. de Figueiredo,
156R. Ierusalimschy and191R. Ierusalimschy and
157W. Celes192W. Celes
158<I>(<A HREF="mailto:lua@tecgraf.puc-rio.br">lua@tecgraf.puc-rio.br</A>)</I>193<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 $1.\" luac.man,v 1.17 1999/07/07 16:02:07 lhf Exp
2.TH LUAC 1 "01 July 1998"2.TH LUAC 1 "1999/07/07 16:02:07"
3.SH NAME3.SH NAME
4luac \- Lua compiler4luac \- Lua compiler
5.SH SYNOPSIS5.SH SYNOPSIS
6.B luac6.B luac
7[7[
8.B \-c8.I options
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
23] [9] [
24.B \-p10.I filenames
25] [
26.B \-q
27] [
28.B \-v
29] [
30.B \-V
31]11]
32.IR sourcefile " ..."
33.SH DESCRIPTION12.SH DESCRIPTION
34.B luac13.B luac
35is the Lua compiler.14is the Lua compiler.
@@ -43,10 +22,16 @@ in Lua. · 7 unmodified lines
43The main advantages of pre-compiling chunks are:22The main advantages of pre-compiling chunks are:
44faster loading,23faster loading,
45protecting source code from user changes,24protecting source code from user changes,
25and
46off-line syntax error detection.26off-line syntax error detection.
47The binary files created by27The binary files created by
48.B luac28.B luac
49are portable to all known architectures.29are portable to all architectures.
30.LP
31Pre-compiling does not imply faster execution
32because in Lua chunks are always compiled into bytecodes before being executed.
33.B luac
34simply allows those bytecodes to be saved in a file for later execution.
50.LP35.LP
51.B luac36.B luac
52produces a single output file containing the bytecodes37produces a single output file containing the bytecodes
@@ -71,16 +56,26 @@ option. · 18 unmodified lines
71.LP56.LP
72Binary files produced by differents runs of57Binary files produced by differents runs of
73.B luac58.B luac
59(even in different machines)
74can be combined into one large file,60can be combined into one large file,
75using 61using
76.BR cat (1).62.BR cat (1).
77The result is still a valid binary file,63The result is still a valid binary file
78and can be loaded with a single call to64and can be loaded with a single call to
79.B lua_dofile65.B lua_dofile
80or 66or
81.BR dofile .67.BR dofile .
82.LP68.LP
69The internal format of the binary files produced by
70.B luac
71may change when a new version of Lua is released.
72We try to maintain compatibility even for binary files,
73but sometimes it cannot be done.
74So,
75save the source files of all Lua programs that you precompile.
76.LP
83.SH OPTIONS77.SH OPTIONS
78Options must be separate.
84.TP79.TP
85.B \-c80.B \-c
86compile (this is the default).81compile (this is the default).
@@ -89,6 +84,21 @@ compile (this is the default). · 2 unmodified lines
89undump, i.e., load and list the given binary files.84undump, i.e., load and list the given binary files.
90If no files are given, then luac undumps85If no files are given, then luac undumps
91.BR luac.out .86.BR luac.out .
87Listing a binary file is useful to learn Lua's virtual machine.
88Listing is also useful to test the integrity of binary files:
89corrupted files will probably generate errors when undumped.
90To test without listing, use
91.BR \-q .
92For a thourough integrity test,
93use
94.BR \-t .
95.TP
96.B \-d
97turn debugging on.
98Individual chunks may
99still control the generation of debug information with
100$debug and $nodebug.
101If debugging is on, then listings show the names of the local variables.
92.TP102.TP
93.BI \-D " name"103.BI \-D " name"
94predefine symbol104predefine symbol
@@ -101,21 +111,17 @@ does · 6 unmodified lines
101predefine any symbols,111predefine any symbols,
102not even the built-in functions.112not even the built-in functions.
103.TP113.TP
104.B \-d
105turn debugging on.
106Individual chunks may
107still control the generation of debug information with
108$debug and $nodebug.
109If debugging is on, then listings show the names of the local variables.
110.TP
111.B \-l114.B \-l
112produce a listing of the compiled bytecode for Lua's virtual machine.115produce a listing of the compiled bytecode for Lua's virtual machine.
113This is the default when undumping.116This is the default when undumping.
114.TP117.TP
115.B \-O118.B \-n
116optimize code.119Save numbers in native format.
117Debug information is removed,120By default,
118duplicate constants are coalesced.121numbers are saved in text form,
122for maximum portability.
123Binary files with numbers in native format are slightly faster to load,
124but are not completely portable.
119.TP125.TP
120.BI \-o " filename"126.BI \-o " filename"
121output to127output to
@@ -124,14 +130,33 @@ instead of the default · 2 unmodified lines
124.BR luac.out .130.BR luac.out .
125The output file cannot be a source file.131The output file cannot be a source file.
126.TP132.TP
133.B \-O
134optimize.
135Debug information is removed
136and
137duplicate constants are coalesced.
138.TP
127.B \-p139.B \-p
128parse sources files but does not generate any output file.140parse sources files but do not generate any output file.
129Used mainly for syntax checking.141Used mainly for syntax checking.
130.TP142.TP
131.B \-q143.B \-q
132quiet; produces no listing.144quiet; produces no listing.
133This is the default when compiling.145This is the default when compiling.
134.TP146.TP
147.B \-t
148perform a thourough integrity test when undumping.
149Code that passes this test is completely safe,
150in the sense that it will not break the interpreter.
151However,
152there 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"
156undefine symbol
157.I name
158for conditional compilation.
159.TP
135.B \-v160.B \-v
136print version information.161print version information.
137.TP162.TP
@@ -155,11 +180,9 @@ http://www.tecgraf.puc-rio.br/lua/ · 17 unmodified lines
155#6 (1996) 635-652.180#6 (1996) 635-652.
156.SH DIAGNOSTICS181.SH DIAGNOSTICS
157Error messages should be self explanatory.182Error messages should be self explanatory.
158.SH BUGS
159Inherits any bugs from Lua,
160but Lua has no bugs...
161.SH AUTHORS183.SH AUTHORS
162L. H. de Figueiredo,184L. H. de Figueiredo,
163R. Ierusalimschy and185R. Ierusalimschy and
164W. Celes186W. Celes
165.I (lua@tecgraf.puc-rio.br)187.I (lua@tecgraf.puc-rio.br)
188.\" EOF
doc/manual.html+628−298
@@ -1,9 +1,12 @@
1<HEAD>1<HEAD>
2<TITLE>Lua 3.1 Reference Manual</TITLE>2<TITLE>Lua 3.2 Reference Manual</TITLE>
3</HEAD>3</HEAD>
4<BODY>4<BODY BGCOLOR="#FFFFFF">
5<h1>Lua 3.1 Reference Manual</h1>5<h1>Lua 3.2 Reference Manual</h1>
6 6
7<!-- $Id: manual.tex,v 1.33 1999/05/27 20:21:03 roberto Exp $ -->
8<P>
9<P>
7<!-- ====================================================================== -->10<!-- ====================================================================== -->
8<HR>11<HR>
9<A NAME="1."></A>12<A NAME="1."></A>
@@ -14,10 +17,6 @@ general procedural programming with data description · 4 unmodified lines
14facilities.17facilities.
15Lua is intended to be used as a light-weight, but powerful,18Lua is intended to be used as a light-weight, but powerful,
16configuration language for any program that needs one.19configuration language for any program that needs one.
17Lua has been designed and implemented by
18W.&nbsp;Celes,
19R.&nbsp;Ierusalimschy and
20L.&nbsp;H.&nbsp;de Figueiredo.
21<P>20<P>
22Lua is implemented as a library, written in C.21Lua is implemented as a library, written in C.
23Being an extension language, Lua has no notion of a ``main'' program:22Being an extension language, Lua has no notion of a ``main'' program:
@@ -48,15 +47,17 @@ at the following URL's: · 24 unmodified lines
48<P>47<P>
49All statements in Lua are executed in a <A NAME="global environment"><EM>global environment</EM></A>.48All statements in Lua are executed in a <A NAME="global environment"><EM>global environment</EM></A>.
50This environment, which keeps all global variables,49This environment, which keeps all global variables,
51is initialized at the beginning of the embedding program and50is initialized with a call from the embedding program to
52persists until its end.51<CODE>lua_open</CODE> and
52persists until a call to <CODE>lua_close</CODE>,
53or the end of the embedding program.
53Optionally, a user can create multiple independent global54Optionally, a user can create multiple independent global
54environments (see Section&nbsp;<A HREF="#mangstate">5.1</A>).55environments (see Section&nbsp;<A HREF="#mangstate">5.1</A>).
55<P>56<P>
56The global environment can be manipulated by Lua code or57The global environment can be manipulated by Lua code or
57by the embedding program,58by the embedding program,
58which can read and write global variables59which can read and write global variables
59using functions from the API library that implements Lua.60using API functions from the library that implements Lua.
60<P>61<P>
61<A NAME="Global variables">Global variables</A> do not need declaration.62<A NAME="Global variables">Global variables</A> do not need declaration.
62Any variable is assumed to be global unless explicitly declared local63Any 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
79When a chunk is executed, first all its code is pre-compiled,80When a chunk is executed, first all its code is pre-compiled,
80then the statements are executed in sequential order.81then the statements are executed in sequential order.
81All modifications a chunk effects on the global environment persist82All modifications a chunk effects on the global environment persist
82after its end.83after the chunk end.
83<P>84<P>
84Chunks may also be pre-compiled into binary form;85Chunks may also be pre-compiled into binary form;
85see program <A NAME="luac"><TT><A HREF="luac.html">luac</A></TT></A> for details.86see 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
104<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>.105<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>.
105<EM>Nil</EM> is the type of the value <B>nil</B>,106<EM>Nil</EM> is the type of the value <B>nil</B>,
106whose main property is to be different from any other value.107whose 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,
108while <EM>string</EM> has the usual meaning.109while <EM>string</EM> has the usual meaning.
109Lua is <A NAME="eight-bit clean">eight-bit clean</A>,110Lua is <A NAME="eight-bit clean">eight-bit clean</A>,
110and so strings may contain any 8-bit character,111and 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
160Each of the types <EM>nil</EM>, <EM>number</EM> and <EM>string</EM> has a different tag.161Each of the types <EM>nil</EM>, <EM>number</EM> and <EM>string</EM> has a different tag.
161All values of each of these types have this same pre-defined tag.162All values of each of these types have this same pre-defined tag.
162Values of type <EM>function</EM> can have two different tags,163Values of type <EM>function</EM> can have two different tags,
163depending on whether they are Lua or C functions.164depending on whether they are Lua functions or C functions.
164Finally,165Finally,
165values of type <EM>userdata</EM> and <EM>table</EM> can have166values of type <EM>userdata</EM> and <EM>table</EM> can have
166as many different tags as needed (see Section&nbsp;<A HREF="#tag-method">4.8</A>).167as 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
200<TT>and</TT> is a reserved word, but <TT>And</TT> and <TT>\'and</TT>201<TT>and</TT> is a reserved word, but <TT>And</TT> and <TT>\'and</TT>
201(if the locale permits) are two other different identifiers.202(if the locale permits) are two other different identifiers.
202As a convention, identifiers starting with underscore followed by203As a convention, identifiers starting with underscore followed by
203uppercase letters should not be used in regular programs.204uppercase letters are reserved for internal variables.
204<P>205<P>
205The following strings denote other <A NAME="tokens">tokens</A>:206The following strings denote other <A NAME="tokens">tokens</A>:
206<PRE>207<PRE>
@@ -211,7 +212,7 @@ The following strings denote other <A NAME="tokens">tokens</A>: · 4 unmodified lines
211<A NAME="Literal strings">Literal strings</A> can be delimited by matching single or double quotes,212<A NAME="Literal strings">Literal strings</A> can be delimited by matching single or double quotes,
212and can contain the C-like escape sequences213and can contain the C-like escape sequences
213<CODE>'\a'</CODE> (bell),214<CODE>'\a'</CODE> (bell),
214<CODE>'\b'</CODE> (back space),215<CODE>'\b'</CODE> (backspace),
215<CODE>'\f'</CODE> (form feed),216<CODE>'\f'</CODE> (form feed),
216<CODE>'\n'</CODE> (new line),217<CODE>'\n'</CODE> (new line),
217<CODE>'\r'</CODE> (carriage return),218<CODE>'\r'</CODE> (carriage return),
@@ -251,9 +252,9 @@ in Unix systems (see Section&nbsp;<A HREF="#lua-sa">8</A>). · 33 unmodified lines
251<P>252<P>
252<A NAME="Numerical constants">Numerical constants</A> may be written with an optional decimal part,253<A NAME="Numerical constants">Numerical constants</A> may be written with an optional decimal part,
253and an optional decimal exponent.254and an optional decimal exponent.
254Examples of valid numerical constants are:255Examples of valid numerical constants are
255<PRE>256<PRE>
256 4 4.0 0.4 4.57e-3 0.3e12257 3 3.0 3.1416 314.16e-2 0.31416E1
257</PRE>258</PRE>
258<P>259<P>
259<A NAME="pre-processor"></A>260<A NAME="pre-processor"></A>
@@ -280,7 +281,7 @@ Directives may be freely nested. · 20 unmodified lines
280Particularly, a <CODE>$endinput</CODE> may occur inside a <CODE>$if</CODE>;281Particularly, a <CODE>$endinput</CODE> may occur inside a <CODE>$if</CODE>;
281in that case, even the matching <CODE>$end</CODE> is not parsed.282in that case, even the matching <CODE>$end</CODE> is not parsed.
282<P>283<P>
283A <EM>cond</EM> part may be:284A <EM>cond</EM> part may be
284<DL>285<DL>
285<DT><B><TT>nil</TT></B><DD> - always false.286<DT><B><TT>nil</TT></B><DD> - always false.
286<DT><B><TT>1</TT></B><DD> - always true.287<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
298Any arithmetic operation applied to a string tries to convert299Any arithmetic operation applied to a string tries to convert
299that string to a number, following the usual rules.300that string to a number, following the usual rules.
300Conversely, whenever a number is used when a string is expected,301Conversely, whenever a number is used when a string is expected,
301that number is converted to a string, according to the following rule:302that number is converted to a string, in a reasonable format.
302if the number is an integer, it is written without exponent or decimal point;
303otherwise, it is formatted following the <CODE>%g</CODE>
304conversion specification of the <CODE>printf</CODE> function in the
305standard C library.
306For complete control on how numbers are converted to strings,303For complete control on how numbers are converted to strings,
307use the <CODE>format</CODE> function (see Section&nbsp;<A HREF="#format">6.2</A>).304use the <CODE>format</CODE> function (see Section&nbsp;<A HREF="#format">6.2</A>).
308<P>305<P>
@@ -313,12 +310,13 @@ use the <CODE>format</CODE> function (see Section&nbsp;<A HREF="#format">6.2</A> · 4 unmodified lines
313<P>310<P>
314Functions in Lua can return many values.311Functions in Lua can return many values.
315Because there are no type declarations,312Because there are no type declarations,
313when a function is called
316the system does not know how many values a function will return,314the system does not know how many values a function will return,
317or how many parameters it needs.315or how many parameters it needs.
318Therefore, sometimes, a list of values must be <EM>adjusted</EM>, at run time,316Therefore, sometimes, a list of values must be <EM>adjusted</EM>, at run time,
319to a given length.317to a given length.
320If there are more values than are needed,318If there are more values than are needed,
321then the last values are thrown away.319then the excess values are thrown away.
322If there are more needs than values,320If there are more needs than values,
323then the list is extended with as many <B>nil</B>'s as needed.321then the list is extended with as many <B>nil</B>'s as needed.
324Adjustment occurs in multiple assignment (see Section&nbsp;<A HREF="#assignment">4.5.2</A>)322Adjustment 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
376Before the assignment, the list of values is <EM>adjusted</EM> to374Before the assignment, the list of values is <EM>adjusted</EM> to
377the length of the list of variables (see Section&nbsp;<A HREF="#adjust">4.4</A>).375the length of the list of variables (see Section&nbsp;<A HREF="#adjust">4.4</A>).
378<P>376<P>
379A single name can denote a global or a local variable,377A single name can denote a global variable, a local variable,
380or a formal parameter:378or a formal parameter:
381<PRE>379<PRE>
382var ::= name380var ::= name
@@ -414,15 +412,14 @@ only <B>nil</B> is considered false. · 31 unmodified lines
414<P>412<P>
415<A NAME="while-do"></A><A NAME="repeat-until"></A><A NAME="if-then-else"></A>413<A NAME="while-do"></A><A NAME="repeat-until"></A><A NAME="if-then-else"></A>
416<PRE>414<PRE>
417stat ::= <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>415stat ::= <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>
418elseif ::= <B>elseif</B> exp1 <B>then</B> block
419</PRE>416</PRE>
420<P>417<P>
421A <TT>return</TT> is used to return values from a function or from a chunk.418A <TT>return</TT> is used to return values from a function or from a chunk.
422<A NAME="return"></A>419<A NAME="return"></A>
423 420
424Because they may return more than one value,421Because they may return more than one value,
425the syntax for a <A NAME="return statement">return statement</A> is:422the syntax for a <A NAME="return statement">return statement</A> is
426<PRE>423<PRE>
427ret ::= <B>return</B> [explist1] [sc]424ret ::= <B>return</B> [explist1] [sc]
428</PRE>425</PRE>
@@ -457,7 +454,7 @@ Otherwise, all variables are initialized with <B>nil</B>. · 28 unmodified lines
457<H2>4.6 - Expressions</H2>454<H2>4.6 - Expressions</H2>
458<P>455<P>
459<H3>4.6.1 - <A NAME="Basic Expressions</H3>">Basic Expressions</H3></A>456<H3>4.6.1 - <A NAME="Basic Expressions</H3>">Basic Expressions</H3></A>
460Basic expressions are:457Basic expressions are
461<PRE>458<PRE>
462exp ::= '<B>(</B>' exp '<B>)</B>'459exp ::= '<B>(</B>' exp '<B>)</B>'
463exp ::= <B>nil</B>460exp ::= <B>nil</B>
@@ -477,7 +474,7 @@ string literals are explained in Section&nbsp;<A HREF="#lexical">4.1</A>; · 13 unmodified lines
477variables are explained in Section&nbsp;<A HREF="#assignment">4.5.2</A>;474variables are explained in Section&nbsp;<A HREF="#assignment">4.5.2</A>;
478upvalues are explained in Section&nbsp;<A HREF="#upvalue">4.7</A>;475upvalues are explained in Section&nbsp;<A HREF="#upvalue">4.7</A>;
479function definitions (<EM>function</EM>) are explained in Section&nbsp;<A HREF="#func-def">4.6.9</A>;476function definitions (<EM>function</EM>) are explained in Section&nbsp;<A HREF="#func-def">4.6.9</A>;
480function call are explained in Section&nbsp;<A HREF="#functioncall">4.6.8</A>.477function calls are explained in Section&nbsp;<A HREF="#functioncall">4.6.8</A>.
481<P>478<P>
482An access to a global variable <CODE>x</CODE> is equivalent to a479An access to a global variable <CODE>x</CODE> is equivalent to a
483call <CODE>getglobal('x')</CODE>;480call <CODE>getglobal('x')</CODE>;
@@ -535,7 +532,7 @@ then their values are compared using lexicographical order. · 51 unmodified lines
535Otherwise, the ``order'' tag method is called (see Section&nbsp;<A HREF="#tag-method">4.8</A>).532Otherwise, the ``order'' tag method is called (see Section&nbsp;<A HREF="#tag-method">4.8</A>).
536<P>533<P>
537<H3>4.6.4 - Logical Operators</H3>534<H3>4.6.4 - Logical Operators</H3>
538The <A NAME="logical operators">logical operators</A> are:535The <A NAME="logical operators">logical operators</A> are
539<A NAME="and"></A><A NAME="or"></A><A NAME="not"></A>536<A NAME="and"></A><A NAME="or"></A><A NAME="not"></A>
540<PRE>537<PRE>
541 and or not538 and or not
@@ -589,7 +586,7 @@ every time a constructor is evaluated, a new table is created. · 47 unmodified lines
589Constructors can be used to create empty tables,586Constructors can be used to create empty tables,
590or to create a table and initialize some fields.587or to create a table and initialize some fields.
591<P>588<P>
592The general syntax for constructors is:589The general syntax for constructors is
593<PRE>590<PRE>
594tableconstructor ::= '<B>{</B>' fieldlist '<B>}</B>'591tableconstructor ::= '<B>{</B>' fieldlist '<B>}</B>'
595fieldlist ::= lfieldlist | ffieldlist | lfieldlist '<B>;</B>' ffieldlist | ffieldlist '<B>;</B>' lfieldlist592fieldlist ::= lfieldlist | ffieldlist | lfieldlist '<B>;</B>' ffieldlist | ffieldlist '<B>;</B>' lfieldlist
@@ -597,17 +594,17 @@ lfieldlist ::= [lfieldlist1] · 1 unmodified line
597ffieldlist ::= [ffieldlist1]594ffieldlist ::= [ffieldlist1]
598</PRE>595</PRE>
599<P>596<P>
600The form <EM>lfieldlist1</EM> is used to initialize lists.597The form <EM>lfieldlist1</EM> is used to initialize lists:
601<PRE>598<PRE>
602lfieldlist1 ::= exp {'<B>,</B>' exp} ['<B>,</B>']599lfieldlist1 ::= exp {'<B>,</B>' exp} ['<B>,</B>']
603</PRE>600</PRE>
604The expressions in the list are assigned to consecutive numerical indices,601The expressions in the list are assigned to consecutive numerical indices,
605starting with 1.602starting with 1.
606For example:603For example,
607<PRE>604<PRE>
608 a = {"v1", "v2", 34}605 a = {"v1", "v2", 34}
609</PRE>606</PRE>
610is equivalent to:607is equivalent to
611<PRE>608<PRE>
612 do609 do
613 local temp = {}610 local temp = {}
@@ -623,11 +620,11 @@ The form <EM>ffieldlist1</EM> initializes other fields in a table: · 9 unmodified lines
623ffieldlist1 ::= ffield {'<B>,</B>' ffield} ['<B>,</B>']620ffieldlist1 ::= ffield {'<B>,</B>' ffield} ['<B>,</B>']
624ffield ::= '<B>[</B>' exp '<B>]</B>' '<B>=</B>' exp | name '<B>=</B>' exp621ffield ::= '<B>[</B>' exp '<B>]</B>' '<B>=</B>' exp | name '<B>=</B>' exp
625</PRE>622</PRE>
626For example:623For example,
627<PRE>624<PRE>
628 a = {[f(k)] = g(y), x = 1, y = 3, [0] = b+c}625 a = {[f(k)] = g(y), x = 1, y = 3, [0] = b+c}
629</PRE>626</PRE>
630is equivalent to:627is equivalent to
631<PRE>628<PRE>
632 do629 do
633 local temp = {}630 local temp = {}
@@ -649,7 +646,7 @@ For example, all forms below are correct: · 15 unmodified lines
649 x = {;}646 x = {;}
650 x = {'a', 'b',}647 x = {'a', 'b',}
651 x = {type='list'; 'a', 'b'}648 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,}
653</PRE>650</PRE>
654<P>651<P>
655<A NAME="functioncall"></A>652<A NAME="functioncall"></A>
@@ -678,6 +675,7 @@ is syntactic sugar for · 22 unmodified lines
678</PRE>675</PRE>
679except that <CODE>simpleexp</CODE> is evaluated only once.676except that <CODE>simpleexp</CODE> is evaluated only once.
680<P>677<P>
678Arguments have the following syntax:
681<PRE>679<PRE>
682args ::= '<B>(</B>' [explist1] '<B>)</B>'680args ::= '<B>(</B>' [explist1] '<B>)</B>'
683args ::= tableconstructor681args ::= tableconstructor
@@ -707,33 +705,33 @@ If the function is called in a place that can hold many values · 23 unmodified lines
707(syntactically denoted by the non-terminal <EM>exp</EM>),705(syntactically denoted by the non-terminal <EM>exp</EM>),
708then no adjustment is made.706then no adjustment is made.
709Note that the only place that can hold many values707Note that the only place that can hold many values
710is the last expression (or the only one) in an assignment708is the last (or the only) expression in an assignment
711or in a return statement; see examples below.709or in a return statement; see examples below.
712<PRE>710<PRE>
713 f(); -- adjusted to 0711 f(); -- adjusted to 0
714 g(x, f()); -- f() is adjusted to 1712 g(x, f()); -- f() is adjusted to 1
715 a,b,c = f(), x; -- f() is adjusted to 1 result (and c gets nil)713 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 2714 a,b,c = x, f(); -- f() is adjusted to 2
717 a,b,c = f(); -- f() is adjusted to 3715 a,b,c = f(); -- f() is adjusted to 3
718 return f(); -- returns all values returned by f()716 return f(); -- returns all values returned by f()
719</PRE>717</PRE>
720<P>718<P>
721<A NAME="func-def"></A>719<A NAME="func-def"></A>
722<H3>4.6.9 - <A NAME="Function Definitions</H3>">Function Definitions</H3></A> 720<H3>4.6.9 - <A NAME="Function Definitions</H3>">Function Definitions</H3></A>
723<P>721<P>
724The syntax for function definition is:722The syntax for function definition is
725<PRE>723<PRE>
726function ::= <B>function</B> '<B>(</B>' [parlist1] '<B>)</B>' block <B>end</B>724function ::= <B>function</B> '<B>(</B>' [parlist1] '<B>)</B>' block <B>end</B>
727stat ::= <B>function</B> funcname '<B>(</B>' [parlist1] '<B>)</B>' block <B>end</B>725stat ::= <B>function</B> funcname '<B>(</B>' [parlist1] '<B>)</B>' block <B>end</B>
728funcname ::= name | name '<B>.</B>' name726funcname ::= name | name '<B>.</B>' name
729</PRE>727</PRE>
730The statement:728The statement
731<PRE>729<PRE>
732 function f (...)730 function f (...)
733 ...731 ...
734 end732 end
735</PRE>733</PRE>
736is just syntactic sugar for:734is just syntactic sugar for
737<PRE>735<PRE>
738 f = function (...)736 f = function (...)
739 ...737 ...
@@ -769,8 +767,8 @@ A vararg function does not adjust its argument list; · 29 unmodified lines
769instead, it collects any extra arguments into an implicit parameter,767instead, it collects any extra arguments into an implicit parameter,
770called <A NAME="arg"><TT>arg</TT></A>.768called <A NAME="arg"><TT>arg</TT></A>.
771This parameter is always initialized as a table,769This parameter is always initialized as a table,
772with a field <CODE>n</CODE> with the number of extra arguments,770with a field <CODE>n</CODE> whose value is the number of extra arguments,
773and the extra arguments at positions 1, 2, ...771and the extra arguments at positions 1,&nbsp;2,&nbsp;...
774<P>772<P>
775As an example, suppose definitions like:773As an example, suppose definitions like:
776<PRE>774<PRE>
@@ -795,21 +793,21 @@ If control reaches the end of a function without a return instruction, · 18 unmodified lines
795then the function returns with no results.793then the function returns with no results.
796<P>794<P>
797There is a special syntax for defining <A NAME="methods">methods</A>,795There is a special syntax for defining <A NAME="methods">methods</A>,
798that is, functions that have an implicit extra parameter <A NAME="self"><TT>self</TT></A>.796that is, functions that have an implicit extra parameter <A NAME="self"><TT>self</TT></A>:
799<PRE>797<PRE>
800function ::= <B>function</B> name '<B>:</B>' name '<B>(</B>' [parlist1] '<B>)</B>' block <B>end</B>798function ::= <B>function</B> name '<B>:</B>' name '<B>(</B>' [parlist1] '<B>)</B>' block <B>end</B>
801</PRE>799</PRE>
802Thus, a declaration like800Thus, a declaration like
803<PRE>801<PRE>
804function v:f (...)802 function v:f (...)
805 ...803 ...
806end804 end
807</PRE>805</PRE>
808is equivalent to806is equivalent to
809<PRE>807<PRE>
810v.f = function (self, ...)808 v.f = function (self, ...)
811 ...809 ...
812end810 end
813</PRE>811</PRE>
814that is, the function gets an extra formal parameter called <CODE>self</CODE>.812that is, the function gets an extra formal parameter called <CODE>self</CODE>.
815Note that the variable <CODE>v</CODE> must have been813Note that the variable <CODE>v</CODE> must have been
@@ -842,19 +840,19 @@ at the point where the function is defined. · 26 unmodified lines
842<P>840<P>
843Here are some examples:841Here are some examples:
844<PRE>842<PRE>
845a,b,c = 1,2,3 -- global variables843 a,b,c = 1,2,3 -- global variables
846function f (x)844 function f (x)
847 local b -- x and b are local to f845 local b -- x and b are local to f
848 local g = function (a)846 local g = function (a)
849 local y -- a and y are local to g847 local y -- a and y are local to g
850 p = a -- OK, access local 'a'848 p = a -- OK, access local 'a'
851 p = c -- OK, access global 'c'849 p = c -- OK, access global 'c'
852 p = b -- ERROR: cannot access a variable in outer scope850 p = b -- ERROR: cannot access a variable in outer scope
853 p = %b -- OK, access frozen value of 'b' (local to 'f')851 p = %b -- OK, access frozen value of 'b' (local to 'f')
854 p = %c -- OK, access frozen value of global 'c'852 p = %c -- OK, access frozen value of global 'c'
855 p = %y -- ERROR: 'y' is not visible where 'g' is defined853 p = %y -- ERROR: 'y' is not visible where 'g' is defined
856 end -- g854 end -- g
857end -- f855 end -- f
858</PRE>856</PRE>
859<P>857<P>
860<P>858<P>
@@ -863,7 +861,7 @@ end -- f · 2 unmodified lines
863<H2>4.8 - Tag Methods</H2> 861<H2>4.8 - Tag Methods</H2>
864<P>862<P>
865Lua provides a powerful mechanism to extend its semantics,863Lua provides a powerful mechanism to extend its semantics,
866called <A NAME="Tag Methods"><EM>Tag Methods</EM></A>.864called <A NAME="tag methods"><EM>tag methods</EM></A>.
867A tag method is a programmer-defined function865A tag method is a programmer-defined function
868that is called at specific key points during the evaluation of a program,866that is called at specific key points during the evaluation of a program,
869allowing the programmer to change the standard Lua behavior at these points.867allowing 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
874in the event (see Section&nbsp;<A HREF="#TypesSec">3</A>).872in the event (see Section&nbsp;<A HREF="#TypesSec">3</A>).
875The function <A NAME="settagmethod"><TT>settagmethod</TT></A> changes the tag method873The function <A NAME="settagmethod"><TT>settagmethod</TT></A> changes the tag method
876associated with a given pair <EM>(tag, event)</EM>.874associated with a given pair <EM>(tag, event)</EM>.
877Its first parameter is the tag, the second is the event name875Its first parameter is the tag, the second parameter is the event name
878(a string, see below),876(a string; see below),
879and the third parameter is the new method (a function),877and the third parameter is the new method (a function),
880or <B>nil</B> to restore the default behavior.878or <B>nil</B> to restore the default behavior for the pair.
881The function returns the previous tag method for that pair.879The function returns the previous tag method for that pair.
882Another function, <A NAME="gettagmethod"><TT>gettagmethod</TT></A>,880Another function, <A NAME="gettagmethod"><TT>gettagmethod</TT></A>,
883receives a tag and an event name and returns the881receives 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
893the real behavior is hard coded in the interpreter,891the real behavior is hard coded in the interpreter,
894and it is much more efficient than this simulation.892and it is much more efficient than this simulation.
895All functions used in these descriptions893All 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.)
897are described in Section&nbsp;<A HREF="#predefined">6.1</A>.895are described in Section&nbsp;<A HREF="#predefined">6.1</A>.
898<P>896<P>
899<DL>897<DL>
@@ -1137,7 +1135,7 @@ called when Lua tries to call a non function value. · 237 unmodified lines
1137</PRE>1135</PRE>
1138<P>1136<P>
1139<DT><B>``gc'':</B><DD><A NAME="gc event"></A>1137<DT><B>``gc'':</B><DD><A NAME="gc event"></A>
1140called when Lua is garbage collecting an object.1138called when Lua is ``garbage collecting'' an object.
1141This method cannot be set for strings, numbers, functions,1139This method cannot be set for strings, numbers, functions,
1142and userdata with default tag.1140and userdata with default tag.
1143For each object to be collected,1141For each object to be collected,
@@ -1165,29 +1163,27 @@ Because Lua is an extension language, · 21 unmodified lines
1165all Lua actions start from C code in the host program1163all Lua actions start from C code in the host program
1166calling a function from the Lua library.1164calling a function from the Lua library.
1167Whenever an error occurs during Lua compilation or execution,1165Whenever an error occurs during Lua compilation or execution,
1168the <A NAME="error method"><EM>error method</EM></A> is called,1166function <CODE>_ERRORMESSAGE</CODE> is called <A NAME="_ERRORMESSAGE"></A>
1167(provided it is different from <B>nil</B>),
1169and then the corresponding function from the library1168and then the corresponding function from the library
1170(<CODE>lua_dofile</CODE>, <CODE>lua_dostring</CODE>,1169(<CODE>lua_dofile</CODE>, <CODE>lua_dostring</CODE>,
1171<CODE>lua_dobuffer</CODE>, or <CODE>lua_callfunction</CODE>)1170<CODE>lua_dobuffer</CODE>, or <CODE>lua_callfunction</CODE>)
1172is terminated, returning an error condition.1171is terminated, returning an error condition.
1173<P>1172<P>
1174The only argument to the error method is a string1173The only argument to <CODE>_ERRORMESSAGE</CODE> is a string
1175describing the error.1174describing the error.
1176The default method prints this message to <CODE>stderr</CODE>.1175The default definition for this function calls <CODE>_ALERT</CODE>,
1177If needed, it is possible to change the error method with the1176which prints the message to <CODE>stderr</CODE> (see Section&nbsp;<A HREF="#alert">6.1</A>).
1178function <CODE>seterrormethod</CODE>,1177The standard I/O library redefines <CODE>_ERRORMESSAGE</CODE>,
1179which gets the new error handler as its only parameter1178and uses the debug facilities (see Section&nbsp;<A HREF="#debugI">7</A>)
1180(see Section&nbsp;<A HREF="#pdf-seterrormethod">6.1</A>).1179to print some extra information,
1181The standard I/O library uses this facility to redefine the error method,
1182using the debug facilities (see Section&nbsp;<A HREF="#debugI">7</A>),
1183in order to print some extra information,
1184such as the call stack.1180such as the call stack.
1185<P>1181<P>
1186To provide more information about errors,1182To provide more information about errors,
1187Lua programs should include the compilation pragma <CODE>$debug</CODE>.1183Lua programs should include the compilation pragma <CODE>$debug</CODE>.
1188<A NAME="pragma"></A>1184<A NAME="pragma"></A>
1189<A NAME="debug pragma"></A>1185<A NAME="debug pragma"></A>
1190When an error occurs in a program compiled with this option,1186When an error occurs in a chunk compiled with this option,
1191the I/O error routine is able to print the number of the1187the I/O error routine is able to print the number of the
1192lines where the calls (and the error) were made.1188lines where the calls (and the error) were made.
1193<P>1189<P>
@@ -1229,6 +1225,8 @@ is stored in a dynamic structure pointed by<A NAME="lua_state"></A> · 35 unmodified lines
1229typedef struct lua_State lua_State;1225typedef struct lua_State lua_State;
1230extern lua_State *lua_state;1226extern lua_State *lua_state;
1231</PRE>1227</PRE>
1228The variable <CODE>lua_state</CODE> is the only C global variable in
1229the Lua library.
1232<P>1230<P>
1233Before calling any API function,1231Before calling any API function,
1234this state must be initialized.1232this 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
1255calling <CODE>lua_open</CODE>.1253calling <CODE>lua_open</CODE>.
1256An easy way to do that is defining an auxiliary function:1254An easy way to do that is defining an auxiliary function:
1257<PRE>1255<PRE>
1258lua_State *lua_newstate (void) {1256 lua_State *lua_newstate (void) {
1259 lua_State *old = lua_setstate(NULL);1257 lua_State *old = lua_setstate(NULL);
1260 lua_open();1258 lua_open();
1261 return lua_setstate(old);1259 return lua_setstate(old);
1262}1260 }
1263</PRE>1261</PRE>
1264This function creates a new state without changing the current state1262This function creates a new state without changing the current state
1265of the interpreter.1263of the interpreter.
1266Note that any new state is built with all predefined functions,1264Note that any new state is created with all predefined functions,
1267but any additional library (such as the standard libraries) must be1265but any additional library (such as the standard libraries) must be
1268explicitly open in the new state, if needed.1266explicitly open in the new state, if needed.
1269<P>1267<P>
1270If necessary, a state may be released:<A NAME="lua_close"></A>1268If necessary, a state may be released by calling<A NAME="lua_close"></A>
1271<PRE>1269<PRE>
1272void lua_close (void);1270void lua_close (void);
1273</PRE>1271</PRE>
@@ -1281,14 +1279,14 @@ If <CODE>lua_state</CODE> is already <CODE>NULL</CODE>, · 7 unmodified lines
1281<CODE>lua_close</CODE> has no effect.1279<CODE>lua_close</CODE> has no effect.
1282<P>1280<P>
1283If you are using multiple states,1281If you are using multiple states,
1284you may find useful the following function,1282you may find useful to define the following function,
1285which releases a given state:1283which releases a given state:
1286<PRE>1284<PRE>
1287void lua_freestate (lua_State *st) {1285 void lua_freestate (lua_State *st) {
1288 lua_State *old = lua_setstate(st);1286 lua_State *old = lua_setstate(st);
1289 lua_close();1287 lua_close();
1290 if (old != st) lua_setstate(old);1288 if (old != st) lua_setstate(old);
1291}1289 }
1292</PRE>1290</PRE>
1293<P>1291<P>
1294<A NAME="valuesCLua"></A>1292<A NAME="valuesCLua"></A>
@@ -1316,7 +1314,7 @@ int lua_isfunction (lua_Object object); · 21 unmodified lines
1316int lua_iscfunction (lua_Object object);1314int lua_iscfunction (lua_Object object);
1317int lua_isuserdata (lua_Object object);1315int lua_isuserdata (lua_Object object);
1318</PRE>1316</PRE>
1319All macros return 1 if the object is compatible with the given type,1317These functions return 1 if the object is compatible with the given type,
1320and 0 otherwise.1318and 0 otherwise.
1321The function <CODE>lua_isnumber</CODE> accepts numbers and numerical strings,1319The function <CODE>lua_isnumber</CODE> accepts numbers and numerical strings,
1322whereas1320whereas
@@ -1356,7 +1354,8 @@ but may contain other zeros in their body. · 33 unmodified lines
1356If you do not know whether a string may contain zeros,1354If you do not know whether a string may contain zeros,
1357you can use <CODE>lua_strlen</CODE> to get the actual length.1355you can use <CODE>lua_strlen</CODE> to get the actual length.
1358Because Lua has garbage collection,1356Because Lua has garbage collection,
1359there is no guarantee that such pointer will be valid after the block ends1357there is no guarantee that the pointer returned by <CODE>lua_getstring</CODE>
1358will be valid after the block ends
1360(see Section&nbsp;<A HREF="#GC">5.3</A>).1359(see Section&nbsp;<A HREF="#GC">5.3</A>).
1361<P>1360<P>
1362<CODE>lua_getcfunction</CODE> converts a <CODE>lua_Object</CODE> to a C function.1361<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
1415<P>1414<P>
1416The second structure, C2lua, is an abstract stack.1415The second structure, C2lua, is an abstract stack.
1417Pushing elements into this stack1416Pushing elements into this stack
1418is done with the following functions and macros:1417is done with the following functions:
1419<A NAME="lua_pushnumber"></A><A NAME="lua_pushlstring"></A><A NAME="lua_pushstring"></A>1418<A NAME="lua_pushnumber"></A><A NAME="lua_pushlstring"></A><A NAME="lua_pushstring"></A>
1420<A NAME="lua_pushcfunction"></A><A NAME="lua_pushusertag"></A>1419<A NAME="lua_pushcfunction"></A><A NAME="lua_pushusertag"></A>
1421<A NAME="lua_pushnil"></A><A NAME="lua_pushobject"></A>1420<A NAME="lua_pushnil"></A><A NAME="lua_pushobject"></A>
@@ -1433,7 +1432,7 @@ void lua_pushcfunction (lua_CFunction f); /* macro */ · 11 unmodified lines
1433All of them receive a C value,1432All of them receive a C value,
1434convert it to a corresponding <CODE>lua_Object</CODE>,1433convert it to a corresponding <CODE>lua_Object</CODE>,
1435and leave the result on the top of C2lua.1434and leave the result on the top of C2lua.
1436Particularly, functions <CODE>lua_pushlstring</CODE> and <CODE>lua_pushstring</CODE>1435In particular, functions <CODE>lua_pushlstring</CODE> and <CODE>lua_pushstring</CODE>
1437make an internal copy of the given string.1436make an internal copy of the given string.
1438Function <CODE>lua_pushstring</CODE> can only be used to push proper C strings1437Function <CODE>lua_pushstring</CODE> can only be used to push proper C strings
1439(that is, strings that do not contain zeros and end with a zero);1438(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
1518used in error messages and debug information.1517used in error messages and debug information.
1519If <CODE>name</CODE> is <CODE>NULL</CODE>,1518If <CODE>name</CODE> is <CODE>NULL</CODE>,
1520Lua gives a default name to the chunk.1519Lua gives a default name to the chunk.
1521In files this name is the file name,
1522and <CODE>lua_dostring</CODE> uses a small prefix
1523of the string as the chunk name.
1524<P>1520<P>
1525These functions return, in structure lua2C,1521These functions return, in structure lua2C,
1526any values eventually returned by the chunks.1522any values eventually returned by the chunks.
@@ -1565,7 +1561,7 @@ The function · 38 unmodified lines
1565<PRE>1561<PRE>
1566lua_Object lua_gettable (void);1562lua_Object lua_gettable (void);
1567</PRE>1563</PRE>
1568pops from the stack C2lua a table and an index,1564pops a table and an index from the stack C2lua,
1569and returns the contents of the table at that index.1565and returns the contents of the table at that index.
1570As in Lua, this operation may trigger a tag method.1566As in Lua, this operation may trigger a tag method.
1571To get the real value of any table index,1567To get the real value of any table index,
@@ -1579,7 +1575,7 @@ lua_Object lua_rawgettable (void); · 7 unmodified lines
1579To store a value in an index,1575To store a value in an index,
1580the program must push the table, the index,1576the program must push the table, the index,
1581and the value onto C2lua,1577and the value onto C2lua,
1582and then call the function:1578and then call the function
1583<A NAME="lua_settable"></A>1579<A NAME="lua_settable"></A>
1584<PRE>1580<PRE>
1585void lua_settable (void);1581void lua_settable (void);
@@ -1636,9 +1632,9 @@ equivalent to the Lua code: · 50 unmodified lines
1636 lua_pushnumber(4); /* 3rd argument */1632 lua_pushnumber(4); /* 3rd argument */
1637 lua_callfunction(lua_getglobal("f")); /* call Lua function */1633 lua_callfunction(lua_getglobal("f")); /* call Lua function */
1638 lua_pushobject(lua_getresult(1)); /* push first result of the call */1634 lua_pushobject(lua_getresult(1)); /* push first result of the call */
1639 lua_setglobal("a"); /* sets global variable 'a' */1635 lua_setglobal("a"); /* set global variable 'a' */
1640 lua_pushobject(lua_getresult(2)); /* push second result of the call */1636 lua_pushobject(lua_getresult(2)); /* push second result of the call */
1641 lua_setglobal("b"); /* sets global variable 'b' */1637 lua_setglobal("b"); /* set global variable 'b' */
1642</PRE>1638</PRE>
1643<P>1639<P>
1644Some special Lua functions have exclusive interfaces.1640Some special Lua functions have exclusive interfaces.
@@ -1651,19 +1647,11 @@ This function never returns. · 6 unmodified lines
1651If the C function has been called from Lua,1647If the C function has been called from Lua,
1652then the corresponding Lua execution terminates,1648then the corresponding Lua execution terminates,
1653as if an error had occurred inside Lua code.1649as if an error had occurred inside Lua code.
1654Otherwise, the whole program terminates with a call to <CODE>exit(1)</CODE>.1650Otherwise, the whole host program terminates with a call to <CODE>exit(1)</CODE>.
1655The <CODE>message</CODE> is passed to the error handler method.1651The <CODE>message</CODE> is passed to the error handler function,
1652<CODE>_ERRORMESSAGE</CODE>.
1656If <CODE>message</CODE> is <CODE>NULL</CODE>,1653If <CODE>message</CODE> is <CODE>NULL</CODE>,
1657the error handler method is not called.1654then <CODE>_ERRORMESSAGE</CODE> is not called.
1658<P>
1659The error handler method (see Section&nbsp;<A HREF="#error">4.9</A>) can be
1660changed with: <A NAME="lua_seterrormethod"></A>
1661<PRE>
1662lua_Object lua_seterrormethod (void);
1663</PRE>
1664This function sets the object at the top of C2lua
1665as the new error method,
1666and returns the old error method value.
1667<P>1655<P>
1668Tag methods can be changed with: <A NAME="lua_settagmethod"></A>1656Tag methods can be changed with: <A NAME="lua_settagmethod"></A>
1669<PRE>1657<PRE>
@@ -1722,12 +1710,13 @@ Like a Lua function, a C function called by Lua can also return · 52 unmodified lines
1722many results.1710many results.
1723<P>1711<P>
1724When a C function is created,1712When a C function is created,
1725it is possible to associate some <EM>upvalues</EM> to it;1713it is possible to associate some <EM>upvalues</EM> to it,
1714thus creating a C closure;
1726then these values are passed to the function whenever it is called,1715then these values are passed to the function whenever it is called,
1727as common arguments.1716as common arguments.
1728To associate upvalues to a function,1717To associate upvalues to a function,
1729first these values must be pushed on C2lua.1718first these values must be pushed on C2lua.
1730Then the function:1719Then the function
1731<A NAME="lua_pushcclosure"></A>1720<A NAME="lua_pushcclosure"></A>
1732<PRE>1721<PRE>
1733void lua_pushcclosure (lua_CFunction fn, int n);1722void lua_pushcclosure (lua_CFunction fn, int n);
@@ -1792,7 +1781,7 @@ The libraries, on the other hand, provide useful routines · 58 unmodified lines
1792that are implemented directly through the standard API.1781that are implemented directly through the standard API.
1793Therefore, they are not necessary to the language,1782Therefore, they are not necessary to the language,
1794and are provided as separate C modules.1783and are provided as separate C modules.
1795Currently there are three standard libraries:1784Currently, there are three standard libraries:
1796<UL>1785<UL>
1797<LI>string manipulation;1786<LI>string manipulation;
1798<LI>mathematical functions (sin, log, etc);1787<LI>mathematical functions (sin, log, etc);
@@ -1809,17 +1798,16 @@ and <CODE>lua_iolibopen</CODE>, declared in <CODE>lualib.h</CODE>. · 10 unmodified lines
1809<A NAME="6.1"></A>1798<A NAME="6.1"></A>
1810<H2>6.1 - Predefined Functions</H2> 1799<H2>6.1 - Predefined Functions</H2>
1811<P>1800<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>
1813<A NAME="pdf-call"></A>1802<A NAME="pdf-call"></A>
1814 1803
1815This function calls function <CODE>func</CODE> with1804Calls function <CODE>func</CODE> with
1816the arguments given by the table <CODE>arg</CODE>.1805the arguments given by the table <CODE>arg</CODE>.
1817The call is equivalent to1806The call is equivalent to
1818<PRE>1807<PRE>
1819 func(arg[1], arg[2], ..., arg[arg.n])1808 func(arg[1], arg[2], ..., arg[n])
1820</PRE>1809</PRE>
1821If <CODE>arg.n</CODE> is not defined,1810where <CODE>n</CODE> is the result of <CODE>getn(arg)</CODE> (see Section&nbsp;<A HREF="#getn">6.1</A>).
1822then Lua stops getting arguments at the first <B>nil</B> value.
1823<P>1811<P>
1824By default,1812By default,
1825all results from <CODE>func</CODE> are just returned by the call.1813all 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
1833<PRE>1821<PRE>
1834a = call(sin, {5}) --&gt; a = 0.0871557 = sin(5)1822a = call(sin, {5}) --&gt; a = 0.0871557 = sin(5)
1835a = call(max, {1,4,5; n=2}) --&gt; a = 4 (only 1 and 4 are arguments)1823a = call(max, {1,4,5; n=2}) --&gt; a = 4 (only 1 and 4 are arguments)
1824a = call(max, {1,4,5; n=2}, "p") --&gt; a = {4; n=1}
1836t = {x=1}1825t = {x=1}
1837a = call(next, {t,nil;n=2}, "p") --&gt; a={"x", 1; n=2}1826a = call(next, {t,nil;n=2}, "p") --&gt; a={"x", 1; n=2}
1838</PRE>1827</PRE>
@@ -1842,14 +1831,15 @@ if an error occurs during the function call, · 3 unmodified lines
1842the error is propagated.1831the error is propagated.
1843If the string <CODE>mode</CODE> contains <CODE>"x"</CODE>,1832If the string <CODE>mode</CODE> contains <CODE>"x"</CODE>,
1844then the call is <EM>protected</EM>.<A NAME="protected calls"></A>1833then the call is <EM>protected</EM>.<A NAME="protected calls"></A>
1845In this mode, function <CODE>call</CODE> does not generate an error,1834In this mode, function <CODE>call</CODE> does not propagate an error,
1846whatever happens during the call.1835regardless of what happens during the call.
1847Instead, it returns <B>nil</B> to signal the error1836Instead, it returns <B>nil</B> to signal the error
1848(besides calling the appropriated error method).1837(besides calling the appropriated error handler).
1849<P>1838<P>
1850If provided, <CODE>errmethod</CODE> is temporarily set as the error method,1839If provided,
1851while <CODE>func</CODE> runs.1840<CODE>errhandler</CODE> is temporarily set as the error function
1852As a particular case, if <CODE>errmethod</CODE> is <B>nil</B>,1841<CODE>_ERRORMESSAGE</CODE>, while <CODE>func</CODE> runs.
1842In particular, if <CODE>errhandler</CODE> is <B>nil</B>,
1853no error messages will be issued during the execution of the called function.1843no error messages will be issued during the execution of the called function.
1854<P>1844<P>
1855<h3> <TT>collectgarbage ([limit])</TT></h3><A NAME="collectgarbage"></A>1845<h3> <TT>collectgarbage ([limit])</TT></h3><A NAME="collectgarbage"></A>
@@ -1858,13 +1848,13 @@ Returns the number of objects collected. · 2 unmodified lines
1858An optional argument, <CODE>limit</CODE>, is a number that1848An optional argument, <CODE>limit</CODE>, is a number that
1859makes the next cycle occur only after that number of new1849makes the next cycle occur only after that number of new
1860objects have been created.1850objects have been created.
1861If absent, Lua uses an adaptive algorithm to set1851If <CODE>limit</CODE> is absent or equal to 0,
1862this limit.1852Lua uses an adaptive algorithm to set this limit.
1863<CODE>collectgarbage</CODE> is equivalent to1853<CODE>collectgarbage</CODE> is equivalent to
1864the API function <CODE>lua_collectgarbage</CODE>.1854the API function <CODE>lua_collectgarbage</CODE>.
1865<P>1855<P>
1866<h3> <TT>dofile (filename)</TT></h3><A NAME="dofile"></A>1856<h3> <TT>dofile (filename)</TT></h3><A NAME="dofile"></A>
1867This function receives a file name,1857Receives a file name,
1868opens the file, and executes the file contents as a Lua chunk,1858opens the file, and executes the file contents as a Lua chunk,
1869or as pre-compiled chunks.1859or as pre-compiled chunks.
1870When called without arguments,1860When called without arguments,
@@ -1877,7 +1867,7 @@ It issues an error when called with a non string argument. · 6 unmodified lines
1877<CODE>dofile</CODE> is equivalent to the API function <CODE>lua_dofile</CODE>.1867<CODE>dofile</CODE> is equivalent to the API function <CODE>lua_dofile</CODE>.
1878<P>1868<P>
1879<h3> <TT>dostring (string [, chunkname])</TT></h3><A NAME="dostring"></A>1869<h3> <TT>dostring (string [, chunkname])</TT></h3><A NAME="dostring"></A>
1880This function executes a given string as a Lua chunk.1870Executes a given string as a Lua chunk.
1881If there is any error executing the string,1871If there is any error executing the string,
1882<CODE>dostring</CODE> returns <B>nil</B>.1872<CODE>dostring</CODE> returns <B>nil</B>.
1883Otherwise, it returns the values returned by the chunk,1873Otherwise, it returns the values returned by the chunk,
@@ -1893,7 +1883,7 @@ Returns a new tag. · 9 unmodified lines
1893<CODE>newtag</CODE> is equivalent to the API function <CODE>lua_newtag</CODE>.1883<CODE>newtag</CODE> is equivalent to the API function <CODE>lua_newtag</CODE>.
1894<P>1884<P>
1895<h3> <TT>next (table, index)</TT></h3><A NAME="next"></A>1885<h3> <TT>next (table, index)</TT></h3><A NAME="next"></A>
1896This function allows a program to traverse all fields of a table.1886Allows a program to traverse all fields of a table.
1897Its first argument is a table and its second argument1887Its first argument is a table and its second argument
1898is an index in this table.1888is an index in this table.
1899It returns the next index of the table and the1889It 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
1911Therefore, the function only considers fields with non <B>nil</B> values.1901Therefore, the function only considers fields with non <B>nil</B> values.
1912The order in which the indices are enumerated is not specified,1902The order in which the indices are enumerated is not specified,
1913<EM>even for numeric indices</EM>1903<EM>even for numeric indices</EM>
1914(to traverse a table in numeric order, use a counter).1904(to traverse a table in numeric order,
1915If the table is modified in any way during a traversal,1905use a counter or the function <CODE>foreachi</CODE>).
1906If the table indices are modified in any way during a traversal,
1916the semantics of <CODE>next</CODE> is undefined.1907the semantics of <CODE>next</CODE> is undefined.
1917<P>1908<P>
1918This function cannot be written with the standard API.1909This function cannot be written with the standard API.
@@ -1925,67 +1916,35 @@ or <B>nil</B> to get a first name. · 6 unmodified lines
1925Similarly to <CODE>next</CODE>, it returns the name of another variable1916Similarly to <CODE>next</CODE>, it returns the name of another variable
1926and its value,1917and its value,
1927or <B>nil</B> if there are no more variables.1918or <B>nil</B> if there are no more variables.
1928There can be no assignments to global variables during the traversal;1919There can be no creation of new global variables during the traversal;
1929otherwise the semantics of <CODE>nextvar</CODE> is undefined.1920otherwise the semantics of <CODE>nextvar</CODE> is undefined.
1930<P>1921<P>
1931This function cannot be written with the standard API.1922This function cannot be written with the standard API.
1932<P>1923<P>
1933<h3> <TT>foreach (table, function)</TT></h3><A NAME="foreach"></A>
1934Executes the given <CODE>function</CODE> over all elements of <CODE>table</CODE>.
1935For each element, the function is called with the index and
1936respective value as arguments.
1937If the function returns any non-<B>nil</B> value,
1938the loop is broken, and the value is returned
1939as the final value of <CODE>foreach</CODE>.
1940<P>
1941This function could be defined in Lua:
1942<PRE>
1943function 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
1950end
1951</PRE>
1952<P>
1953<h3> <TT>foreachvar (function)</TT></h3><A NAME="foreachvar"></A>
1954Executes <CODE>function</CODE> over all global variables.
1955For each variable,
1956the function is called with its name and its value as arguments.
1957If the function returns any non-nil value,
1958the loop is broken, and the value is returned
1959as the final value of <CODE>foreachvar</CODE>.
1960<P>
1961This function could be defined in Lua:
1962<PRE>
1963function 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
1970end
1971</PRE>
1972<P>
1973<h3> <TT>tostring (e)</TT></h3><A NAME="tostring"></A>1924<h3> <TT>tostring (e)</TT></h3><A NAME="tostring"></A>
1974This function receives an argument of any type and1925Receives an argument of any type and
1975converts it to a string in a reasonable format.1926converts it to a string in a reasonable format.
1976For complete control on how numbers are converted,1927For complete control on how numbers are converted,
1977use function <CODE>format</CODE>.1928use function <CODE>format</CODE>.
1978<P>1929<P>
1979<h3> <TT>print (e1, e2, ...)</TT></h3><A NAME="print"></A>1930<h3> <TT>print (e1, e2, ...)</TT></h3><A NAME="print"></A>
1980This function receives any number of arguments,1931Receives any number of arguments,
1981and prints their values using the strings returned by <CODE>tostring</CODE>.1932and prints their values using the strings returned by <CODE>tostring</CODE>.
1982This function is not intended for formatted output,1933This function is not intended for formatted output,
1983but only as a quick way to show a value,1934but only as a quick way to show a value,
1984for instance for error messages or debugging.1935for instance for debugging.
1985See Section&nbsp;<A HREF="#libio">6.4</A> for functions for formatted output.1936See Section&nbsp;<A HREF="#libio">6.4</A> for functions for formatted output.
1986<P>1937<P>
1938<A NAME="alert"></A>
1939<h3> <TT>_ALERT (message)</TT></h3><A NAME="alert"></A>
1940Prints its only string argument to <A NAME="stderr"><TT>stderr</TT></A>.
1941All error messages in Lua are printed through this function.
1942Therefore, a program may redefine it
1943to change the way such messages are shown
1944(for instance, for systems without <CODE>stderr</CODE>).
1945<P>
1987<h3> <TT>tonumber (e [, base])</TT></h3><A NAME="tonumber"></A>1946<h3> <TT>tonumber (e [, base])</TT></h3><A NAME="tonumber"></A>
1988This function receives one argument,1947Receives one argument,
1989and tries to convert it to a number.1948and tries to convert it to a number.
1990If the argument is already a number or a string convertible1949If the argument is already a number or a string convertible
1991to a number, then <CODE>tonumber</CODE> returns that number;1950to a number, then <CODE>tonumber</CODE> returns that number;
@@ -2002,7 +1961,7 @@ In other bases, only integers are accepted. · 10 unmodified lines
2002<P>1961<P>
2003<A NAME="pdf-type"></A>1962<A NAME="pdf-type"></A>
2004<h3> <TT>type (v)</TT></h3><A NAME="type"></A>1963<h3> <TT>type (v)</TT></h3><A NAME="type"></A>
2005This function allows Lua to test the type of a value.1964Allows Lua to test the type of a value.
2006It receives one argument, and returns its type, coded as a string.1965It receives one argument, and returns its type, coded as a string.
2007The possible results of this function are1966The possible results of this function are
2008<CODE>"nil"</CODE> (a string, not the value <B>nil</B>),1967<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
2013and <CODE>"userdata"</CODE>.1972and <CODE>"userdata"</CODE>.
2014<P>1973<P>
2015<h3> <TT>tag (v)</TT></h3><A NAME="tag"></A>1974<h3> <TT>tag (v)</TT></h3><A NAME="tag"></A>
2016This function allows Lua to test the tag of a value (see Section&nbsp;<A HREF="#TypesSec">3</A>).1975Allows Lua to test the tag of a value (see Section&nbsp;<A HREF="#TypesSec">3</A>).
2017It receives one argument, and returns its tag (a number).1976It receives one argument, and returns its tag (a number).
2018<CODE>tag</CODE> is equivalent to the API function <CODE>lua_tag</CODE>.1977<CODE>tag</CODE> is equivalent to the API function <CODE>lua_tag</CODE>.
2019<P>1978<P>
2020<h3> <TT>settag (t, tag)</TT></h3><A NAME="settag"></A>1979<h3> <TT>settag (t, tag)</TT></h3><A NAME="settag"></A>
2021This function sets the tag of a given table (see Section&nbsp;<A HREF="#TypesSec">3</A>).1980Sets the tag of a given table (see Section&nbsp;<A HREF="#TypesSec">3</A>).
2022<CODE>tag</CODE> must be a value created with <CODE>newtag</CODE>1981<CODE>tag</CODE> must be a value created with <CODE>newtag</CODE>
2023(see Section&nbsp;<A HREF="#pdf-newtag">6.1</A>).1982(see Section&nbsp;<A HREF="#pdf-newtag">6.1</A>).
2024It returns the value of its first argument (the table).1983It 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
2027<P>1986<P>
2028<P>1987<P>
2029<h3> <TT>assert (v [, message])</TT></h3><A NAME="assert"></A>1988<h3> <TT>assert (v [, message])</TT></h3><A NAME="assert"></A>
2030This function issues an <EM>``assertion failed!''</EM> error1989Issues an <EM>``assertion failed!''</EM> error
2031when its argument is <B>nil</B>.1990when its argument is <B>nil</B>.
2032This function is equivalent to the following Lua function:1991This function is equivalent to the following Lua function:
2033<PRE>1992<PRE>
2034function assert (v, m)1993 function assert (v, m)
2035 if not v then1994 if not v then
2036 m = m or ""1995 m = m or ""
2037 error("assertion failed! " .. m)1996 error("assertion failed! " .. m)
2038 end1997 end
2039end1998 end
2040</PRE>1999</PRE>
2041<P>2000<P>
2042<A NAME="pdf-error"></A>2001<A NAME="pdf-error"></A>
2043<h3> <TT>error (message)</TT></h3><A NAME="error"></A>2002<h3> <TT>error (message)</TT></h3><A NAME="error"></A>
2044This function calls the error handler and then terminates2003Calls the error handler and then terminates
2045the last protected function called2004the last protected function called
2046(in&nbsp;C: <CODE>lua_dofile</CODE>, <CODE>lua_dostring</CODE>,2005(in&nbsp;C: <CODE>lua_dofile</CODE>, <CODE>lua_dostring</CODE>,
2047<CODE>lua_dobuffer</CODE>, or <CODE>lua_callfunction</CODE>;2006<CODE>lua_dobuffer</CODE>, or <CODE>lua_callfunction</CODE>;
@@ -2064,7 +2023,7 @@ without invoking any tag method. · 16 unmodified lines
2064and <CODE>value</CODE> is any Lua value.2023and <CODE>value</CODE> is any Lua value.
2065<P>2024<P>
2066<h3> <TT>rawsetglobal (name, value)</TT></h3><A NAME="rawsetglobal"></A>2025<h3> <TT>rawsetglobal (name, value)</TT></h3><A NAME="rawsetglobal"></A>
2067This function assigns the given value to a global variable.2026Assigns the given value to a global variable.
2068The string <CODE>name</CODE> does not need to be a2027The string <CODE>name</CODE> does not need to be a
2069syntactically valid variable name.2028syntactically valid variable name.
2070Therefore,2029Therefore,
@@ -2073,7 +2032,7 @@ this function can set global variables with strange names like · 2 unmodified lines
2073Function <CODE>rawsetglobal</CODE> returns the value of its second argument.2032Function <CODE>rawsetglobal</CODE> returns the value of its second argument.
2074<P>2033<P>
2075<h3> <TT>setglobal (name, value)</TT></h3><A NAME="setglobal"></A>2034<h3> <TT>setglobal (name, value)</TT></h3><A NAME="setglobal"></A>
2076This function assigns the given value to a global variable,2035Assigns the given value to a global variable,
2077or calls a tag method.2036or calls a tag method.
2078Its full semantics is explained in Section&nbsp;<A HREF="#tag-method">4.8</A>.2037Its full semantics is explained in Section&nbsp;<A HREF="#tag-method">4.8</A>.
2079The string <CODE>name</CODE> does not need to be a2038The string <CODE>name</CODE> does not need to be a
@@ -2081,42 +2040,197 @@ syntactically valid variable name. · 1 unmodified line
2081Function <CODE>setglobal</CODE> returns the value of its second argument.2040Function <CODE>setglobal</CODE> returns the value of its second argument.
2082<P>2041<P>
2083<h3> <TT>rawgetglobal (name)</TT></h3><A NAME="rawgetglobal"></A>2042<h3> <TT>rawgetglobal (name)</TT></h3><A NAME="rawgetglobal"></A>
2084This function retrieves the value of a global variable.2043Retrieves the value of a global variable.
2085The string <CODE>name</CODE> does not need to be a2044The string <CODE>name</CODE> does not need to be a
2086syntactically valid variable name.2045syntactically valid variable name.
2087<P>2046<P>
2088<h3> <TT>getglobal (name)</TT></h3><A NAME="getglobal"></A>2047<h3> <TT>getglobal (name)</TT></h3><A NAME="getglobal"></A>
2089This function retrieves the value of a global variable,2048Retrieves the value of a global variable,
2090or calls a tag method.2049or calls a tag method.
2091Its full semantics is explained in Section&nbsp;<A HREF="#tag-method">4.8</A>.2050Its full semantics is explained in Section&nbsp;<A HREF="#tag-method">4.8</A>.
2092The string <CODE>name</CODE> does not need to be a2051The string <CODE>name</CODE> does not need to be a
2093syntactically valid variable name.2052syntactically valid variable name.
2094<P>2053<P>
2095<h3> <TT>seterrormethod (newmethod)</TT></h3>
2096<A NAME="pdf-seterrormethod"></A>
2097
2098Sets the error handler (see Section&nbsp;<A HREF="#error">4.9</A>).
2099<CODE>newmethod</CODE> must be a function or <B>nil</B>,
2100in which case the error handler does nothing.
2101Returns the old error handler.
2102<P>
2103<h3> <TT>settagmethod (tag, event, newmethod)</TT></h3>2054<h3> <TT>settagmethod (tag, event, newmethod)</TT></h3>
2104<A NAME="settagmethod"></A>2055<A NAME="settagmethod"></A>
2105This function sets a new tag method to the given pair <EM>(tag, event)</EM>.2056Sets a new tag method to the given pair <EM>(tag, event)</EM>.
2106It returns the old method.2057It returns the old method.
2107If <CODE>newmethod</CODE> is <B>nil</B>,2058If <CODE>newmethod</CODE> is <B>nil</B>,
2108<CODE>settagmethod</CODE> restores the default behavior for the given event.2059<CODE>settagmethod</CODE> restores the default behavior for the given event.
2109<P>2060<P>
2110<h3> <TT>gettagmethod (tag, event)</TT></h3>2061<h3> <TT>gettagmethod (tag, event)</TT></h3>
2111<A NAME="gettagmethod"></A>2062<A NAME="gettagmethod"></A>
2112This function returns the current tag method2063Returns the current tag method
2113for a given pair <EM>(tag, event)</EM>.2064for a given pair <EM>(tag, event)</EM>.
2114<P>2065<P>
2115<h3> <TT>copytagmethods (tagto, tagfrom)</TT></h3>2066<h3> <TT>copytagmethods (tagto, tagfrom)</TT></h3>
2116<A NAME="copytagmethods"></A>2067<A NAME="copytagmethods"></A>
2117This function copies all tag methods from one tag to another;2068Copies all tag methods from one tag to another;
2118it returns <CODE>tagto</CODE>.2069it returns <CODE>tagto</CODE>.
2119<P>2070<P>
2071<A NAME="getn"></A>
2072<h3> <TT>getn (table)</TT></h3><A NAME="getn"></A>
2073Returns the ``size'' of a table, when seen as a list.
2074If the table has an <CODE>n</CODE> field with a numeric value,
2075this is its ``size''.
2076Otherwise, the size is the largest numerical index with a non-nil
2077value in the table.
2078This 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>
2094Executes the given <CODE>function</CODE> over all elements of <CODE>table</CODE>.
2095For each element, the function is called with the index and
2096respective value as arguments.
2097If the function returns any non-<B>nil</B> value,
2098the loop is broken, and the value is returned
2099as the final value of <CODE>foreach</CODE>.
2100<P>
2101This 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>
2115Executes the given <CODE>function</CODE> over the
2116numerical indices of <CODE>table</CODE>.
2117For each index, the function is called with the index and
2118respective value as arguments.
2119Indices are visited in sequential order,
2120from 1 to <CODE>n</CODE>,
2121where <CODE>n</CODE> is the result of <CODE>getn(table)</CODE> (see Section&nbsp;<A HREF="#getn">6.1</A>).
2122If the function returns any non-<B>nil</B> value,
2123the loop is broken, and the value is returned
2124as the final value of <CODE>foreachi</CODE>.
2125<P>
2126This 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>
2139Executes <CODE>function</CODE> over all global variables.
2140For each variable,
2141the function is called with its name and its value as arguments.
2142If the function returns any non-nil value,
2143the loop is broken, and the value is returned
2144as the final value of <CODE>foreachvar</CODE>.
2145<P>
2146This 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>
2160Inserts element <CODE>value</CODE> at table position <CODE>pos</CODE>,
2161shifting other elements to open space.
2162The 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>))
2164so that a call <CODE>tinsert(t,x)</CODE> inserts <CODE>x</CODE> at the end
2165of table <CODE>t</CODE>.
2166<P>
2167This function also sets or increments the field <CODE>n</CODE> of the table,
2168to <CODE>n+1</CODE>.
2169<P>
2170This function is equivalent to the following Lua function,
2171except 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>
2192Removes from <CODE>table</CODE> the element at position <CODE>pos</CODE>,
2193shifting other elements to close the space.
2194Returns the value of the removed element.
2195The 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>)),
2197so that a call <CODE>tremove(t)</CODE> removes the last element
2198of table <CODE>t</CODE>.
2199<P>
2200This function also sets or decrements the field <CODE>n</CODE> of the table,
2201to <CODE>n-1</CODE>.
2202<P>
2203This function is equivalent to the following Lua function,
2204except 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>
2222Sorts table elements in a given order, <EM>in-place</EM>,
2223from <CODE>table[1]</CODE> to <CODE>table[n]</CODE>,
2224where <CODE>n</CODE> is the result of <CODE>getn(table)</CODE> (see Section&nbsp;<A HREF="#getn">6.1</A>).
2225If <CODE>comp</CODE> is given,
2226it must be a function that receives two table elements,
2227and 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).
2229If <CODE>comp</CODE> is not given,
2230the standard <CODE>&lt;</CODE> Lua operator is used instead.
2231<P>
2232Function <CODE>sort</CODE> returns the (sorted) table.
2233<P>
2120<P>2234<P>
2121<A NAME="6.2"></A>2235<A NAME="6.2"></A>
2122<H2>6.2 - String Manipulation</H2>2236<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
2127<P>2241<P>
2128<h3> <TT>strfind (str, pattern [, init [, plain]])</TT></h3>2242<h3> <TT>strfind (str, pattern [, init [, plain]])</TT></h3>
2129<A NAME="strfind"></A>2243<A NAME="strfind"></A>
2130This function looks for the first <EM>match</EM> of2244Looks for the first <EM>match</EM> of
2131<CODE>pattern</CODE> in <CODE>str</CODE>.2245<CODE>pattern</CODE> in <CODE>str</CODE>.
2132If it finds one, then it returns the indices on <CODE>str</CODE>2246If it finds one, then it returns the indices on <CODE>str</CODE>
2133where this occurrence starts and ends;2247where this occurrence starts and ends;
@@ -2203,7 +2317,7 @@ Note that numerical codes are not necessarily portable across platforms. · 69 unmodified lines
2203<h3> <TT>format (formatstring, e1, e2, ...)</TT></h3><A NAME="format"></A>2317<h3> <TT>format (formatstring, e1, e2, ...)</TT></h3><A NAME="format"></A>
2204<A NAME="format"></A>2318<A NAME="format"></A>
2205 2319
2206This function returns a formatted version of its variable number of arguments2320Returns a formatted version of its variable number of arguments
2207following the description given in its first argument (which must be a string).2321following the description given in its first argument (which must be a string).
2208The format string follows the same rules as the <CODE>printf</CODE> family of2322The format string follows the same rules as the <CODE>printf</CODE> family of
2209standard C functions.2323standard C functions.
@@ -2212,9 +2326,8 @@ The only differences are that the options/modifiers · 2 unmodified lines
2212and <CODE>h</CODE> are not supported,2326and <CODE>h</CODE> are not supported,
2213and there is an extra option, <CODE>q</CODE>.2327and there is an extra option, <CODE>q</CODE>.
2214This option formats a string in a form suitable to be safely read2328This option formats a string in a form suitable to be safely read
2215back by the Lua interpreter;2329back by the Lua interpreter:
2216that is,2330The string is written between double quotes,
2217the string is written between double quotes,
2218and all double quotes, returns and backslashes in the string2331and all double quotes, returns and backslashes in the string
2219are correctly escaped when written.2332are correctly escaped when written.
2220For instance, the call2333For 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
2241<CODE>g</CODE>, <CODE>G</CODE>, <CODE>i</CODE>, <CODE>o</CODE>, <CODE>u</CODE>, <CODE>X</CODE>, and <CODE>x</CODE> all2354<CODE>g</CODE>, <CODE>G</CODE>, <CODE>i</CODE>, <CODE>o</CODE>, <CODE>u</CODE>, <CODE>X</CODE>, and <CODE>x</CODE> all
2242expect a number as argument,2355expect a number as argument,
2243whereas <CODE>q</CODE> and <CODE>s</CODE> expect a string.2356whereas <CODE>q</CODE> and <CODE>s</CODE> expect a string.
2244Note that the <CODE>*</CODE> modifier can be simulated by building2357The <CODE>*</CODE> modifier can be simulated by building
2245the appropriate format string.2358the appropriate format string.
2246For example, <CODE>"%*g"</CODE> can be simulated with2359For example, <CODE>"%*g"</CODE> can be simulated with
2247<CODE>"%"..width.."g"</CODE>.2360<CODE>"%"..width.."g"</CODE>.
@@ -2273,30 +2386,29 @@ the maximum number of substitutions to occur. · 25 unmodified lines
2273For instance, when <CODE>n</CODE> is 1 only the first occurrence of2386For instance, when <CODE>n</CODE> is 1 only the first occurrence of
2274<CODE>pat</CODE> is replaced.2387<CODE>pat</CODE> is replaced.
2275<P>2388<P>
2276See some examples below:2389Here are some examples:
2277<PRE>2390<PRE>
2278 x = gsub("hello world", "(%w%w*)", "%1 %1")2391 x = gsub("hello world", "(%w+)", "%1 %1")
2279 --&gt; x="hello hello world world"2392 --&gt; x="hello hello world world"
2280<P>2393<P>
2281 x = gsub("hello world", "(%w%w*)", "%1 %1", 1)2394 x = gsub("hello world", "(%w+)", "%1 %1", 1)
2282 --&gt; x="hello hello world"2395 --&gt; x="hello hello world"
2283<P>2396<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")
2285 --&gt; x="world hello Lua from"2398 --&gt; x="world hello Lua from"
2286<P>2399<P>
2287 x = gsub("home = $HOME, user = $USER", "$(%w%w*)", getenv)2400 x = gsub("home = $HOME, user = $USER", "%$(%w+)", getenv)
2288 --&gt; x="home = /home/roberto, user = roberto" (for instance)2401 --&gt; x="home = /home/roberto, user = roberto" (for instance)
2289<P>2402<P>
2290 x = gsub("4+5 = $return 4+5$", "$(.-)%$", dostring)2403 x = gsub("4+5 = $return 4+5$", "%$(.-)%$", dostring)
2291 --&gt; x="4+5 = 9"2404 --&gt; x="4+5 = 9"
2292<P>2405<P>
2293 local t = {name="lua", version="3.1"}2406 local t = {name="lua", version="3.2"}
2294 x = gsub("$name - $version", "$(%w%w*)", function (v) return %t[v] end)2407 x = gsub("$name - $version", "%$(%w+)", function (v) return %t[v] end)
2295 --&gt; x="lua - 3.1"2408 --&gt; x="lua - 3.2"
2296<P>2409<P>
2297 t = {n=0}2410 t = {n=0}
2298 gsub("first second word", "(%w%w*)",2411 gsub("first second word", "(%w+)", function (w) tinsert(%t, w) end)
2299 function (w) %t.n = %t.n+1; %t[%t.n] = w end)
2300 --&gt; t={"first", "second", "word"; n=3}2412 --&gt; t={"first", "second", "word"; n=3}
2301</PRE>2413</PRE>
2302<P>2414<P>
@@ -2308,24 +2420,25 @@ See some examples below: · 5 unmodified lines
2308a <A NAME="character class"><EM>character class</EM></A> is used to represent a set of characters.2420a <A NAME="character class"><EM>character class</EM></A> is used to represent a set of characters.
2309The following combinations are allowed in describing a character class:2421The following combinations are allowed in describing a character class:
2310<DL>2422<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>)
2312- represents the character <EM>x</EM> itself.2425- represents the character <EM>x</EM> itself.
2313<DT><B><TT>.</TT></B><DD> - (a dot) represents all characters.2426<DT><B><TT>.</TT></B><DD> - (a dot) represents all characters.
2314<DT><B><TT>%a</TT></B><DD> - represents all letters.2427<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.
2316<DT><B><TT>%d</TT></B><DD> - represents all digits.2429<DT><B><TT>%d</TT></B><DD> - represents all digits.
2317<DT><B><TT>%D</TT></B><DD> - represents all non digits.
2318<DT><B><TT>%l</TT></B><DD> - represents all lower case letters.2430<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.
2320<DT><B><TT>%s</TT></B><DD> - represents all space characters.2432<DT><B><TT>%s</TT></B><DD> - represents all space characters.
2321<DT><B><TT>%S</TT></B><DD> - represents all non space characters.
2322<DT><B><TT>%u</TT></B><DD> - represents all upper case letters.2433<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.
2324<DT><B><TT>%w</TT></B><DD> - represents all alphanumeric characters.2434<DT><B><TT>%w</TT></B><DD> - represents all alphanumeric characters.
2325<DT><B><TT>%W</TT></B><DD> - represents all non alphanumeric characters.2435<DT><B><TT>%x</TT></B><DD> - represents all hexa-decimal digits.
2326<DT><B><TT>%</TT><EM>x</EM></B><DD> (where <EM>x</EM> is any non alphanumeric character) -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) -
2327represents the character <EM>x</EM>.2438represents the character <EM>x</EM>.
2328This is the standard way to escape the magic characters <CODE>()%.[*-?</CODE>.2439This is the standard way to escape the magic characters <CODE>()%.[]*-?</CODE>.
2440It is strongly recommended that any control character (even the non magic),
2441when used to represent itself in a pattern, should be preceded by a <CODE>%</CODE>.
2329<DT><B><TT>[char-set</TT></B>]<DD> -2442<DT><B><TT>[char-set</TT></B>]<DD> -
2330Represents the class which is the union of all2443Represents the class which is the union of all
2331characters in char-set.2444characters in char-set.
@@ -2343,13 +2456,16 @@ E.g., assuming an <EM>ascii</EM> character set, · 11 unmodified lines
2343represents the complement of char-set,2456represents the complement of char-set,
2344where char-set is interpreted as above.2457where char-set is interpreted as above.
2345</DL>2458</DL>
2459For all classes represented by single letters (<CODE>%a</CODE>, <CODE>%c</CODE>, ...),
2460the correspondent upper-case letter represents the complement of the class.
2461For instance, <CODE>%S</CODE> represents all non-space characters.
2346<P>2462<P>
2347The definitions of letter, space, etc. depend on the current locale.2463The definitions of letter, space, etc. depend on the current locale.
2348In particular, the class <CODE>[a-z]</CODE> may not be equivalent to <CODE>%l</CODE>.2464In particular, the class <CODE>[a-z]</CODE> may not be equivalent to <CODE>%l</CODE>.
2349The second form should be preferred for more portable programs.2465The second form should be preferred for more portable programs.
2350<P>2466<P>
2351<H4>Pattern Item:</H4>2467<H4>Pattern Item:</H4>
2352a <A NAME="pattern item"><EM>pattern item</EM></A> may be:2468a <A NAME="pattern item"><EM>pattern item</EM></A> may be
2353<UL>2469<UL>
2354<LI>2470<LI>
2355a single character class,2471a single character class,
@@ -2357,12 +2473,16 @@ which matches any single character in the class; · 1 unmodified line
2357<LI>2473<LI>
2358a single character class followed by <CODE>*</CODE>,2474a single character class followed by <CODE>*</CODE>,
2359which matches 0 or more repetitions of characters in the class.2475which matches 0 or more repetitions of characters in the class.
2360These repetition items will always match the longest possible sequence.2476These repetition items will always match the longest possible sequence;
2477<LI>
2478a single character class followed by <CODE>+</CODE>,
2479which matches 1 or more repetitions of characters in the class.
2480These repetition items will always match the longest possible sequence;
2361<LI>2481<LI>
2362a single character class followed by <CODE>-</CODE>,2482a single character class followed by <CODE>-</CODE>,
2363which also matches 0 or more repetitions of characters in the class.2483which also matches 0 or more repetitions of characters in the class.
2364Unlike <CODE>*</CODE>,2484Unlike <CODE>*</CODE>,
2365these repetition items will always match the shortest possible sequence.2485these repetition items will always match the shortest possible sequence;
2366<LI>2486<LI>
2367a single character class followed by <CODE>?</CODE>,2487a single character class followed by <CODE>?</CODE>,
2368which matches 0 or 1 occurrence of a character in the class;2488which 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
2441returns a pseudo-random real number in the range <I>[0,1)</I>.2561returns a pseudo-random real number in the range <I>[0,1)</I>.
2442When called with a number <I>n</I>,2562When called with a number <I>n</I>,
2443<CODE>random</CODE> returns a pseudo-random integer in the range <I>[1,n]</I>.2563<CODE>random</CODE> returns a pseudo-random integer in the range <I>[1,n]</I>.
2564When 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>.
2444<P>2566<P>
2445<P>2567<P>
2446<A NAME="libio"></A>2568<A NAME="libio"></A>
2447<A NAME="6.4"></A>2569<A NAME="6.4"></A>
2448<H2>6.4 - I/O Facilities</H2> 2570<H2>6.4 - I/O Facilities</H2>
2449<P>2571<P>
2450All input and output operations in Lua are done over two2572All input and output operations in Lua are done, by default,
2451<A NAME="file handles"><EM>file handles</EM></A>, one for reading and one for writing.2573over two <A NAME="file handles"><EM>file handles</EM></A>, one for reading and one for writing.
2452These handles are stored in two Lua global variables,2574These handles are stored in two Lua global variables,
2453called <CODE>_INPUT</CODE> and <CODE>_OUTPUT</CODE>.2575called <CODE>_INPUT</CODE> and <CODE>_OUTPUT</CODE>.
2454The global variables2576The global variables
@@ -2461,12 +2583,39 @@ Initially, <CODE>_INPUT=_STDIN</CODE> and <CODE>_OUTPUT=_STDOUT</CODE>. · 6 unmodified lines
2461<P>2583<P>
2462A file handle is a userdata containing the file stream <CODE>FILE*</CODE>,2584A file handle is a userdata containing the file stream <CODE>FILE*</CODE>,
2463and with a distinctive tag created by the I/O library.2585and with a distinctive tag created by the I/O library.
2464<P>2586Whenever a file handle is collected by the garbage collector,
2587its correspondent stream is automatically closed.
2465<P>2588<P>
2466Unless otherwise stated,2589Unless otherwise stated,
2467all I/O functions return <B>nil</B> on failure and2590all I/O functions return <B>nil</B> on failure and
2468some value different from <B>nil</B> on success.2591some value different from <B>nil</B> on success.
2469<P>2592<P>
2593<h3> <TT>openfile (filename, mode)</TT></h3><A NAME="openfile"></A>
2594<P>
2595This function opens a file,
2596in the mode specified in the string <CODE>mode</CODE>.
2597It returns a new file handle,
2598or, in case of errors, <B>nil</B> plus a string describing the error.
2599This function does not modify either <CODE>_INPUT</CODE> or <CODE>_OUTPUT</CODE>.
2600<P>
2601The 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>
2611The string mode may also have a <CODE>b</CODE> at the end,
2612which 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>
2616This function closes the given file.
2617It does not modify either <CODE>_INPUT</CODE> or <CODE>_OUTPUT</CODE>.
2618<P>
2470<h3> <TT>readfrom (filename)</TT></h3><A NAME="readfrom"></A>2619<h3> <TT>readfrom (filename)</TT></h3><A NAME="readfrom"></A>
2471<P>2620<P>
2472This function may be called in two ways.2621This function may be called in two ways.
@@ -2519,52 +2668,81 @@ usually limited and depends on the system. · 46 unmodified lines
2519<P>2668<P>
2520<h3> <TT>appendto (filename)</TT></h3><A NAME="appendto"></A>2669<h3> <TT>appendto (filename)</TT></h3><A NAME="appendto"></A>
2521<P>2670<P>
2522This function opens a file named <CODE>filename</CODE> and sets it as the2671Opens a file named <CODE>filename</CODE> and sets it as the
2523value of <CODE>_OUTPUT</CODE>.2672value of <CODE>_OUTPUT</CODE>.
2524Unlike the <CODE>writeto</CODE> operation,2673Unlike the <CODE>writeto</CODE> operation,
2525this function does not erase any previous content of the file.2674this function does not erase any previous content of the file.
2526If this function fails, it returns <B>nil</B>,2675If this function fails, it returns <B>nil</B>,
2527plus a string describing the error.2676plus a string describing the error.
2528<P>2677<P>
2529Note that function <CODE>writeto</CODE> is
2530available to close an output file opened by <CODE>appendto</CODE>.
2531<P>
2532<h3> <TT>remove (filename)</TT></h3><A NAME="remove"></A>2678<h3> <TT>remove (filename)</TT></h3><A NAME="remove"></A>
2533<P>2679<P>
2534This function deletes the file with the given name.2680Deletes the file with the given name.
2535If this function fails, it returns <B>nil</B>,2681If this function fails, it returns <B>nil</B>,
2536plus a string describing the error.2682plus a string describing the error.
2537<P>2683<P>
2538<h3> <TT>rename (name1, name2)</TT></h3><A NAME="rename"></A>2684<h3> <TT>rename (name1, name2)</TT></h3><A NAME="rename"></A>
2539<P>2685<P>
2540This function renames file named <CODE>name1</CODE> to <CODE>name2</CODE>.2686Renames file named <CODE>name1</CODE> to <CODE>name2</CODE>.
2687If this function fails, it returns <B>nil</B>,
2688plus a string describing the error.
2689<P>
2690<h3> <TT>flush ([filehandle])</TT></h3><A NAME="flush"></A>
2691<P>
2692Saves any written data to the given file.
2693If <CODE>filehandle</CODE> is not specified,
2694flushes all open files.
2541If this function fails, it returns <B>nil</B>,2695If this function fails, it returns <B>nil</B>,
2542plus a string describing the error.2696plus a string describing the error.
2543<P>2697<P>
2698<h3> <TT>seek (filehandle [, whence] [, offset])</TT></h3><A NAME="seek"></A>
2699<P>
2700Sets and gets the file position,
2701measured in bytes from the beginning of the file,
2702to the position given by <CODE>offset</CODE> plus a base
2703specified 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>
2709In case of success, function <CODE>seek</CODE> returns the final file position,
2710measured in bytes from the beginning of the file.
2711If the call fails, it returns <B>nil</B>,
2712plus a string describing the error.
2713<P>
2714The default value for <CODE>whence</CODE> is <CODE>"cur"</CODE>,
2715and for <CODE>offset</CODE> is 0.
2716Therefore, the call <CODE>seek(file)</CODE> returns the current
2717file position, without changing it;
2718the call <CODE>seek(file, "set")</CODE> sets the position to the
2719beginning of the file (and returns 0);
2720and the call <CODE>seek(file, "end")</CODE> sets the position to the
2721end of the file, and returns its size.
2722<P>
2544<h3> <TT>tmpname ()</TT></h3><A NAME="tmpname"></A>2723<h3> <TT>tmpname ()</TT></h3><A NAME="tmpname"></A>
2545<P>2724<P>
2546This function returns a string with a file name that can safely2725Returns a string with a file name that can safely
2547be used for a temporary file.2726be used for a temporary file.
2548The file must be explicitly removed when no longer needed.2727The file must be explicitly removed when no longer needed.
2549<P>2728<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>
2551<P>2730<P>
2552This function reads the file <CODE>_INPUT</CODE>,2731Reads file <CODE>_INPUT</CODE>,
2553or from <CODE>filehandle</CODE> if this argument is given,2732or <CODE>filehandle</CODE> if this argument is given,
2554according to a read pattern, which specifies how much to read;2733according to read patterns, which specify how much to read.
2555characters are read from the input file until2734For each pattern,
2556the read pattern fails or ends.2735the function returns a string with the characters read,
2557The function <CODE>read</CODE> returns a string with the characters read,
2558even if the pattern succeeds only partially,2736even if the pattern succeeds only partially,
2559or <B>nil</B> if the read pattern fails <EM>and</EM>2737or <B>nil</B> if the read pattern fails <EM>and</EM>
2560the result string would be empty.2738the result string would be empty.
2561When called without parameters,2739When called without patterns,
2562it uses a default pattern that reads the next line2740it uses a default pattern that reads the next line
2563(see below).2741(see below).
2564<P>2742<P>
2565A <A NAME="read pattern"><EM>read pattern</EM></A> is a sequence of read pattern items.2743A <A NAME="read pattern"><EM>read pattern</EM></A> is a sequence of read pattern items.
2566An item may be a single character class2744An item may be a single character class
2567or a character class followed by <CODE>?</CODE> or by <CODE>*</CODE>.2745or a character class followed by <CODE>?</CODE>, by <CODE>*</CODE>, or by <CODE>+</CODE>.
2568A single character class reads the next character from the input2746A single character class reads the next character from the input
2569if it belongs to the class, otherwise it fails.2747if it belongs to the class, otherwise it fails.
2570A character class followed by <CODE>?</CODE> reads the next character2748A character class followed by <CODE>?</CODE> reads the next character
@@ -2573,6 +2751,9 @@ it never fails. · 2 unmodified lines
2573A character class followed by <CODE>*</CODE> reads until a character that2751A character class followed by <CODE>*</CODE> reads until a character that
2574does not belong to the class, or end of file;2752does not belong to the class, or end of file;
2575since it can match a sequence of zero characters, it never fails.2753since it can match a sequence of zero characters, it never fails.
2754A character class followed by <CODE>+</CODE> reads until a character that
2755does not belong to the class, or end of file;
2756it fails if it cannot read at least one character.
2576Note that the behavior of read patterns is slightly different from2757Note that the behavior of read patterns is slightly different from
2577the regular pattern matching behavior,2758the regular pattern matching behavior,
2578where a <CODE>*</CODE> expands to the maximum length <EM>such that</EM>2759where 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
2585Characters matching a skip are read,2766Characters matching a skip are read,
2586but are not included in the resulting string.2767but are not included in the resulting string.
2587<P>2768<P>
2588Following are some examples of read patterns and their meanings:2769There are some predefined patterns, as follows:
2589<UL>2770<DL>
2590<LI><CODE>"."</CODE> returns the next character, or <B>nil</B> on end of file.2771<DT><B>``*n''</B><DD> reads a number;
2591<LI><CODE>".*"</CODE> reads the whole file.2772this is the only pattern that returns a number instead of a string.
2592<LI><CODE>"[^\n]*{\n}"</CODE> returns the next line2773<DT><B>``*l''</B><DD> returns the next line
2593(skipping the end of line), or <B>nil</B> on end of file.2774(skipping the end of line), or <B>nil</B> on end of file.
2594This is the default pattern.2775This is the default pattern.
2595<LI><CODE>"{%s*}%S%S*"</CODE> returns the next word2776It is equivalent to the pattern <CODE>"[^\n]*{\n}"</CODE>.
2777<DT><B>``*a''</B><DD> reads the whole file.
2778It is equivalent to the pattern <CODE>".*"</CODE>.
2779<DT><B>``*w''</B><DD> returns the next word
2596(maximal sequence of non white-space characters),2780(maximal sequence of non white-space characters),
2597skipping spaces if necessary,2781skipping spaces if necessary, or <B>nil</B> on end of file.
2598or <B>nil</B> on end of file.2782It is equivalent to the pattern <CODE>"{%s*}%S+"</CODE>.
2599<LI><CODE>"{%s*}[+-]?%d%d*"</CODE> returns the next integer2783</DL>
2600or <B>nil</B> if the next characters do not conform to an integer format.
2601</UL>
2602<P>2784<P>
2603<h3> <TT>write ([filehandle, ] value1, ...)</TT></h3><A NAME="write"></A>2785<h3> <TT>write ([filehandle, ] value1, ...)</TT></h3><A NAME="write"></A>
2604<P>2786<P>
2605This function writes the value of each of its arguments to the2787Writes the value of each of its arguments to
2606file <CODE>_OUTPUT</CODE>,2788file <CODE>_OUTPUT</CODE>,
2607or to <CODE>filehandle</CODE> if this argument is given,2789or to <CODE>filehandle</CODE> if this argument is given.
2608The arguments must be strings or numbers.2790The arguments must be strings or numbers.
2609To write other values,2791To write other values,
2610use <CODE>tostring</CODE> or <CODE>format</CODE> before <CODE>write</CODE>.2792use <CODE>tostring</CODE> or <CODE>format</CODE> before <CODE>write</CODE>.
@@ -2613,21 +2795,21 @@ plus a string describing the error. · 2 unmodified lines
2613<P>2795<P>
2614<h3> <TT>date ([format])</TT></h3><A NAME="date"></A>2796<h3> <TT>date ([format])</TT></h3><A NAME="date"></A>
2615<P>2797<P>
2616This function returns a string containing date and time2798Returns a string containing date and time
2617formatted according to the given string <CODE>format</CODE>,2799formatted according to the given string <CODE>format</CODE>,
2618following the same rules of the ANSI C function <CODE>strftime</CODE>.2800following the same rules of the ANSI C function <CODE>strftime</CODE>.
2619When called without arguments,2801When called without arguments,
2620it returns a reasonable date and time representation that depends on2802it returns a reasonable date and time representation that depends on
2621the host system and the locale.2803the host system and on the locale.
2622<P>2804<P>
2623<h3> <TT>clock ()</TT></h3><A NAME="clock"></A>2805<h3> <TT>clock ()</TT></h3><A NAME="clock"></A>
2624<P>2806<P>
2625This function returns an approximation of the amount of CPU time2807Returns an approximation of the amount of CPU time
2626used by the program, in seconds.2808used by the program, in seconds.
2627<P>2809<P>
2628<h3> <TT>exit ([code])</TT></h3><A NAME="exit"></A>2810<h3> <TT>exit ([code])</TT></h3><A NAME="exit"></A>
2629<P>2811<P>
2630This function calls the C function <CODE>exit</CODE>,2812Calls the C function <CODE>exit</CODE>,
2631with an optional <CODE>code</CODE>,2813with an optional <CODE>code</CODE>,
2632to terminate the program.2814to terminate the program.
2633The default value for <CODE>code</CODE> is 1.2815The default value for <CODE>code</CODE> is 1.
@@ -2694,12 +2876,16 @@ it accepts only a handle returned by · 60 unmodified lines
2694<P>2876<P>
2695Three other functions produce extra information about a function:2877Three other functions produce extra information about a function:
2696<PRE>2878<PRE>
2697void lua_funcinfo (lua_Object func, char **filename, int *linedefined);2879void lua_funcinfo (lua_Object func, char **source, int *linedefined);
2698int lua_currentline (lua_Function func);2880int lua_currentline (lua_Function func);
2699char *lua_getobjname (lua_Object o, char **name);2881char *lua_getobjname (lua_Object o, char **name);
2700</PRE>2882</PRE>
2701<CODE>lua_funcinfo</CODE> gives the file name and the line where the2883<CODE>lua_funcinfo</CODE> gives the source and the line where the
2702given function has been defined.2884given function has been defined:
2885If the function was defined in a string,
2886<CODE>source</CODE> is that string;
2887If the function was defined in a file,
2888<CODE>source</CODE> starts with a <CODE>@</CODE> followed by the file name.
2703If the ``function'' is in fact the main code of a chunk,2889If the ``function'' is in fact the main code of a chunk,
2704then <CODE>linedefined</CODE> is 0.2890then <CODE>linedefined</CODE> is 0.
2705If the function is a C function,2891If 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
2708The function <CODE>lua_currentline</CODE> gives the current line where2894The function <CODE>lua_currentline</CODE> gives the current line where
2709a given function is executing.2895a given function is executing.
2710It only works if the function has been compiled with debug2896It only works if the function has been compiled with debug
2711information (see Section&nbsp;<A HREF="#pragma">4.9</A>).2897information.
2712When no line information is available,2898When no line information is available,
2713<CODE>lua_currentline</CODE> returns <I>-1</I>.2899<CODE>lua_currentline</CODE> returns <I>-1</I>.
2714<P>2900<P>
2901The generation of debug information is controled by an internal flag,
2902which can be switched with
2903<PRE>
2904int lua_setdebug (int debug);
2905</PRE>
2906This function sets the flag and returns its previous value.
2907This flag can also be set from Lua&nbsp;(see Section&nbsp;<A HREF="#pragma">4.9</A>).
2908<P>
2715Function <CODE>lua_getobjname</CODE> tries to find a reasonable name for2909Function <CODE>lua_getobjname</CODE> tries to find a reasonable name for
2716a given function.2910a given function.
2717Because functions in Lua are first class values,2911Because functions in Lua are first class values,
2718they do not have a fixed name:2912they do not have a fixed name:
2719Some functions may be the value of many global variables,2913Some functions may be the value of many global variables,
2720while others may be stored only in a table field.2914while others may be stored only in a table field.
2721Function <CODE>lua_getobjname</CODE> first checks whether the given2915Function <CODE>lua_getobjname</CODE> checks whether the given
2722function is a tag method.2916function is a tag method or the value of a global variable.
2723If so, it returns the string <CODE>"tag-method"</CODE>,2917If the given function is a tag method, then <CODE>lua_getobjname</CODE>
2918returns the string <CODE>"tag-method"</CODE>,
2724and <CODE>name</CODE> is set to point to the event name.2919and <CODE>name</CODE> is set to point to the event name.
2725Otherwise, if the given function is the value of a global variable,2920If the given function is the value of a global variable,
2726then <CODE>lua_getobjname</CODE> returns the string <CODE>"global"</CODE>,2921then <CODE>lua_getobjname</CODE> returns the string <CODE>"global"</CODE>,
2727and <CODE>name</CODE> points to the variable name.2922and <CODE>name</CODE> points to the variable name.
2728If the given function is neither a tag method nor a global variable,2923If 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
2736local variables of a given activation record.2931local variables of a given activation record.
2737They only work if the function has been compiled with debug2932They only work if the function has been compiled with debug
2738information (see Section&nbsp;<A HREF="#pragma">4.9</A>).2933information (see Section&nbsp;<A HREF="#pragma">4.9</A>).
2934Moreover, for these functions, a local variable becomes
2935visible in the line after its definition.
2739<PRE>2936<PRE>
2740lua_Object lua_getlocal (lua_Function func, int local_number, char **name);2937lua_Object lua_getlocal (lua_Function func, int local_number, char **name);
2741int lua_setlocal (lua_Function func, int local_number);2938int lua_setlocal (lua_Function func, int local_number);
@@ -2766,17 +2963,17 @@ then this function fails and returns 0. · 24 unmodified lines
2766The Lua interpreter offers two hooks for debugging purposes:2963The Lua interpreter offers two hooks for debugging purposes:
2767<PRE>2964<PRE>
2768typedef void (*lua_CHFunction) (lua_Function func, char *file, int line);2965typedef void (*lua_CHFunction) (lua_Function func, char *file, int line);
2769extern lua_CHFunction lua_callhook;2966lua_CHFunction lua_setcallhook (lua_CHFunction func);
2770<P>2967<P>
2771typedef void (*lua_LHFunction) (int line);2968typedef void (*lua_LHFunction) (int line);
2772extern lua_LHFunction lua_linehook;2969lua_LHFunction lua_setlinehook (lua_LHFunction func);
2773</PRE>2970</PRE>
2774The first one is called whenever the interpreter enters or leaves a2971The first hook is called whenever the interpreter enters or leaves a
2775function.2972function.
2776When entering a function,2973When entering a function,
2777its parameters are a handle to the function activation record,2974its parameters are a handle to the function activation record,
2778plus the file and the line where the function is defined (the same2975plus the file and the line where the function is defined
2779information which is provided by <CODE>lua_funcinfo</CODE>);2976(the same information which is provided by <CODE>lua_funcinfo</CODE>);
2780when leaving a function, <CODE>func</CODE> is <CODE>LUA_NOOBJECT</CODE>,2977when leaving a function, <CODE>func</CODE> is <CODE>LUA_NOOBJECT</CODE>,
2781<CODE>file</CODE> is <CODE>"(return)"</CODE>, and <CODE>line</CODE> is 0.2978<CODE>file</CODE> is <CODE>"(return)"</CODE>, and <CODE>line</CODE> is 0.
2782<P>2979<P>
@@ -2785,12 +2982,131 @@ the line of code it is executing. · 2 unmodified lines
2785Its only parameter is the line number2982Its only parameter is the line number
2786(the same information which is provided by the call2983(the same information which is provided by the call
2787<CODE>lua_currentline(lua_stackedfunction(0))</CODE>).2984<CODE>lua_currentline(lua_stackedfunction(0))</CODE>).
2788This second hook is only called if the active function2985This second hook is called only if the active function
2789has been compiled with debug information (see Section&nbsp;<A HREF="#pragma">4.9</A>).2986has been compiled with debug information (see Section&nbsp;<A HREF="#pragma">4.9</A>).
2790<P>2987<P>
2791A hook is disabled when its value is <CODE>NULL</CODE>,2988A hook is disabled when its value is <CODE>NULL</CODE>,
2792which is the initial value of both hooks.2989which is the initial value of both hooks.
2990Both <CODE>lua_setcallhook</CODE> and <CODE>lua_setlinehook</CODE>
2991set 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>
2998The library <CODE>ldblib</CODE> provides
2999the functionallity of the debugger interface to Lua programs.
3000If you want to use this library,
3001your host application must open it,
3002calling <CODE>lua_dblibopen</CODE>.
3003<P>
3004You should exert great care when using this library.
3005The functions provided here should be used exclusively for debugging
3006and similar tasks (e.g. profiling).
3007Please resist the temptation to use them as a
3008usual programming tool.
3009They are slow and violate some (otherwise) secure aspects of the
3010language (e.g. privacy of local variables).
3011As a general rule, if your program does not need this library,
3012do not open it.
3013<P>
3014<P>
3015<h3> <TT>funcinfo (function)</TT></h3><A NAME="funcinfo"></A>
3016<P>
3017This function returns a table with information about the given function.
3018The 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,
3022or <CODE>"Lua"</CODE> if this is a Lua function.
3023<P>
3024<DT><B>source</B><DD> the source where the function was defined.
3025If the function was defined in a string,
3026<CODE>source</CODE> is that string;
3027If 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,
3034or <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;
3038if <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>
3044This function returns a table with informations about the function
3045running at level <CODE>index</CODE> of the stack.
3046Index 0 is the current function (<CODE>getstack</CODE> itself).
3047If <CODE>index</CODE> is bigger than the number of active functions,
3048the function returns <B>nil</B>.
3049The table contains all the fields returned by <CODE>funcinfo</CODE>,
3050plus 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;
3054this will be available only when the function is
3055precompiled with debug information.
3056</DL>
2793<P>3057<P>
3058<h3> <TT>getlocal (index [, local])</TT></h3><A NAME="getlocal"></A>
3059<P>
3060This function returns information about the local variables of the
3061function at level <CODE>index</CODE> of the stack.
3062It can be called in three ways.
3063When called without a <CODE>local</CODE> argument,
3064it returns a table, which associates variable names to their values.
3065When called with a name (a string) as <CODE>local</CODE>,
3066it returns the value of the local variable with that name.
3067Finally, when called with an index (a number),
3068it returns the value and the name of the local variable
3069with that index.
3070(The first parameter has index 1, and so on,
3071until the last active local variable.)
3072In that case, the function returns <B>nil</B> if there is no local
3073variable with the given index.
3074The specification by index is the only way to distinguish
3075homonym variables in a function.
3076<P>
3077<h3> <TT>setlocal (index, local, newvalue)</TT></h3><A NAME="setlocal"></A>
3078<P>
3079This function changes the values of the local variables of the
3080function at level <CODE>index</CODE> of the stack.
3081The local variable can be specified by name or by index;
3082see function <CODE>getlocal</CODE>.
3083<P>
3084<h3> <TT>setcallhook (hook)</TT></h3><A NAME="setcallhook"></A>
3085<P>
3086Sets the function <CODE>hook</CODE> as the call hook;
3087this hook will be called every time the interpreter starts and
3088exits the execution of a function.
3089When Lua enters a function,
3090the hook is called with the function been called,
3091plus the source and the line where the function is defined.
3092When Lua exits a function,
3093the hook is called with no arguments.
3094<P>
3095When called without arguments,
3096this function turns off call hooks.
3097<P>
3098<h3> <TT>setlinehook (hook)</TT></h3><A NAME="setlinehook"></A>
3099<P>
3100Sets the function <CODE>hook</CODE> as the line hook;
3101this hook will be called every time the interpreter changes
3102the line of code it is executing.
3103The only argument to the hook is the line number the interpreter
3104is about to execut.
3105This hook is called only if the active function
3106has been compiled with debug information (see Section&nbsp;<A HREF="#pragma">4.9</A>).
3107<P>
3108When called without arguments,
3109this function turns off line hooks.
2794<P>3110<P>
2795<P>3111<P>
2796<A NAME="lua-sa"></A>3112<A NAME="lua-sa"></A>
@@ -2866,6 +3182,18 @@ the previous public versions of Lua, · 69 unmodified lines
2866some differences had to be introduced.3182some differences had to be introduced.
2867Here is a list of all these incompatibilities.3183Here is a list of all these incompatibilities.
2868<P>3184<P>
3185<h2>Incompatibilities with <A NAME="version 3.1</h2>">version 3.1</h2></A>
3186<UL>
3187<LI>
3188In 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>.
3190Therefore, they are no longer directly accessible, and must be
3191manipulated 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>
2869<h2>Incompatibilities with <A NAME="version 3.0</h2>">version 3.0</h2></A>3197<h2>Incompatibilities with <A NAME="version 3.0</h2>">version 3.0</h2></A>
2870<UL>3198<UL>
2871<P>3199<P>
@@ -2877,7 +3205,7 @@ so any existing program that opens at least one standard · 5 unmodified lines
2877library before calling Lua does not need to be modified.3205library before calling Lua does not need to be modified.
2878<P>3206<P>
2879<LI>Function <CODE>dostring</CODE> no longer accepts an optional second argument,3207<LI>Function <CODE>dostring</CODE> no longer accepts an optional second argument,
2880with a temporary error method.3208with a temporary error handler.
2881This facility is now provided by function <CODE>call</CODE>.3209This facility is now provided by function <CODE>call</CODE>.
2882<P>3210<P>
2883<LI>Function <CODE>gsub</CODE> no longer accepts an optional fourth argument3211<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
2898<P>3226<P>
2899</UL>3227</UL>
2900<P>3228<P>
2901<P>
2902 3229
2903<HR>3230<HR>
3231<SMALL>
2904Last update:3232Last update:
2905Fri Jul 10 15:10:14 EST 19983233Wed Jul 7 13:36:24 EST 1999
2906by <A HREF="http://www.tecgraf.puc-rio.br/~lhf/">lhf</A>.3234by <A HREF="http://www.tecgraf.puc-rio.br/~lhf/">lhf</A>.
3235</SMALL>
3236
2907</BODY>3237</BODY>
2908</HTML>3238</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>
25Last update:
26Wed Jul 7 13:24:17 EST 1999
27by <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
5 run with lua_dobuffer.5 run with lua_dobuffer.
6 This allows C programs to include all necessary Lua code, even in6 This allows C programs to include all necessary Lua code, even in
7 precompiled form.7 precompiled form.
8 Even if code is include in source form, bin2c is useful because it8 Even if the code is included in source form, bin2c is useful because it
9 avoids the hassle of having to quote special characters in C strings.9 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 C10 Example of usage: Run bin2c file1 file2 ... > init.h. Then, in your C
11 program, just do #include "init.h" anywhere in the *body* of a11 program, just do #include "init.h" anywhere in the *body* of a
12 function. This will be equivalent to calling12 function. This will be equivalent to calling
13 lua_dofile("file1"); lua_dofile("file2"); ...13 lua_dofile("file1"); lua_dofile("file2"); ...
@@ -17,7 +17,8 @@ min.c · 3 unmodified lines
17 17
18setfallback.lua18setfallback.lua
19 An implementation of fallbacks on top of tag methods.19 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.
21 If you have C code that uses lua_setfallback, then define LUA_COMPAT2_522 If you have C code that uses lua_setfallback, then define LUA_COMPAT2_5
22 before building Lua (see config).23 before building Lua (see config).
23 24
etc/bin2c.c+7−2
@@ -2,15 +2,16 @@ · 1 unmodified line
2* bin2c.c2* bin2c.c
3* convert binary files to byte arrays3* convert binary files to byte arrays
4* Luiz Henrique de Figueiredo (lhf@tecgraf.puc-rio.br)4* Luiz Henrique de Figueiredo (lhf@tecgraf.puc-rio.br)
5* 25 Jun 98 10:55:125* 24 Nov 98 12:15:27
6*/6*/
7 7
8#include <ctype.h>8#include <ctype.h>
9#include <stdio.h>9#include <stdio.h>
10#include <stdlib.h>
10 11
11void dump(FILE* f, int n)12void dump(FILE* f, int n)
12{13{
13 printf("static unsigned char B%d[]={\n");14 printf("static unsigned char B%d[]={\n",n);
14 for (n=1;;n++)15 for (n=1;;n++)
15 {16 {
16 int c=getc(f); 17 int c=getc(f);
@@ -49,6 +50,7 @@ void emit(char* fn, int n) · 32 unmodified lines
49 50
50int main(int argc, char* argv[])51int main(int argc, char* argv[])
51{52{
53 printf("/* code automatically generated by bin2c -- DO NOT EDIT */\n");
52 printf("{\n");54 printf("{\n");
53 if (argc<2)55 if (argc<2)
54 {56 {
@@ -58,6 +60,9 @@ int main(int argc, char* argv[]) · 3 unmodified lines
58 else60 else
59 {61 {
60 int i;62 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");
61 for (i=1; i<argc; i++) fdump(argv[i],i);66 for (i=1; i<argc; i++) fdump(argv[i],i);
62 for (i=1; i<argc; i++) emit(argv[i],i);67 for (i=1; i<argc; i++) emit(argv[i],i);
63 }68 }
etc/trace.c+14−18
@@ -1,6 +1,6 @@
1/*1/*
2* trace.c2* trace.c
3* a simple execution tracer3* a simple execution tracer for Lua
4*/4*/
5 5
6#include <stdio.h>6#include <stdio.h>
@@ -8,45 +8,41 @@ · 1 unmodified line
8#include "lua.h"8#include "lua.h"
9#include "luadebug.h"9#include "luadebug.h"
10 10
11static FILE* P; /* output file */11static FILE* LOG; /* output file */
12static int L=0; /* indentation level */12static int L=0; /* indentation level */
13 13
14static void linehook(int line)14static void linehook(int line)
15{15{
16 fprintf(P,"%*sLINE(%d)\t-- %d\n",L,"",line,L);16 fprintf(LOG,"%*sLINE(%d)\t-- %d\n",L,"",line,L);
17}17}
18 18
19static void callhook(lua_Function func, char* file, int line)19static void callhook(lua_Function func, char* file, int line)
20{20{
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);
22 if (line==0 && strcmp(file,"(return)")==0) --L; else ++L;22 if (line==0 && strcmp(file,"(return)")==0) --L; else ++L;
23}23}
24 24
25void start_trace(void)25void start_trace(FILE* logfile)
26{26{
27 lua_linehook=linehook;27 lua_setlinehook(linehook);
28 lua_callhook=callhook;28 lua_setcallhook(callhook);
29 lua_debug=1;29 lua_setdebug(1);
30#if 030 LOG=logfile;
31 P=fopen("trace.out","w");
32#else
33 P=stderr;
34#endif
35}31}
36 32
37void stop_trace(void)33void stop_trace(void)
38{34{
39 lua_linehook=NULL;35 lua_setlinehook(NULL);
40 lua_callhook=NULL;36 lua_setcallhook(NULL);
41 lua_debug=0;37 lua_setdebug(0);
42 fclose(P);38 fclose(LOG);
43}39}
44 40
45int main(void)41int main(void)
46{42{
47 int rc;43 int rc;
48 lua_open();44 lua_open();
49 start_trace();45 start_trace(stderr);
50 rc=lua_dofile(0);46 rc=lua_dofile(0);
51 stop_trace();47 stop_trace();
52 return rc;48 return rc;
include/lauxlib.h+7−1
@@ -1,5 +1,5 @@
1/*1/*
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 $
3** Auxiliary functions for building Lua libraries3** Auxiliary functions for building Lua libraries
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -28,7 +28,11 @@ char *luaL_check_lstr (int numArg, long *len); · 22 unmodified lines
28#define luaL_opt_string(n, d) (luaL_opt_lstr((n), (d), NULL))28#define luaL_opt_string(n, d) (luaL_opt_lstr((n), (d), NULL))
29char *luaL_opt_lstr (int numArg, char *def, long *len);29char *luaL_opt_lstr (int numArg, char *def, long *len);
30double luaL_check_number (int numArg);30double 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))
31double luaL_opt_number (int numArg, double def);33double 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))
32lua_Object luaL_functionarg (int arg);36lua_Object luaL_functionarg (int arg);
33lua_Object luaL_tablearg (int arg);37lua_Object luaL_tablearg (int arg);
34lua_Object luaL_nonnullarg (int numArg);38lua_Object luaL_nonnullarg (int numArg);
@@ -42,6 +46,8 @@ int luaL_newbuffer (int size); · 7 unmodified lines
42void luaL_oldbuffer (int old);46void luaL_oldbuffer (int old);
43char *luaL_buffer (void);47char *luaL_buffer (void);
44int luaL_findstring (char *name, char *list[]);48int luaL_findstring (char *name, char *list[]);
49void luaL_chunkid (char *out, char *source, int len);
50void luaL_filesource (char *out, char *filename, int len);
45 51
46 52
47#endif53#endif
include/lua.h+13−16
@@ -1,5 +1,5 @@
1/*1/*
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 $
3** Lua - An Extensible Extension Language3** Lua - An Extensible Extension Language
4** TeCGraf: Grupo de Tecnologia em Computacao Grafica, PUC-Rio, Brazil4** TeCGraf: Grupo de Tecnologia em Computacao Grafica, PUC-Rio, Brazil
5** e-mail: lua@tecgraf.puc-rio.br5** e-mail: lua@tecgraf.puc-rio.br
@@ -11,8 +11,8 @@ · 5 unmodified lines
11#ifndef lua_h11#ifndef lua_h
12#define lua_h12#define lua_h
13 13
14#define LUA_VERSION "Lua 3.1"14#define LUA_VERSION "Lua 3.2"
15#define LUA_COPYRIGHT "Copyright (C) 1994-1998 TeCGraf, PUC-Rio"15#define LUA_COPYRIGHT "Copyright (C) 1994-1999 TeCGraf, PUC-Rio"
16#define LUA_AUTHORS "W. Celes, R. Ierusalimschy & L. H. de Figueiredo"16#define LUA_AUTHORS "W. Celes, R. Ierusalimschy & L. H. de Figueiredo"
17 17
18 18
@@ -20,19 +20,18 @@ · 1 unmodified line
20 20
21#define LUA_ANYTAG (-1)21#define LUA_ANYTAG (-1)
22 22
23typedef void (*lua_CFunction) (void);
24typedef unsigned int lua_Object;
25
26typedef struct lua_State lua_State;23typedef struct lua_State lua_State;
27extern lua_State *lua_state;24extern lua_State *lua_state;
28 25
26typedef void (*lua_CFunction) (void);
27typedef unsigned int lua_Object;
28
29void lua_open (void);29void lua_open (void);
30void lua_close (void);30void lua_close (void);
31lua_State *lua_setstate (lua_State *st);31lua_State *lua_setstate (lua_State *st);
32 32
33lua_Object lua_settagmethod (int tag, char *event); /* In: new method */33lua_Object lua_settagmethod (int tag, char *event); /* In: new method */
34lua_Object lua_gettagmethod (int tag, char *event);34lua_Object lua_gettagmethod (int tag, char *event);
35lua_Object lua_seterrormethod (void); /* In: new method */
36 35
37int lua_newtag (void);36int lua_newtag (void);
38int lua_copytagmethods (int tagto, int tagfrom);37int lua_copytagmethods (int tagto, int tagfrom);
@@ -90,6 +89,9 @@ lua_Object lua_rawgettable (void); /* In: table, index */ · 51 unmodified lines
90 89
91int lua_tag (lua_Object object);90int lua_tag (lua_Object object);
92 91
92char *lua_nextvar (char *varname); /* Out: value */
93int lua_next (lua_Object o, int i);
94 /* Out: ref, value */
93 95
94int lua_ref (int lock); /* In: value */96int lua_ref (int lock); /* In: value */
95lua_Object lua_getref (int ref);97lua_Object lua_getref (int ref);
@@ -101,29 +103,23 @@ long lua_collectgarbage (long limit); · 5 unmodified lines
101 103
102 104
103/* =============================================================== */105/* =============================================================== */
104/* some useful macros/derived functions */106/* some useful macros/functions */
105 107
106int (lua_call) (char *name);
107#define lua_call(name) lua_callfunction(lua_getglobal(name))108#define lua_call(name) lua_callfunction(lua_getglobal(name))
108 109
109void (lua_pushref) (int ref);
110#define lua_pushref(ref) lua_pushobject(lua_getref(ref))110#define lua_pushref(ref) lua_pushobject(lua_getref(ref))
111 111
112int (lua_refobject) (lua_Object o, int l);
113#define lua_refobject(o,l) (lua_pushobject(o), lua_ref(l))112#define lua_refobject(o,l) (lua_pushobject(o), lua_ref(l))
114 113
115void (lua_register) (char *n, lua_CFunction f);
116#define lua_register(n,f) (lua_pushcfunction(f), lua_setglobal(n))114#define lua_register(n,f) (lua_pushcfunction(f), lua_setglobal(n))
117 115
118void (lua_pushuserdata) (void *u);
119#define lua_pushuserdata(u) lua_pushusertag(u, 0)116#define lua_pushuserdata(u) lua_pushusertag(u, 0)
120 117
121void (lua_pushcfunction) (lua_CFunction f);
122#define lua_pushcfunction(f) lua_pushcclosure(f, 0)118#define lua_pushcfunction(f) lua_pushcclosure(f, 0)
123 119
124int (lua_clonetag) (int t);
125#define lua_clonetag(t) lua_copytagmethods(lua_newtag(), (t))120#define lua_clonetag(t) lua_copytagmethods(lua_newtag(), (t))
126 121
122lua_Object lua_seterrormethod (void); /* In: new method */
127 123
128/* ==========================================================================124/* ==========================================================================
129** for compatibility with old versions. Avoid using these macros/functions125** 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
162 158
163 159
164/******************************************************************************160/******************************************************************************
165* Copyright (c) 1994-1998 TeCGraf, PUC-Rio. All rights reserved.161* Copyright (c) 1994-1999 TeCGraf, PUC-Rio. All rights reserved.
166* 162*
167* Permission is hereby granted, without written agreement and without license163* Permission is hereby granted, without written agreement and without license
168* or royalty fees, to use, copy, modify, and distribute this software and its164* 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
192* The Lua language and this implementation have been entirely designed and188* The Lua language and this implementation have been entirely designed and
193* written by Waldemar Celes Filho, Roberto Ierusalimschy and189* written by Waldemar Celes Filho, Roberto Ierusalimschy and
194* Luiz Henrique de Figueiredo at TeCGraf, PUC-Rio.190* Luiz Henrique de Figueiredo at TeCGraf, PUC-Rio.
191*
195* This implementation contains no third-party code.192* This implementation contains no third-party code.
196******************************************************************************/193******************************************************************************/
include/luadebug.h+6−5
@@ -1,5 +1,5 @@
1/*1/*
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 $
3** Debugging API3** Debugging API
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -17,17 +17,18 @@ typedef void (*lua_LHFunction) (int line); · 11 unmodified lines
17typedef void (*lua_CHFunction) (lua_Function func, char *file, int line);17typedef void (*lua_CHFunction) (lua_Function func, char *file, int line);
18 18
19lua_Function lua_stackedfunction (int level);19lua_Function lua_stackedfunction (int level);
20void lua_funcinfo (lua_Object func, char **filename, int *linedefined);20void lua_funcinfo (lua_Object func, char **source, int *linedefined);
21int lua_currentline (lua_Function func);21int lua_currentline (lua_Function func);
22char *lua_getobjname (lua_Object o, char **name);22char *lua_getobjname (lua_Object o, char **name);
23 23
24lua_Object lua_getlocal (lua_Function func, int local_number, char **name);24lua_Object lua_getlocal (lua_Function func, int local_number, char **name);
25int lua_setlocal (lua_Function func, int local_number);25int lua_setlocal (lua_Function func, int local_number);
26 26
27int lua_nups (lua_Function func);
27 28
28extern lua_LHFunction lua_linehook;29lua_LHFunction lua_setlinehook (lua_LHFunction func);
29extern lua_CHFunction lua_callhook;30lua_CHFunction lua_setcallhook (lua_CHFunction func);
30extern int lua_debug;31int lua_setdebug (int debug);
31 32
32 33
33#endif34#endif
include/lualib.h+5−3
@@ -1,5 +1,5 @@
1/*1/*
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 $
3** Lua standard libraries3** Lua standard libraries
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -10,12 +10,13 @@ · 4 unmodified lines
10 10
11#include "lua.h"11#include "lua.h"
12 12
13
14void lua_iolibopen (void);13void lua_iolibopen (void);
15void lua_strlibopen (void);14void lua_strlibopen (void);
16void lua_mathlibopen (void);15void lua_mathlibopen (void);
16void lua_dblibopen (void);
17 17
18 18
19void lua_userinit (void);
19 20
20 21
21/* To keep compatibility with old versions */22/* To keep compatibility with old versions */
@@ -28,7 +29,8 @@ void lua_mathlibopen (void); · 6 unmodified lines
28 29
29/* Auxiliary functions (private) */30/* Auxiliary functions (private) */
30 31
31int luaI_singlematch (int c, char *p, char **ep);32char *luaI_classend (char *p);
33int luaI_singlematch (int c, char *p, char *ep);
32 34
33#endif35#endif
34 36
src/lapi.c+165−103
@@ -1,5 +1,5 @@
1/*1/*
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 $
3** Lua API3** Lua API
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -25,17 +25,16 @@ · 19 unmodified lines
25 25
26 26
27char lua_ident[] = "$Lua: " LUA_VERSION " " LUA_COPYRIGHT " $\n"27char lua_ident[] = "$Lua: " LUA_VERSION " " LUA_COPYRIGHT " $\n"
28 "$Autores: " LUA_AUTHORS " $";28 "$Authors: " LUA_AUTHORS " $";
29 29
30 30
31 31
32TObject *luaA_Address (lua_Object o)32TObject *luaA_Address (lua_Object o) {
33{33 return (o != LUA_NOOBJECT) ? Address(o) : NULL;
34 return Address(o);
35}34}
36 35
37 36
38static int normalized_type (TObject *o)37static lua_Type normalized_type (TObject *o)
39{38{
40 int t = ttype(o);39 int t = ttype(o);
41 switch (t) {40 switch (t) {
@@ -71,12 +70,8 @@ void luaA_packresults (void) · 29 unmodified lines
71}70}
72 71
73 72
74int luaA_passresults (void)73int luaA_passresults (void) {
75{74 L->Cstack.base = L->Cstack.lua2C; /* position of first result */
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;
80 return L->Cstack.num;75 return L->Cstack.num;
81}76}
82 77
@@ -88,24 +83,29 @@ static void checkCparams (int nParams) · 5 unmodified lines
88}83}
89 84
90 85
91static lua_Object put_luaObject (TObject *o)86static lua_Object put_luaObject (TObject *o) {
92{
93 luaD_openstack((L->stack.top-L->stack.stack)-L->Cstack.base);87 luaD_openstack((L->stack.top-L->stack.stack)-L->Cstack.base);
94 L->stack.stack[L->Cstack.base++] = *o;88 L->stack.stack[L->Cstack.base++] = *o;
95 return L->Cstack.base; /* this is +1 real position (see Ref) */89 return L->Cstack.base; /* this is +1 real position (see Ref) */
96}90}
97 91
98 92
99static lua_Object put_luaObjectonTop (void)93static lua_Object put_luaObjectonTop (void) {
100{
101 luaD_openstack((L->stack.top-L->stack.stack)-L->Cstack.base);94 luaD_openstack((L->stack.top-L->stack.stack)-L->Cstack.base);
102 L->stack.stack[L->Cstack.base++] = *(--L->stack.top);95 L->stack.stack[L->Cstack.base++] = *(--L->stack.top);
103 return L->Cstack.base; /* this is +1 real position (see Ref) */96 return L->Cstack.base; /* this is +1 real position (see Ref) */
104}97}
105 98
106 99
107lua_Object lua_pop (void)100static void top2LC (int n) {
108{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
108lua_Object lua_pop (void) {
109 checkCparams(1);109 checkCparams(1);
110 return put_luaObjectonTop();110 return put_luaObjectonTop();
111}111}
@@ -131,7 +131,7 @@ int lua_callfunction (lua_Object function) · 19 unmodified lines
131 else {131 else {
132 luaD_openstack((L->stack.top-L->stack.stack)-L->Cstack.base);132 luaD_openstack((L->stack.top-L->stack.stack)-L->Cstack.base);
133 set_normalized(L->stack.stack+L->Cstack.base, Address(function));133 set_normalized(L->stack.stack+L->Cstack.base, Address(function));
134 return luaD_protectedrun(MULT_RET);134 return luaD_protectedrun();
135 }135 }
136}136}
137 137
@@ -150,12 +150,12 @@ lua_Object lua_settagmethod (int tag, char *event) · 12 unmodified lines
150}150}
151 151
152 152
153lua_Object lua_seterrormethod (void)153lua_Object lua_seterrormethod (void) {
154{154 lua_Object temp;
155 TObject temp = L->errorim;
156 checkCparams(1);155 checkCparams(1);
157 L->errorim = *(--L->stack.top);156 temp = lua_getglobal("_ERRORMESSAGE");
158 return put_luaObject(&temp);157 lua_setglobal("_ERRORMESSAGE");
158 return temp;
159}159}
160 160
161 161
@@ -167,34 +167,26 @@ lua_Object lua_gettable (void) · 5 unmodified lines
167}167}
168 168
169 169
170lua_Object lua_rawgettable (void)170lua_Object lua_rawgettable (void) {
171{
172 checkCparams(2);171 checkCparams(2);
173 if (ttype(L->stack.top-2) != LUA_T_ARRAY)172 if (ttype(L->stack.top-2) != LUA_T_ARRAY)
174 lua_error("indexed expression not a table in rawgettable");173 lua_error("indexed expression not a table in rawgettable");
175 else {174 *(L->stack.top-2) = *luaH_get(avalue(L->stack.top-2), L->stack.top-1);
176 TObject *h = luaH_get(avalue(L->stack.top-2), L->stack.top-1);175 --L->stack.top;
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 }
183 return put_luaObjectonTop();176 return put_luaObjectonTop();
184}177}
185 178
186 179
187void lua_settable (void)180void lua_settable (void) {
188{
189 checkCparams(3);181 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 */
191}184}
192 185
193 186
194void lua_rawsettable (void)187void lua_rawsettable (void) {
195{
196 checkCparams(3);188 checkCparams(3);
197 luaV_settable(L->stack.top-3, 0);189 luaV_rawsettable(L->stack.top-3);
198}190}
199 191
200 192
@@ -373,14 +365,11 @@ void luaA_pushobject (TObject *o) · 172 unmodified lines
373 incr_top;365 incr_top;
374}366}
375 367
376void lua_pushobject (lua_Object o)368void lua_pushobject (lua_Object o) {
377{
378 if (o == LUA_NOOBJECT)369 if (o == LUA_NOOBJECT)
379 lua_error("API error - attempt to push a NOOBJECT");370 lua_error("API error - attempt to push a NOOBJECT");
380 else {371 set_normalized(L->stack.top, Address(o));
381 set_normalized(L->stack.top, Address(o));372 incr_top;
382 incr_top;
383 }
384}373}
385 374
386 375
@@ -426,22 +415,108 @@ void lua_settag (int tag) · 39 unmodified lines
426 break;415 break;
427 default:416 default:
428 luaL_verror("cannot change the tag of a %.20s",417 luaL_verror("cannot change the tag of a %.20s",
429 luaO_typenames[-ttype((L->stack.top-1))]);418 luaO_typename(L->stack.top-1));
430 }419 }
431 L->stack.top--;420 L->stack.top--;
432}421}
433 422
434 423
424TaggedString *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
443char *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
457int 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
471int 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
435/*482/*
436** =======================================================483** {======================================================
437** Debug interface484** To manipulate some state information
438** =======================================================485** =======================================================
439*/486*/
440 487
488lua_State *lua_setstate (lua_State *st) {
489 lua_State *old = lua_state;
490 lua_state = st;
491 return old;
492}
493
494lua_LHFunction lua_setlinehook (lua_LHFunction func) {
495 lua_LHFunction old = L->linehook;
496 L->linehook = func;
497 return old;
498}
499
500lua_CHFunction lua_setcallhook (lua_CHFunction func) {
501 lua_CHFunction old = L->callhook;
502 L->callhook = func;
503 return old;
504}
505
506int lua_setdebug (int debug) {
507 int old = L->debug;
508 L->debug = debug;
509 return old;
510}
511
512/* }====================================================== */
441 513
442/* Hooks */514
443lua_CHFunction lua_callhook = NULL;515/*
444lua_LHFunction lua_linehook = NULL;516** {======================================================
517** Debug interface
518** =======================================================
519*/
445 520
446 521
447lua_Function lua_stackedfunction (int level)522lua_Function lua_stackedfunction (int level)
@@ -457,6 +532,12 @@ lua_Function lua_stackedfunction (int level) · 9 unmodified lines
457}532}
458 533
459 534
535int 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
460int lua_currentline (lua_Function func)541int lua_currentline (lua_Function func)
461{542{
462 TObject *f = Address(func);543 TObject *f = Address(func);
@@ -465,8 +546,7 @@ int lua_currentline (lua_Function func) · 2 unmodified lines
465}546}
466 547
467 548
468lua_Object lua_getlocal (lua_Function func, int local_number, char **name)549lua_Object lua_getlocal (lua_Function func, int local_number, char **name) {
469{
470 /* check whether func is a Lua function */550 /* check whether func is a Lua function */
471 if (lua_tag(func) != LUA_T_PROTO)551 if (lua_tag(func) != LUA_T_PROTO)
472 return LUA_NOOBJECT;552 return LUA_NOOBJECT;
@@ -477,7 +557,7 @@ lua_Object lua_getlocal (lua_Function func, int local_number, char **name) · 4 unmodified lines
477 if (*name) {557 if (*name) {
478 /* if "*name", there must be a LUA_T_LINE */558 /* if "*name", there must be a LUA_T_LINE */
479 /* therefore, f+2 points to function base */559 /* therefore, f+2 points to function base */
480 return Ref((f+2)+(local_number-1));560 return put_luaObject((f+2)+(local_number-1));
481 }561 }
482 else562 else
483 return LUA_NOOBJECT;563 return LUA_NOOBJECT;
@@ -508,18 +588,17 @@ int lua_setlocal (lua_Function func, int local_number) · 24 unmodified lines
508}588}
509 589
510 590
511void lua_funcinfo (lua_Object func, char **filename, int *linedefined)591void lua_funcinfo (lua_Object func, char **source, int *linedefined) {
512{
513 if (!lua_isfunction(func))592 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");
515 else {594 else {
516 TObject *f = luaA_protovalue(Address(func));595 TObject *f = luaA_protovalue(Address(func));
517 if (normalized_type(f) == LUA_T_PROTO) {596 if (normalized_type(f) == LUA_T_PROTO) {
518 *filename = tfvalue(f)->fileName->str;597 *source = tfvalue(f)->source->str;
519 *linedefined = tfvalue(f)->lineDefined;598 *linedefined = tfvalue(f)->lineDefined;
520 }599 }
521 else {600 else {
522 *filename = "(C)";601 *source = "(C)";
523 *linedefined = -1;602 *linedefined = -1;
524 }603 }
525 }604 }
@@ -534,31 +613,37 @@ static int checkfunc (TObject *o) · 8 unmodified lines
534 613
535char *lua_getobjname (lua_Object o, char **name)614char *lua_getobjname (lua_Object o, char **name)
536{ /* try to find a name for given function */615{ /* try to find a name for given function */
537 set_normalized(L->stack.top, Address(o)); /* to be accessed by "checkfunc */616 set_normalized(L->stack.top, Address(o)); /* to be accessed by "checkfunc" */
538 if ((*name = luaT_travtagmethods(checkfunc)) != NULL)617 if ((*name = luaS_travsymbol(checkfunc)) != NULL)
539 return "tag-method";
540 else if ((*name = luaS_travsymbol(checkfunc)) != NULL)
541 return "global";618 return "global";
619 else if ((*name = luaT_travtagmethods(checkfunc)) != NULL)
620 return "tag-method";
542 else return "";621 else return "";
543}622}
544 623
624/* }====================================================== */
625
626
545/*627/*
546** =======================================================628** {======================================================
547** BLOCK mechanism629** BLOCK mechanism
548** =======================================================630** =======================================================
549*/631*/
550 632
551 633
552void lua_beginblock (void)634#ifndef MAX_C_BLOCKS
553{635#define MAX_C_BLOCKS 1000 /* arbitrary limit */
554 if (L->numCblocks >= MAX_C_BLOCKS)636#endif
555 lua_error("too many nested blocks");637
638
639void lua_beginblock (void) {
640 luaM_growvector(L->Cblocks, L->numCblocks, 1, struct C_Lua_Stack,
641 "too many nested blocks", MAX_C_BLOCKS);
556 L->Cblocks[L->numCblocks] = L->Cstack;642 L->Cblocks[L->numCblocks] = L->Cstack;
557 L->numCblocks++;643 L->numCblocks++;
558}644}
559 645
560void lua_endblock (void)646void lua_endblock (void) {
561{
562 --L->numCblocks;647 --L->numCblocks;
563 L->Cstack = L->Cblocks[L->numCblocks];648 L->Cstack = L->Cblocks[L->numCblocks];
564 luaD_adjusttop(L->Cstack.base);649 luaD_adjusttop(L->Cstack.base);
@@ -566,8 +651,7 @@ void lua_endblock (void) · 1 unmodified line
566 651
567 652
568 653
569int lua_ref (int lock)654int lua_ref (int lock) {
570{
571 int ref;655 int ref;
572 checkCparams(1);656 checkCparams(1);
573 ref = luaC_ref(L->stack.top-1, lock);657 ref = luaC_ref(L->stack.top-1, lock);
@@ -577,32 +661,12 @@ int lua_ref (int lock) · 3 unmodified lines
577 661
578 662
579 663
580lua_Object lua_getref (int ref)664lua_Object lua_getref (int ref) {
581{
582 TObject *o = luaC_getref(ref);665 TObject *o = luaC_getref(ref);
583 return (o ? put_luaObject(o) : LUA_NOOBJECT);666 return (o ? put_luaObject(o) : LUA_NOOBJECT);
584}667}
585 668
586 669/* }====================================================== */
587/*
588** =======================================================
589** Derived functions
590** =======================================================
591*/
592int (lua_call) (char *name) { return lua_call(name); }
593
594void (lua_pushref) (int ref) { lua_pushref(ref); }
595
596int (lua_refobject) (lua_Object o, int l) { return lua_refobject(o, l); }
597
598void (lua_register) (char *n, lua_CFunction f) { lua_register(n, f); }
599
600void (lua_pushuserdata) (void *u) { lua_pushuserdata(u); }
601
602void (lua_pushcfunction) (lua_CFunction f) { lua_pushcfunction(f); }
603
604int (lua_clonetag) (int t) { return lua_clonetag(t); }
605
606 670
607 671
608 672
@@ -611,17 +675,15 @@ int (lua_clonetag) (int t) { return lua_clonetag(t); } · 2 unmodified lines
611** API: set a function as a fallback675** API: set a function as a fallback
612*/676*/
613 677
614static void do_unprotectedrun (lua_CFunction f, int nParams, int nResults)678static void do_unprotectedrun (lua_CFunction f, int nParams, int nResults) {
615{
616 StkId base = (L->stack.top-L->stack.stack)-nParams;
617 luaD_openstack(nParams);679 luaD_openstack(nParams);
618 L->stack.stack[base].ttype = LUA_T_CPROTO;680 (L->stack.top-nParams)->ttype = LUA_T_CPROTO;
619 L->stack.stack[base].value.f = f;681 (L->stack.top-nParams)->value.f = f;
620 luaD_call(base+1, nResults);682 luaD_calln(nParams, nResults);
621}683}
622 684
623lua_Object lua_setfallback (char *name, lua_CFunction fallback)685
624{686lua_Object lua_setfallback (char *name, lua_CFunction fallback) {
625 lua_pushstring(name);687 lua_pushstring(name);
626 lua_pushcfunction(fallback);688 lua_pushcfunction(fallback);
627 do_unprotectedrun(luaT_setfallback, 2, 1);689 do_unprotectedrun(luaT_setfallback, 2, 1);
src/lapi.h+3−1
@@ -1,5 +1,5 @@
1/*1/*
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 $
3** Auxiliary functions from Lua API3** Auxiliary functions from Lua API
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -16,5 +16,7 @@ TObject *luaA_Address (lua_Object o); · 10 unmodified lines
16void luaA_pushobject (TObject *o);16void luaA_pushobject (TObject *o);
17void luaA_packresults (void);17void luaA_packresults (void);
18int luaA_passresults (void);18int luaA_passresults (void);
19TaggedString *luaA_nextvar (TaggedString *g);
20int luaA_next (Hash *t, int i);
19 21
20#endif22#endif
src/lauxlib.c+29−7
@@ -1,5 +1,5 @@
1/*1/*
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 $
3** Auxiliary functions for building Lua libraries3** Auxiliary functions for building Lua libraries
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -10,9 +10,10 @@ · 4 unmodified lines
10#include <string.h>10#include <string.h>
11 11
12/* Please Notice: This file uses only the official API of Lua12/* Please Notice: This file uses only the official API of Lua
13** Any function declared here could be written as an application13** Any function declared here could be written as an application function.
14** function. With care, these functions can be used by other libraries.14** With care, these functions can be used by other libraries.
15*/15*/
16
16#include "lauxlib.h"17#include "lauxlib.h"
17#include "lua.h"18#include "lua.h"
18#include "luadebug.h"19#include "luadebug.h"
@@ -27,12 +28,13 @@ int luaL_findstring (char *name, char *list[]) { · 8 unmodified lines
27 return -1; /* name not found */28 return -1; /* name not found */
28}29}
29 30
30void luaL_argerror (int numarg, char *extramsg)31void luaL_argerror (int numarg, char *extramsg) {
31{32 lua_Function f = lua_stackedfunction(0);
32 char *funcname;33 char *funcname;
33 lua_getobjname(lua_stackedfunction(0), &funcname);34 lua_getobjname(f, &funcname);
35 numarg -= lua_nups(f);
34 if (funcname == NULL)36 if (funcname == NULL)
35 funcname = "???";37 funcname = "?";
36 if (extramsg == NULL)38 if (extramsg == NULL)
37 luaL_verror("bad argument #%d to function `%.50s'", numarg, funcname);39 luaL_verror("bad argument #%d to function `%.50s'", numarg, funcname);
38 else40 else
@@ -109,3 +111,23 @@ void luaL_verror (char *fmt, ...) · 70 unmodified lines
109 lua_error(buff);111 lua_error(buff);
110}112}
111 113
114
115void 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
130void 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 @@
1/*1/*
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 $
3** Auxiliary functions for building Lua libraries3** Auxiliary functions for building Lua libraries
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -16,70 +16,60 @@ · 10 unmodified lines
16** Auxiliary buffer16** Auxiliary buffer
17-------------------------------------------------------*/17-------------------------------------------------------*/
18 18
19#define BUFF_STEP 3219
20#define EXTRABUFF 32
21
20 22
21#define openspace(size) if (L->Mbuffnext+(size) > L->Mbuffsize) Openspace(size)23#define openspace(size) if (L->Mbuffnext+(size) > L->Mbuffsize) Openspace(size)
22 24
23static void Openspace (int size)25static void Openspace (int size) {
24{
25 lua_State *l = L; /* to optimize */26 lua_State *l = L; /* to optimize */
26 int base = l->Mbuffbase-l->Mbuffer;27 size += EXTRABUFF;
27 l->Mbuffsize *= 2;28 l->Mbuffsize = l->Mbuffnext+size;
28 if (l->Mbuffnext+size > l->Mbuffsize) /* still not big enough? */29 luaM_growvector(l->Mbuffer, l->Mbuffnext, size, char, arrEM, MAX_INT);
29 l->Mbuffsize = l->Mbuffnext+size;
30 l->Mbuffer = luaM_realloc(l->Mbuffer, l->Mbuffsize);
31 l->Mbuffbase = l->Mbuffer+base;
32}30}
33 31
34 32
35char *luaL_openspace (int size)33char *luaL_openspace (int size) {
36{
37 openspace(size);34 openspace(size);
38 return L->Mbuffer+L->Mbuffnext;35 return L->Mbuffer+L->Mbuffnext;
39}36}
40 37
41 38
42void luaL_addchar (int c)39void luaL_addchar (int c) {
43{40 openspace(1);
44 openspace(BUFF_STEP);41 L->Mbuffer[L->Mbuffnext++] = (char)c;
45 L->Mbuffer[L->Mbuffnext++] = c;
46}42}
47 43
48 44
49void luaL_resetbuffer (void)45void luaL_resetbuffer (void) {
50{46 L->Mbuffnext = L->Mbuffbase;
51 L->Mbuffnext = L->Mbuffbase-L->Mbuffer;
52}47}
53 48
54 49
55void luaL_addsize (int n)50void luaL_addsize (int n) {
56{
57 L->Mbuffnext += n;51 L->Mbuffnext += n;
58}52}
59 53
60int luaL_getsize (void)54int luaL_getsize (void) {
61{55 return L->Mbuffnext-L->Mbuffbase;
62 return L->Mbuffnext-(L->Mbuffbase-L->Mbuffer);
63}56}
64 57
65int luaL_newbuffer (int size)58int luaL_newbuffer (int size) {
66{59 int old = L->Mbuffbase;
67 int old = L->Mbuffbase-L->Mbuffer;
68 openspace(size);60 openspace(size);
69 L->Mbuffbase = L->Mbuffer+L->Mbuffnext;61 L->Mbuffbase = L->Mbuffnext;
70 return old;62 return old;
71}63}
72 64
73 65
74void luaL_oldbuffer (int old)66void luaL_oldbuffer (int old) {
75{67 L->Mbuffnext = L->Mbuffbase;
76 L->Mbuffnext = L->Mbuffbase-L->Mbuffer;68 L->Mbuffbase = old;
77 L->Mbuffbase = L->Mbuffer+old;
78}69}
79 70
80 71
81char *luaL_buffer (void)72char *luaL_buffer (void) {
82{73 return L->Mbuffer+L->Mbuffbase;
83 return L->Mbuffbase;
84}74}
85 75
src/lbuiltin.c+488−278
@@ -1,5 +1,5 @@
1/*1/*
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 $
3** Built-in functions3** Built-in functions
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -23,11 +23,18 @@ · 17 unmodified lines
23#include "ltm.h"23#include "ltm.h"
24#include "lua.h"24#include "lua.h"
25#include "lundump.h"25#include "lundump.h"
26#include "lvm.h"
26 27
27 28
28 29
29static void pushstring (TaggedString *s)30/*
30{31** {======================================================
32** Auxiliary functions
33** =======================================================
34*/
35
36
37static void pushtagstring (TaggedString *s) {
31 TObject o;38 TObject o;
32 o.ttype = LUA_T_STRING;39 o.ttype = LUA_T_STRING;
33 o.value.ts = s;40 o.value.ts = s;
@@ -35,209 +42,126 @@ static void pushstring (TaggedString *s) · 1 unmodified line
35}42}
36 43
37 44
38static void nextvar (void)45static real getsize (Hash *h) {
39{46 real max = 0;
40 TObject *o = luaA_Address(luaL_nonnullarg(1));47 int i;
41 TaggedString *g;48 for (i = 0; i<nhash(h); i++) {
42 if (ttype(o) == LUA_T_NIL)49 Node *n = h->node+i;
43 g = (TaggedString *)L->rootglobal.next;50 if (ttype(ref(n)) == LUA_T_NUMBER &&
44 else {51 ttype(val(n)) != LUA_T_NIL &&
45 luaL_arg_check(ttype(o) == LUA_T_STRING, 1, "variable name expected");52 nvalue(ref(n)) > max)
46 g = tsvalue(o);53 max = nvalue(ref(n));
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);
56 }54 }
57 else lua_pushnil();55 return max;
58}56}
59 57
60 58
61static void foreachvar (void)59static real getnarg (Hash *a) {
62{60 TObject index;
63 TObject f = *luaA_Address(luaL_functionarg(1));61 TObject *value;
64 GCnode *g;62 /* value = table.n */
65 StkId name = L->Cstack.base++; /* place to keep var name (to avoid GC) */63 ttype(&index) = LUA_T_STRING;
66 ttype(L->stack.stack+name) = LUA_T_NIL;64 tsvalue(&index) = luaS_new("n");
67 L->stack.top++;65 value = luaH_get(a, &index);
68 for (g = L->rootglobal.next; g; g = g->next) {66 return (ttype(value) == LUA_T_NUMBER) ? nvalue(value) : getsize(a);
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 }
82}67}
83 68
84 69
85static void next (void)70static Hash *gethash (int arg) {
86{71 return avalue(luaA_Address(luaL_tablearg(arg)));
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();
95}72}
96 73
97 74/* }====================================================== */
98static 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}
116 75
117 76
118static void internaldostring (void)77/*
119{78** {======================================================
120 long l;79** Functions that use only the official API
121 char *s = luaL_check_lstr(1, &l);80** =======================================================
122 if (*s == ID_CHUNK)81*/
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}
128 82
129 83
130static void internaldofile (void)84/*
131{85** If your system does not support "stderr", redefine this function, or
132 char *fname = luaL_opt_string(1, NULL);86** redefine _ERRORMESSAGE so that it won't need _ALERT.
133 if (lua_dofile(fname) == 0)87*/
134 if (luaA_passresults() == 0)88static void luaB_alert (void) {
135 lua_pushuserdata(NULL); /* at least one result to signal no errors */89 fputs(luaL_check_string(1), stderr);
136}90}
137 91
138 92
139static void to_string (void) {93/*
140 lua_Object obj = lua_getparam(1);94** Standard implementation of _ERRORMESSAGE.
141 char *buff = luaL_openspace(30);95** The library "iolib" redefines _ERRORMESSAGE for better error information.
142 TObject *o = luaA_Address(obj);96*/
143 switch (ttype(o)) {97static void error_message (void) {
144 case LUA_T_NUMBER:98 lua_Object al = lua_rawgetglobal("_ALERT");
145 lua_pushstring(lua_getstring(obj));99 if (lua_isfunction(al)) { /* avoid error loop if _ALERT is not defined */
146 return;100 char buff[600];
147 case LUA_T_STRING:101 sprintf(buff, "lua error: %.500s\n", luaL_check_string(1));
148 lua_pushobject(obj);102 lua_pushstring(buff);
149 return;103 lua_callfunction(al);
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");
175 }104 }
176 lua_pushstring(buff);
177}105}
178 106
179 107
180static void luaI_print (void) {108/*
181 TaggedString *ts = luaS_new("tostring");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
118static void luaB_print (void) {
119 lua_Object args[MAXPRINT];
182 lua_Object obj;120 lua_Object obj;
183 int i = 1;121 int n = 0;
184 while ((obj = lua_getparam(i++)) != LUA_NOOBJECT) {122 int i;
185 luaA_pushobject(&ts->u.s.globalval);123 while ((obj = lua_getparam(n+1)) != LUA_NOOBJECT) {
186 lua_pushobject(obj);124 luaL_arg_check(n < MAXPRINT, n+1, "too many arguments");
187 luaD_call((L->stack.top-L->stack.stack)-1, 1);125 args[n++] = obj;
188 if (ttype(L->stack.top-1) != LUA_T_STRING)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))
189 lua_error("`tostring' must return a string to `print'");133 lua_error("`tostring' must return a string to `print'");
190 printf("%s\t", svalue(L->stack.top-1));134 if (i>0) fputs("\t", stdout);
191 L->stack.top--;135 fputs(lua_getstring(obj), stdout);
192 }136 }
193 printf("\n");137 fputs("\n", stdout);
194}
195
196
197static 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));
202}138}
203 139
204 140
205static void tonumber (void)141static void luaB_tonumber (void) {
206{142 int base = luaL_opt_int(2, 10);
207 int base = luaL_opt_number(2, 10);
208 if (base == 10) { /* standard conversion */143 if (base == 10) { /* standard conversion */
209 lua_Object o = lua_getparam(1);144 lua_Object o = lua_getparam(1);
210 if (lua_isnumber(o))145 if (lua_isnumber(o)) lua_pushnumber(lua_getnumber(o));
211 lua_pushnumber(lua_getnumber(o));146 else lua_pushnil(); /* not a number */
212 }147 }
213 else {148 else {
214 char *s = luaL_check_string(1);149 char *s = luaL_check_string(1);
215 unsigned long n;150 long n;
216 luaL_arg_check(0 <= base && base <= 36, 2, "base out of range");151 luaL_arg_check(0 <= base && base <= 36, 2, "base out of range");
217 n = strtol(s, &s, base);152 n = strtol(s, &s, base);
218 while (isspace(*s)) s++; /* skip trailing spaces */153 while (isspace((unsigned char)*s)) s++; /* skip trailing spaces */
219 if (*s) lua_pushnil(); /* invalid format: return nil */154 if (*s) lua_pushnil(); /* invalid format: return nil */
220 else lua_pushnumber(n);155 else lua_pushnumber(n);
221 }156 }
222}157}
223 158
224 159
225static void luaI_error (void)160static void luaB_error (void) {
226{
227 lua_error(lua_getstring(lua_getparam(1)));161 lua_error(lua_getstring(lua_getparam(1)));
228}162}
229 163
230 164static void luaB_setglobal (void) {
231static 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
239static void setglobal (void)
240{
241 char *n = luaL_check_string(1);165 char *n = luaL_check_string(1);
242 lua_Object value = luaL_nonnullarg(2);166 lua_Object value = luaL_nonnullarg(2);
243 lua_pushobject(value);167 lua_pushobject(value);
@@ -245,8 +169,7 @@ static void setglobal (void) · 1 unmodified line
245 lua_pushobject(value); /* return given value */169 lua_pushobject(value); /* return given value */
246}170}
247 171
248static void rawsetglobal (void)172static void luaB_rawsetglobal (void) {
249{
250 char *n = luaL_check_string(1);173 char *n = luaL_check_string(1);
251 lua_Object value = luaL_nonnullarg(2);174 lua_Object value = luaL_nonnullarg(2);
252 lua_pushobject(value);175 lua_pushobject(value);
@@ -254,51 +177,111 @@ static void rawsetglobal (void) · 1 unmodified line
254 lua_pushobject(value); /* return given value */177 lua_pushobject(value); /* return given value */
255}178}
256 179
257static void getglobal (void)180static void luaB_getglobal (void) {
258{
259 lua_pushobject(lua_getglobal(luaL_check_string(1)));181 lua_pushobject(lua_getglobal(luaL_check_string(1)));
260}182}
261 183
262static void rawgetglobal (void)184static void luaB_rawgetglobal (void) {
263{
264 lua_pushobject(lua_rawgetglobal(luaL_check_string(1)));185 lua_pushobject(lua_rawgetglobal(luaL_check_string(1)));
265}186}
266 187
267static void luatag (void)188static void luaB_luatag (void) {
268{
269 lua_pushnumber(lua_tag(lua_getparam(1)));189 lua_pushnumber(lua_tag(lua_getparam(1)));
270}190}
271 191
192static 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
199static void luaB_newtag (void) {
200 lua_pushnumber(lua_newtag());
201}
202
203static void luaB_copytagmethods (void) {
204 lua_pushnumber(lua_copytagmethods(luaL_check_int(1),
205 luaL_check_int(2)));
206}
207
208static void luaB_rawgettable (void) {
209 lua_pushobject(luaL_nonnullarg(1));
210 lua_pushobject(luaL_nonnullarg(2));
211 lua_pushobject(lua_rawgettable());
212}
213
214static 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
221static 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
227static void luaB_gettagmethod (void) {
228 lua_pushobject(lua_gettagmethod(luaL_check_int(1), luaL_check_string(2)));
229}
272 230
273static int getnarg (lua_Object table)231static void luaB_seterrormethod (void) {
274{232 lua_Object nf = luaL_functionarg(1);
275 lua_Object temp;233 lua_pushobject(nf);
276 /* temp = table.n */234 lua_pushobject(lua_seterrormethod());
277 lua_pushobject(table); lua_pushstring("n"); temp = lua_rawgettable();235}
278 return (lua_isnumber(temp) ? lua_getnumber(temp) : MAX_INT);236
237static void luaB_collectgarbage (void) {
238 lua_pushnumber(lua_collectgarbage(luaL_opt_int(1, 0)));
279}239}
280 240
281static void luaI_call (void)241/* }====================================================== */
282{242
243
244/*
245** {======================================================
246** Functions that could use only the official API but
247** do not, for efficiency.
248** =======================================================
249*/
250
251static 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
262static 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
270static void luaB_call (void) {
283 lua_Object f = luaL_nonnullarg(1);271 lua_Object f = luaL_nonnullarg(1);
284 lua_Object arg = luaL_tablearg(2);272 Hash *arg = gethash(2);
285 char *options = luaL_opt_string(3, "");273 char *options = luaL_opt_string(3, "");
286 lua_Object err = lua_getparam(4);274 lua_Object err = lua_getparam(4);
287 int narg = getnarg(arg);275 int narg = (int)getnarg(arg);
288 int i, status;276 int i, status;
289 if (err != LUA_NOOBJECT) { /* set new error method */277 if (err != LUA_NOOBJECT) { /* set new error method */
290 lua_pushobject(err);278 lua_pushobject(err);
291 err = lua_seterrormethod();279 err = lua_seterrormethod();
292 }280 }
293 /* push arg[1...n] */281 /* push arg[1...n] */
294 for (i=0; i<narg; i++) {282 luaD_checkstack(narg);
295 lua_Object temp;283 for (i=0; i<narg; i++)
296 /* temp = arg[i+1] */284 *(L->stack.top++) = *luaH_getint(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 }
302 status = lua_callfunction(f);285 status = lua_callfunction(f);
303 if (err != LUA_NOOBJECT) { /* restore old error method */286 if (err != LUA_NOOBJECT) { /* restore old error method */
304 lua_pushobject(err);287 lua_pushobject(err);
@@ -312,7 +295,7 @@ static void luaI_call (void) · 7 unmodified lines
312 else295 else
313 lua_error(NULL);296 lua_error(NULL);
314 }297 }
315 else { /* no errors */298 else { /* no errors */
316 if (strchr(options, 'p'))299 if (strchr(options, 'p'))
317 luaA_packresults();300 luaA_packresults();
318 else301 else
@@ -321,91 +304,306 @@ static void luaI_call (void) · 2 unmodified lines
321}304}
322 305
323 306
324static void settag (void)307static void luaB_nextvar (void) {
325{308 TObject *o = luaA_Address(luaL_nonnullarg(1));
326 lua_Object o = luaL_tablearg(1);309 TaggedString *g;
327 lua_pushobject(o);310 if (ttype(o) == LUA_T_NIL)
328 lua_settag(luaL_check_number(2));311 g = NULL;
329 lua_pushobject(o); /* returns first argument */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();
330}318}
331 319
332 320
333static void newtag (void)321static void luaB_next (void) {
334{322 Hash *a = gethash(1);
335 lua_pushnumber(lua_newtag());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();
336}327}
337 328
338 329
339static void copytagmethods (void)330static void luaB_tostring (void) {
340{331 lua_Object obj = lua_getparam(1);
341 lua_pushnumber(lua_copytagmethods(luaL_check_number(1),332 TObject *o = luaA_Address(obj);
342 luaL_check_number(2)));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);
343}363}
344 364
345 365
346static void rawgettable (void)366static void luaB_type (void) {
347{367 lua_Object o = luaL_nonnullarg(1);
348 lua_pushobject(luaL_nonnullarg(1));368 lua_pushstring(luaO_typename(luaA_Address(o)));
349 lua_pushobject(luaL_nonnullarg(2));369 lua_pushnumber(lua_tag(o));
350 lua_pushobject(lua_rawgettable());
351}370}
352 371
372/* }====================================================== */
353 373
354static void rawsettable (void)374
355{375
356 lua_pushobject(luaL_nonnullarg(1));376/*
357 lua_pushobject(luaL_nonnullarg(2));377** {======================================================
358 lua_pushobject(luaL_nonnullarg(3));378** "Extra" functions
359 lua_rawsettable();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
386static 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, ""));
360}390}
361 391
362 392
363static void settagmethod (void)393static void luaB_foreachi (void) {
364{394 Hash *t = gethash(1);
365 lua_Object nf = luaL_nonnullarg(3);395 int i;
366 lua_pushobject(nf);396 int n = (int)getnarg(t);
367 lua_pushobject(lua_settagmethod((int)luaL_check_number(1),397 TObject f;
368 luaL_check_string(2)));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 }
369}412}
370 413
371 414
372static void gettagmethod (void)415static void luaB_foreach (void) {
373{416 Hash *a = gethash(1);
374 lua_pushobject(lua_gettagmethod((int)luaL_check_number(1),417 int i;
375 luaL_check_string(2)));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 }
376}433}
377 434
378 435
379static void seterrormethod (void)436static void luaB_foreachvar (void) {
380{437 GCnode *g;
381 lua_Object nf = luaL_functionarg(1);438 TObject f; /* see comment in 'foreachi' */
382 lua_pushobject(nf);439 f = *luaA_Address(luaL_functionarg(1));
383 lua_pushobject(lua_seterrormethod());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
460static void luaB_getn (void) {
461 lua_pushnumber(getnarg(gethash(1)));
462}
463
464
465static 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
483static 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 */
384}493}
385 494
386 495
387static void luaI_collectgarbage (void)496/* {
388{497** Quicksort
389 lua_pushnumber(lua_collectgarbage(luaL_opt_number(1, 0)));498*/
499
500static 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
507static 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
525static 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
568static 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);
390}578}
391 579
580/* }}===================================================== */
581
392 582
393/*583/*
394** =======================================================584** ====================================================== */
585
586
587
588#ifdef DEBUG
589/*
590** {======================================================
395** some DEBUG functions591** some DEBUG functions
396** =======================================================592** =======================================================
397*/593*/
398#ifdef DEBUG
399 594
400static void mem_query (void)595static void mem_query (void) {
401{
402 lua_pushnumber(totalmem);596 lua_pushnumber(totalmem);
403 lua_pushnumber(numblocks);597 lua_pushnumber(numblocks);
404}598}
405 599
406 600
407static void countlist (void)601static void query_strings (void) {
408{602 lua_pushnumber(L->string_root[luaL_check_int(1)].nuse);
603}
604
605
606static void countlist (void) {
409 char *s = luaL_check_string(1);607 char *s = luaL_check_string(1);
410 GCnode *l = (s[0]=='t') ? L->roottable.next : (s[0]=='c') ? L->rootcl.next :608 GCnode *l = (s[0]=='t') ? L->roottable.next : (s[0]=='c') ? L->rootcl.next :
411 (s[0]=='p') ? L->rootproto.next : L->rootglobal.next;609 (s[0]=='p') ? L->rootproto.next : L->rootglobal.next;
@@ -418,8 +616,7 @@ static void countlist (void) · 6 unmodified lines
418}616}
419 617
420 618
421static void testC (void)619static void testC (void) {
422{
423#define getnum(s) ((*s++) - '0')620#define getnum(s) ((*s++) - '0')
424#define getname(s) (nome[0] = *s++, nome)621#define getname(s) (nome[0] = *s++, nome)
425 622
@@ -428,7 +625,7 @@ static void testC (void) · 2 unmodified lines
428 char nome[2];625 char nome[2];
429 char *s = luaL_check_string(1);626 char *s = luaL_check_string(1);
430 nome[1] = 0;627 nome[1] = 0;
431 while (1) {628 for (;;) {
432 switch (*s++) {629 switch (*s++) {
433 case '0': case '1': case '2': case '3': case '4':630 case '0': case '1': case '2': case '3': case '4':
434 case '5': case '6': case '7': case '8': case '9':631 case '5': case '6': case '7': case '8': case '9':
@@ -454,11 +651,17 @@ static void testC (void) · 19 unmodified lines
454 case '=': lua_setglobal(getname(s)); break;651 case '=': lua_setglobal(getname(s)); break;
455 case 's': lua_pushstring(getname(s)); break;652 case 's': lua_pushstring(getname(s)); break;
456 case 'o': lua_pushobject(reg[getnum(s)]); break;653 case 'o': lua_pushobject(reg[getnum(s)]); break;
457 case 'f': (lua_call)(getname(s)); break;654 case 'f': lua_call(getname(s)); break;
458 case 'i': reg[getnum(s)] = lua_gettable(); break;655 case 'i': reg[getnum(s)] = lua_gettable(); break;
459 case 'I': reg[getnum(s)] = lua_rawgettable(); break;656 case 'I': reg[getnum(s)] = lua_rawgettable(); break;
460 case 't': lua_settable(); break;657 case 't': lua_settable(); break;
461 case 'T': lua_rawsettable(); break;658 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 }
462 default: luaL_verror("unknown command in `testC': %c", *(s-1));665 default: luaL_verror("unknown command in `testC': %c", *(s-1));
463 }666 }
464 if (*s == 0) return;667 if (*s == 0) return;
@@ -466,13 +669,12 @@ static void testC (void) · 1 unmodified line
466 }669 }
467}670}
468 671
672/* }====================================================== */
469#endif673#endif
470 674
471 675
472/*676
473** Internal functions677static struct luaL_reg builtin_funcs[] = {
474*/
475static struct luaL_reg int_funcs[] = {
476#ifdef LUA_COMPAT2_5678#ifdef LUA_COMPAT2_5
477 {"setfallback", luaT_setfallback},679 {"setfallback", luaT_setfallback},
478#endif680#endif
@@ -480,46 +682,54 @@ static struct luaL_reg int_funcs[] = { · 1 unmodified line
480 {"testC", testC},682 {"testC", testC},
481 {"totalmem", mem_query},683 {"totalmem", mem_query},
482 {"count", countlist},684 {"count", countlist},
685 {"querystr", query_strings},
483#endif686#endif
484 {"assert", luaI_assert},687 {"_ALERT", luaB_alert},
485 {"call", luaI_call},688 {"_ERRORMESSAGE", error_message},
486 {"collectgarbage", luaI_collectgarbage},689 {"call", luaB_call},
487 {"dofile", internaldofile},690 {"collectgarbage", luaB_collectgarbage},
488 {"copytagmethods", copytagmethods},691 {"copytagmethods", luaB_copytagmethods},
489 {"dostring", internaldostring},692 {"dofile", luaB_dofile},
490 {"error", luaI_error},693 {"dostring", luaB_dostring},
491 {"foreach", foreach},694 {"error", luaB_error},
492 {"foreachvar", foreachvar},695 {"getglobal", luaB_getglobal},
493 {"getglobal", getglobal},696 {"gettagmethod", luaB_gettagmethod},
494 {"newtag", newtag},697 {"newtag", luaB_newtag},
495 {"next", next},698 {"next", luaB_next},
496 {"nextvar", nextvar},699 {"nextvar", luaB_nextvar},
497 {"print", luaI_print},700 {"print", luaB_print},
498 {"rawgetglobal", rawgetglobal},701 {"rawgetglobal", luaB_rawgetglobal},
499 {"rawgettable", rawgettable},702 {"rawgettable", luaB_rawgettable},
500 {"rawsetglobal", rawsetglobal},703 {"rawsetglobal", luaB_rawsetglobal},
501 {"rawsettable", rawsettable},704 {"rawsettable", luaB_rawsettable},
502 {"seterrormethod", seterrormethod},705 {"seterrormethod", luaB_seterrormethod},
503 {"setglobal", setglobal},706 {"setglobal", luaB_setglobal},
504 {"settagmethod", settagmethod},707 {"settag", luaB_settag},
505 {"gettagmethod", gettagmethod},708 {"settagmethod", luaB_settagmethod},
506 {"settag", settag},709 {"tag", luaB_luatag},
507 {"tonumber", tonumber},710 {"tonumber", luaB_tonumber},
508 {"tostring", to_string},711 {"tostring", luaB_tostring},
509 {"tag", luatag},712 {"type", luaB_type},
510 {"type", luaI_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}
511};722};
512 723
513 724
514#define INTFUNCSIZE (sizeof(int_funcs)/sizeof(int_funcs[0]))725#define INTFUNCSIZE (sizeof(builtin_funcs)/sizeof(builtin_funcs[0]))
515 726
516 727
517void luaB_predefine (void)728void luaB_predefine (void) {
518{
519 /* pre-register mem error messages, to avoid loop when error arises */729 /* pre-register mem error messages, to avoid loop when error arises */
520 luaS_newfixedstring(tableEM);730 luaS_newfixedstring(tableEM);
521 luaS_newfixedstring(memEM);731 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])));
523 lua_pushstring(LUA_VERSION);733 lua_pushstring(LUA_VERSION);
524 lua_setglobal("_VERSION");734 lua_setglobal("_VERSION");
525}735}
src/ldo.c+90−132
@@ -1,5 +1,5 @@
1/*1/*
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 $
3** Stack and Call structure of Lua3** Stack and Call structure of Lua
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -10,6 +10,7 @@ · 4 unmodified lines
10#include <stdlib.h>10#include <stdlib.h>
11#include <string.h>11#include <string.h>
12 12
13#include "lauxlib.h"
13#include "ldo.h"14#include "ldo.h"
14#include "lfunc.h"15#include "lfunc.h"
15#include "lgc.h"16#include "lgc.h"
@@ -17,6 +18,7 @@ · 1 unmodified line
17#include "lobject.h"18#include "lobject.h"
18#include "lparser.h"19#include "lparser.h"
19#include "lstate.h"20#include "lstate.h"
21#include "lstring.h"
20#include "ltm.h"22#include "ltm.h"
21#include "lua.h"23#include "lua.h"
22#include "luadebug.h"24#include "luadebug.h"
@@ -27,42 +29,33 @@ · 4 unmodified lines
27 29
28 30
29#ifndef STACK_LIMIT31#ifndef STACK_LIMIT
30#define STACK_LIMIT 600032#define STACK_LIMIT 6000 /* arbitrary limit */
31#endif33#endif
32 34
33 35
34 36
35/*37#define STACK_UNIT 128
36** Error messages
37*/
38
39static void stderrorim (void)
40{
41 fprintf(stderr, "lua error: %s\n", lua_getstring(lua_getparam(1)));
42}
43
44 38
45 39
46#define STACK_UNIT 12840#ifdef DEBUG
41#undef STACK_UNIT
42#define STACK_UNIT 2
43#endif
47 44
48 45
49void luaD_init (void)46void luaD_init (void) {
50{
51 L->stack.stack = luaM_newvector(STACK_UNIT, TObject);47 L->stack.stack = luaM_newvector(STACK_UNIT, TObject);
52 L->stack.top = L->stack.stack;48 L->stack.top = L->stack.stack;
53 L->stack.last = L->stack.stack+(STACK_UNIT-1);49 L->stack.last = L->stack.stack+(STACK_UNIT-1);
54 ttype(&L->errorim) = LUA_T_CPROTO;
55 fvalue(&L->errorim) = stderrorim;
56}50}
57 51
58 52
59void luaD_checkstack (int n)53void luaD_checkstack (int n) {
60{
61 struct Stack *S = &L->stack;54 struct Stack *S = &L->stack;
62 if (S->last-S->top <= n) {55 if (S->last-S->top <= n) {
63 StkId top = S->top-S->stack;56 StkId top = S->top-S->stack;
64 int stacksize = (S->last-S->stack)+1+STACK_UNIT+n;57 int stacksize = (S->last-S->stack)+STACK_UNIT+n;
65 S->stack = luaM_reallocvector(S->stack, stacksize, TObject);58 luaM_reallocvector(S->stack, stacksize, TObject);
66 S->last = S->stack+(stacksize-1);59 S->last = S->stack+(stacksize-1);
67 S->top = S->stack + top;60 S->top = S->stack + top;
68 if (stacksize >= STACK_LIMIT) { /* stack overflow? */61 if (stacksize >= STACK_LIMIT) { /* stack overflow? */
@@ -78,8 +71,7 @@ void luaD_checkstack (int n) · 9 unmodified lines
78/*71/*
79** Adjust stack. Set top to the given value, pushing NILs if needed.72** Adjust stack. Set top to the given value, pushing NILs if needed.
80*/73*/
81void luaD_adjusttop (StkId newtop)74void luaD_adjusttop (StkId newtop) {
82{
83 int diff = newtop-(L->stack.top-L->stack.stack);75 int diff = newtop-(L->stack.top-L->stack.stack);
84 if (diff <= 0)76 if (diff <= 0)
85 L->stack.top += diff;77 L->stack.top += diff;
@@ -94,38 +86,35 @@ void luaD_adjusttop (StkId newtop) · 8 unmodified lines
94/*86/*
95** Open a hole below "nelems" from the L->stack.top.87** Open a hole below "nelems" from the L->stack.top.
96*/88*/
97void luaD_openstack (int nelems)89void luaD_openstack (int nelems) {
98{
99 luaO_memup(L->stack.top-nelems+1, L->stack.top-nelems,90 luaO_memup(L->stack.top-nelems+1, L->stack.top-nelems,
100 nelems*sizeof(TObject));91 nelems*sizeof(TObject));
101 incr_top;92 incr_top;
102}93}
103 94
104 95
105void luaD_lineHook (int line)96void luaD_lineHook (int line) {
106{
107 struct C_Lua_Stack oldCLS = L->Cstack;97 struct C_Lua_Stack oldCLS = L->Cstack;
108 StkId old_top = L->Cstack.lua2C = L->Cstack.base = L->stack.top-L->stack.stack;98 StkId old_top = L->Cstack.lua2C = L->Cstack.base = L->stack.top-L->stack.stack;
109 L->Cstack.num = 0;99 L->Cstack.num = 0;
110 (*lua_linehook)(line);100 (*L->linehook)(line);
111 L->stack.top = L->stack.stack+old_top;101 L->stack.top = L->stack.stack+old_top;
112 L->Cstack = oldCLS;102 L->Cstack = oldCLS;
113}103}
114 104
115 105
116void luaD_callHook (StkId base, TProtoFunc *tf, int isreturn)106void luaD_callHook (StkId base, TProtoFunc *tf, int isreturn) {
117{
118 struct C_Lua_Stack oldCLS = L->Cstack;107 struct C_Lua_Stack oldCLS = L->Cstack;
119 StkId old_top = L->Cstack.lua2C = L->Cstack.base = L->stack.top-L->stack.stack;108 StkId old_top = L->Cstack.lua2C = L->Cstack.base = L->stack.top-L->stack.stack;
120 L->Cstack.num = 0;109 L->Cstack.num = 0;
121 if (isreturn)110 if (isreturn)
122 (*lua_callhook)(LUA_NOOBJECT, "(return)", 0);111 (*L->callhook)(LUA_NOOBJECT, "(return)", 0);
123 else {112 else {
124 TObject *f = L->stack.stack+base-1;113 TObject *f = L->stack.stack+base-1;
125 if (tf)114 if (tf)
126 (*lua_callhook)(Ref(f), tf->fileName->str, tf->lineDefined);115 (*L->callhook)(Ref(f), tf->source->str, tf->lineDefined);
127 else116 else
128 (*lua_callhook)(Ref(f), "(C)", -1);117 (*L->callhook)(Ref(f), "(C)", -1);
129 }118 }
130 L->stack.top = L->stack.stack+old_top;119 L->stack.top = L->stack.stack+old_top;
131 L->Cstack = oldCLS;120 L->Cstack = oldCLS;
@@ -137,28 +126,26 @@ void luaD_callHook (StkId base, TProtoFunc *tf, int isreturn) · 5 unmodified lines
137** Cstack.num is the number of arguments; Cstack.lua2C points to the126** Cstack.num is the number of arguments; Cstack.lua2C points to the
138** first argument. Returns an index to the first result from C.127** first argument. Returns an index to the first result from C.
139*/128*/
140static StkId callC (lua_CFunction f, StkId base)129static StkId callC (lua_CFunction f, StkId base) {
141{130 struct C_Lua_Stack *cls = &L->Cstack;
142 struct C_Lua_Stack *CS = &L->Cstack;131 struct C_Lua_Stack oldCLS = *cls;
143 struct C_Lua_Stack oldCLS = *CS;
144 StkId firstResult;132 StkId firstResult;
145 int numarg = (L->stack.top-L->stack.stack) - base;133 int numarg = (L->stack.top-L->stack.stack) - base;
146 CS->num = numarg;134 cls->num = numarg;
147 CS->lua2C = base;135 cls->lua2C = base;
148 CS->base = base+numarg; /* == top-stack */136 cls->base = base+numarg; /* == top-stack */
149 if (lua_callhook)137 if (L->callhook)
150 luaD_callHook(base, NULL, 0);138 luaD_callHook(base, NULL, 0);
151 (*f)(); /* do the actual call */139 (*f)(); /* do the actual call */
152 if (lua_callhook) /* func may have changed lua_callhook */140 if (L->callhook) /* func may have changed callhook */
153 luaD_callHook(base, NULL, 1);141 luaD_callHook(base, NULL, 1);
154 firstResult = CS->base;142 firstResult = cls->base;
155 *CS = oldCLS;143 *cls = oldCLS;
156 return firstResult;144 return firstResult;
157}145}
158 146
159 147
160static StkId callCclosure (struct Closure *cl, lua_CFunction f, StkId base)148static StkId callCclosure (struct Closure *cl, lua_CFunction f, StkId base) {
161{
162 TObject *pbase;149 TObject *pbase;
163 int nup = cl->nelems; /* number of upvalues */150 int nup = cl->nelems; /* number of upvalues */
164 luaD_checkstack(nup);151 luaD_checkstack(nup);
@@ -172,24 +159,25 @@ static StkId callCclosure (struct Closure *cl, lua_CFunction f, StkId base) · 7 unmodified lines
172}159}
173 160
174 161
175void luaD_callTM (TObject *f, int nParams, int nResults)162void luaD_callTM (TObject *f, int nParams, int nResults) {
176{
177 luaD_openstack(nParams);163 luaD_openstack(nParams);
178 *(L->stack.top-nParams-1) = *f;164 *(L->stack.top-nParams-1) = *f;
179 luaD_call((L->stack.top-L->stack.stack)-nParams, nResults);165 luaD_calln(nParams, nResults);
180}166}
181 167
182 168
183/*169/*
184** Call a function (C or Lua). The parameters must be on the L->stack.stack,170** Call a function (C or Lua). The parameters must be on the stack,
185** between [L->stack.stack+base,L->stack.top). The function to be called is at L->stack.stack+base-1.171** between [top-nArgs,top). The function to be called is right below the
186** When returns, the results are on the L->stack.stack, between [L->stack.stack+base-1,L->stack.top).172** arguments.
173** When returns, the results are on the stack, between [top-nArgs-1,top).
187** The number of results is nResults, unless nResults=MULT_RET.174** The number of results is nResults, unless nResults=MULT_RET.
188*/175*/
189void luaD_call (StkId base, int nResults)176void luaD_calln (int nArgs, int nResults) {
190{177 struct Stack *S = &L->stack; /* to optimize */
178 StkId base = (S->top-S->stack)-nArgs;
179 TObject *func = S->stack+base-1;
191 StkId firstResult;180 StkId firstResult;
192 TObject *func = L->stack.stack+base-1;
193 int i;181 int i;
194 switch (ttype(func)) {182 switch (ttype(func)) {
195 case LUA_T_CPROTO:183 case LUA_T_CPROTO:
@@ -214,23 +202,23 @@ void luaD_call (StkId base, int nResults) · 18 unmodified lines
214 TObject *im = luaT_getimbyObj(func, IM_FUNCTION);202 TObject *im = luaT_getimbyObj(func, IM_FUNCTION);
215 if (ttype(im) == LUA_T_NIL)203 if (ttype(im) == LUA_T_NIL)
216 lua_error("call expression not a function");204 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);
218 return;206 return;
219 }207 }
220 }208 }
221 /* adjust the number of results */209 /* adjust the number of results */
222 if (nResults != MULT_RET)210 if (nResults == MULT_RET)
211 nResults = (S->top-S->stack)-firstResult;
212 else
223 luaD_adjusttop(firstResult+nResults);213 luaD_adjusttop(firstResult+nResults);
224 /* move results to base-1 (to erase parameters and function) */214 /* move results to base-1 (to erase parameters and function) */
225 base--;215 base--;
226 nResults = L->stack.top - (L->stack.stack+firstResult); /* actual number of results */
227 for (i=0; i<nResults; i++)216 for (i=0; i<nResults; i++)
228 *(L->stack.stack+base+i) = *(L->stack.stack+firstResult+i);217 *(S->stack+base+i) = *(S->stack+firstResult+i);
229 L->stack.top -= firstResult-base;218 S->top -= firstResult-base;
230}219}
231 220
232 221
233
234/*222/*
235** Traverse all objects on L->stack.stack223** Traverse all objects on L->stack.stack
236*/224*/
@@ -243,59 +231,50 @@ void luaD_travstack (int (*fn)(TObject *)) · 6 unmodified lines
243 231
244 232
245 233
246static void message (char *s)234static void message (char *s) {
247{235 TObject *em = &(luaS_new("_ERRORMESSAGE")->u.s.globalval);
248 TObject im = L->errorim;236 if (ttype(em) == LUA_T_PROTO || ttype(em) == LUA_T_CPROTO ||
249 if (ttype(&im) != LUA_T_NIL) {237 ttype(em) == LUA_T_CLOSURE) {
238 *L->stack.top = *em;
239 incr_top;
250 lua_pushstring(s);240 lua_pushstring(s);
251 luaD_callTM(&im, 1, 0);241 luaD_calln(1, 0);
252 }242 }
253}243}
254 244
255/*245/*
256** Reports an error, and jumps up to the available recover label246** Reports an error, and jumps up to the available recover label
257*/247*/
258void lua_error (char *s)248void lua_error (char *s) {
259{
260 if (s) message(s);249 if (s) message(s);
261 if (L->errorJmp)250 if (L->errorJmp)
262 longjmp(*((jmp_buf *)L->errorJmp), 1);251 longjmp(L->errorJmp->b, 1);
263 else {252 else {
264 fprintf (stderr, "lua: exit(1). Unable to recover\n");253 message("exit(1). Unable to recover.\n");
265 exit(1);254 exit(1);
266 }255 }
267}256}
268 257
269/*
270** Call the function at L->Cstack.base, and incorporate results on
271** the Lua2C structure.
272*/
273static 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
282 258
283/*259/*
284** Execute a protected call. Assumes that function is at L->Cstack.base and260** Execute a protected call. Assumes that function is at L->Cstack.base and
285** parameters are on top of it. Leave nResults on the stack.261** parameters are on top of it. Leave nResults on the stack.
286*/262*/
287int luaD_protectedrun (int nResults)263int luaD_protectedrun (void) {
288{
289 jmp_buf myErrorJmp;
290 int status;
291 volatile struct C_Lua_Stack oldCLS = L->Cstack;264 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;
293 L->errorJmp = &myErrorJmp;268 L->errorJmp = &myErrorJmp;
294 if (setjmp(myErrorJmp) == 0) {269 if (setjmp(myErrorJmp.b) == 0) {
295 do_callinc(nResults);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 */
296 status = 0;275 status = 0;
297 }276 }
298 else { /* an error occurred: restore L->Cstack and L->stack.top */277 else { /* an error occurred: restore L->Cstack and L->stack.top */
299 L->Cstack = oldCLS;278 L->Cstack = oldCLS;
300 L->stack.top = L->stack.stack+L->Cstack.base;279 L->stack.top = L->stack.stack+L->Cstack.base;
301 status = 1;280 status = 1;
@@ -308,18 +287,20 @@ int luaD_protectedrun (int nResults) · 6 unmodified lines
308/*287/*
309** returns 0 = chunk loaded; 1 = error; 2 = no more chunks to load288** returns 0 = chunk loaded; 1 = error; 2 = no more chunks to load
310*/289*/
311static int protectedparser (ZIO *z, int bin)290static int protectedparser (ZIO *z, int bin) {
312{291 volatile struct C_Lua_Stack oldCLS = L->Cstack;
292 struct lua_longjmp myErrorJmp;
313 volatile int status;293 volatile int status;
314 TProtoFunc *volatile tf;294 TProtoFunc *volatile tf;
315 jmp_buf myErrorJmp;295 struct lua_longjmp *volatile oldErr = L->errorJmp;
316 jmp_buf *volatile oldErr = L->errorJmp;
317 L->errorJmp = &myErrorJmp;296 L->errorJmp = &myErrorJmp;
318 if (setjmp(myErrorJmp) == 0) {297 if (setjmp(myErrorJmp.b) == 0) {
319 tf = bin ? luaU_undump1(z) : luaY_parser(z);298 tf = bin ? luaU_undump1(z) : luaY_parser(z);
320 status = 0;299 status = 0;
321 }300 }
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;
323 tf = NULL;304 tf = NULL;
324 status = 1;305 status = 1;
325 }306 }
@@ -334,9 +315,9 @@ static int protectedparser (ZIO *z, int bin) · 8 unmodified lines
334}315}
335 316
336 317
337static int do_main (ZIO *z, int bin)318static int do_main (ZIO *z, int bin) {
338{
339 int status;319 int status;
320 int debug = L->debug; /* save debug status */
340 do {321 do {
341 long old_blocks = (luaC_checkGC(), L->nblocks);322 long old_blocks = (luaC_checkGC(), L->nblocks);
342 status = protectedparser(z, bin);323 status = protectedparser(z, bin);
@@ -345,10 +326,11 @@ static int do_main (ZIO *z, int bin) · 2 unmodified lines
345 else {326 else {
346 unsigned long newelems2 = 2*(L->nblocks-old_blocks);327 unsigned long newelems2 = 2*(L->nblocks-old_blocks);
347 L->GCthreshold += newelems2;328 L->GCthreshold += newelems2;
348 status = luaD_protectedrun(MULT_RET);329 status = luaD_protectedrun();
349 L->GCthreshold -= newelems2;330 L->GCthreshold -= newelems2;
350 }331 }
351 } while (bin && status == 0);332 } while (bin && status == 0);
333 L->debug = debug; /* restore debug status */
352 return status;334 return status;
353}335}
354 336
@@ -364,23 +346,24 @@ void luaD_gcIM (TObject *o) · 9 unmodified lines
364}346}
365 347
366 348
367int lua_dofile (char *filename)349#define MAXFILENAME 260 /* maximum part of a file name kept */
368{350
351int lua_dofile (char *filename) {
369 ZIO z;352 ZIO z;
370 int status;353 int status;
371 int c;354 int c;
372 int bin;355 int bin;
356 char source[MAXFILENAME];
373 FILE *f = (filename == NULL) ? stdin : fopen(filename, "r");357 FILE *f = (filename == NULL) ? stdin : fopen(filename, "r");
374 if (f == NULL)358 if (f == NULL)
375 return 2;359 return 2;
376 if (filename == NULL)
377 filename = "(stdin)";
378 c = fgetc(f);360 c = fgetc(f);
379 ungetc(c, f);361 ungetc(c, f);
380 bin = (c == ID_CHUNK);362 bin = (c == ID_CHUNK);
381 if (bin)363 if (bin)
382 f = freopen(filename, "rb", f); /* set binary mode */364 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);
384 status = do_main(&z, bin);367 status = do_main(&z, bin);
385 if (f != stdin)368 if (f != stdin)
386 fclose(f);369 fclose(f);
@@ -388,40 +371,15 @@ int lua_dofile (char *filename) · 1 unmodified line
388}371}
389 372
390 373
391#define SIZE_PREF 20 /* size of string prefix to appear in error messages */
392#define SSIZE_PREF "20"
393
394
395static 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
410int lua_dostring (char *str) {374int lua_dostring (char *str) {
411 return lua_dobuffer(str, strlen(str), NULL);375 return lua_dobuffer(str, strlen(str), str);
412}376}
413 377
414 378
415int lua_dobuffer (char *buff, int size, char *name) {379int lua_dobuffer (char *buff, int size, char *name) {
416 char newname[SIZE_PREF+25];
417 ZIO z;380 ZIO z;
418 int status;381 if (!name) name = "?";
419 if (name==NULL) {
420 build_name(buff, newname);
421 name = newname;
422 }
423 luaZ_mopen(&z, buff, size, name);382 luaZ_mopen(&z, buff, size, name);
424 status = do_main(&z, buff[0]==ID_CHUNK);383 return do_main(&z, buff[0]==ID_CHUNK);
425 return status;
426}384}
427 385
src/ldo.h+3−3
@@ -1,5 +1,5 @@
1/*1/*
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 $
3** Stack and Call structure of Lua3** Stack and Call structure of Lua
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -35,9 +35,9 @@ void luaD_adjusttop (StkId newtop); · 29 unmodified lines
35void luaD_openstack (int nelems);35void luaD_openstack (int nelems);
36void luaD_lineHook (int line);36void luaD_lineHook (int line);
37void luaD_callHook (StkId base, TProtoFunc *tf, int isreturn);37void luaD_callHook (StkId base, TProtoFunc *tf, int isreturn);
38void luaD_call (StkId base, int nResults);38void luaD_calln (int nArgs, int nResults);
39void luaD_callTM (TObject *f, int nParams, int nResults);39void luaD_callTM (TObject *f, int nParams, int nResults);
40int luaD_protectedrun (int nResults);40int luaD_protectedrun (void);
41void luaD_gcIM (TObject *o);41void luaD_gcIM (TObject *o);
42void luaD_travstack (int (*fn)(TObject *));42void luaD_travstack (int (*fn)(TObject *));
43void luaD_checkstack (int n);43void luaD_checkstack (int n);
src/lfunc.c+2−2
@@ -1,5 +1,5 @@
1/*1/*
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 $
3** Auxiliary functions to manipulate prototypes and closures3** Auxiliary functions to manipulate prototypes and closures
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -31,7 +31,7 @@ TProtoFunc *luaF_newproto (void) · 25 unmodified lines
31 TProtoFunc *f = luaM_new(TProtoFunc);31 TProtoFunc *f = luaM_new(TProtoFunc);
32 f->code = NULL;32 f->code = NULL;
33 f->lineDefined = 0;33 f->lineDefined = 0;
34 f->fileName = NULL;34 f->source = NULL;
35 f->consts = NULL;35 f->consts = NULL;
36 f->nconsts = 0;36 f->nconsts = 0;
37 f->locvars = NULL;37 f->locvars = NULL;
src/lgc.c+9−22
@@ -1,5 +1,5 @@
1/*1/*
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 $
3** Garbage Collector3** Garbage Collector
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -29,23 +29,18 @@ static int markobject (TObject *o); · 23 unmodified lines
29*/29*/
30 30
31 31
32int luaC_ref (TObject *o, int lock)32int luaC_ref (TObject *o, int lock) {
33{
34 int ref;33 int ref;
35 if (ttype(o) == LUA_T_NIL)34 if (ttype(o) == LUA_T_NIL)
36 ref = -1; /* special ref for nil */35 ref = -1; /* special ref for nil */
37 else {36 else {
38 for (ref=0; ref<L->refSize; ref++)37 for (ref=0; ref<L->refSize; ref++)
39 if (L->refArray[ref].status == FREE)38 if (L->refArray[ref].status == FREE)
40 goto found;39 break;
41 /* no more empty spaces */ {40 if (ref == L->refSize) { /* no more empty spaces? */
42 int oldSize = L->refSize;41 luaM_growvector(L->refArray, L->refSize, 1, struct ref, refEM, MAX_INT);
43 L->refSize = luaM_growvector(&L->refArray, L->refSize, struct ref,42 L->refSize++;
44 refEM, MAX_INT);43 }
45 for (ref=oldSize; ref<L->refSize; ref++)
46 L->refArray[ref].status = FREE;
47 ref = oldSize;
48 } found:
49 L->refArray[ref].o = *o;44 L->refArray[ref].o = *o;
50 L->refArray[ref].status = lock ? LOCK : HOLD;45 L->refArray[ref].status = lock ? LOCK : HOLD;
51 }46 }
@@ -163,21 +158,13 @@ static void strmark (TaggedString *s) · 111 unmodified lines
163}158}
164 159
165 160
166static void protomark (TProtoFunc *f)161static void protomark (TProtoFunc *f) {
167{
168 if (!f->head.marked) {162 if (!f->head.marked) {
169 LocVar *v = f->locvars;
170 int i;163 int i;
171 f->head.marked = 1;164 f->head.marked = 1;
172 if (f->fileName)165 strmark(f->source);
173 strmark(f->fileName);
174 for (i=0; i<f->nconsts; i++)166 for (i=0; i<f->nconsts; i++)
175 markobject(&f->consts[i]);167 markobject(&f->consts[i]);
176 if (v) {
177 for (; v->line != -1; v++)
178 if (v->varname)
179 strmark(v->varname);
180 }
181 }168 }
182}169}
183 170
src/lib/Makefile+2−2
@@ -7,8 +7,8 @@ include $(LUA)/config · 6 unmodified lines
7# actually only used in liolib.c7# actually only used in liolib.c
8EXTRA_DEFS= $(POPEN)8EXTRA_DEFS= $(POPEN)
9 9
10OBJS= liolib.o lmathlib.o lstrlib.o10OBJS= linit.o ldblib.o liolib.o lmathlib.o lstrlib.o
11SRCS= liolib.c lmathlib.c lstrlib.c11SRCS= linit.c ldblib.c liolib.c lmathlib.c lstrlib.c
12 12
13T= $(LIB)/liblualib.a13T= $(LIB)/liblualib.a
14 14
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
18static 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
26static 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
34static 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
61static 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
79static void funcinfo (void) {
80 lua_pushobject(getfuncinfo(luaL_functionarg(1)));
81}
82
83
84static 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
104static 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
133static 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
145static int linehook = -1; /* Lua reference to line hook function */
146static int callhook = -1; /* Lua reference to call hook function */
147
148
149static 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
158static void linef (int line) {
159 lua_pushnumber(line);
160 dohook(linehook);
161}
162
163
164static 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
174static 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
189static 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
204static 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
214void 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
11void 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 @@
1/*1/*
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 $
3** Standard I/O (and system) library3** Standard I/O (and system) library
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -20,6 +20,7 @@ · 14 unmodified lines
20#ifndef OLD_ANSI20#ifndef OLD_ANSI
21#include <locale.h>21#include <locale.h>
22#else22#else
23/* no support for locale and for strerror: fake them */
23#define setlocale(a,b) 024#define setlocale(a,b) 0
24#define LC_ALL 025#define LC_ALL 0
25#define LC_COLLATE 026#define LC_COLLATE 0
@@ -31,10 +32,12 @@ · 5 unmodified lines
31#endif32#endif
32 33
33 34
34#define CLOSEDTAG 235#define IOTAG 1
35#define IOTAG 136
37#define FIRSTARG 2 /* 1st is upvalue */
38
39#define CLOSEDTAG(tag) ((tag)-1) /* assume that CLOSEDTAG = iotag-1 */
36 40
37#define FIRSTARG 3 /* 1st and 2nd are upvalues */
38 41
39#define FINPUT "_INPUT"42#define FINPUT "_INPUT"
40#define FOUTPUT "_OUTPUT"43#define FOUTPUT "_OUTPUT"
@@ -43,262 +46,371 @@ · 2 unmodified lines
43#ifdef POPEN46#ifdef POPEN
44FILE *popen();47FILE *popen();
45int pclose();48int pclose();
49#define CLOSEFILE(f) {if (pclose(f) == -1) fclose(f);}
46#else50#else
51/* no support for popen */
47#define popen(x,y) NULL /* that is, popen always fails */52#define popen(x,y) NULL /* that is, popen always fails */
48#define pclose(x) (-1)53#define CLOSEFILE(f) {fclose(f);}
49#endif54#endif
50 55
51 56
52static int gettag (int i)
53{
54 return lua_getnumber(lua_getparam(i));
55}
56
57 57
58static void pushresult (int i)58static void pushresult (int i) {
59{
60 if (i)59 if (i)
61 lua_pushuserdata(NULL);60 lua_pushuserdata(NULL);
62 else {61 else {
63 lua_pushnil();62 lua_pushnil();
64 lua_pushstring(strerror(errno));63 lua_pushstring(strerror(errno));
64 lua_pushnumber(errno);
65 }65 }
66}66}
67 67
68 68
69static int ishandler (lua_Object f)69/*
70{70** {======================================================
71** FILE Operations
72** =======================================================
73*/
74
75static int gettag (void) {
76 return (int)lua_getnumber(lua_getparam(IOTAG));
77}
78
79
80static int ishandle (lua_Object f) {
71 if (lua_isuserdata(f)) {81 if (lua_isuserdata(f)) {
72 if (lua_tag(f) == gettag(CLOSEDTAG))82 int tag = gettag();
83 if (lua_tag(f) == CLOSEDTAG(tag))
73 lua_error("cannot access a closed file");84 lua_error("cannot access a closed file");
74 return lua_tag(f) == gettag(IOTAG);85 return lua_tag(f) == tag;
75 }86 }
76 else return 0;87 else return 0;
77}88}
78 89
79static FILE *getfile (char *name)90
80{91static FILE *getfilebyname (char *name) {
81 lua_Object f = lua_getglobal(name);92 lua_Object f = lua_getglobal(name);
82 if (!ishandler(f))93 if (!ishandle(f))
83 luaL_verror("global variable `%.50s' is not a file handle", name);94 luaL_verror("global variable `%.50s' is not a file handle", name);
84 return lua_getuserdata(f);95 return lua_getuserdata(f);
85}96}
86 97
87 98
88static FILE *getfileparam (char *name, int *arg)99static FILE *getfile (int arg) {
89{100 lua_Object f = lua_getparam(arg);
90 lua_Object f = lua_getparam(*arg);101 return (ishandle(f)) ? lua_getuserdata(f) : NULL;
91 if (ishandler(f)) {102}
103
104
105static FILE *getnonullfile (int arg) {
106 FILE *f = getfile(arg);
107 luaL_arg_check(f, arg, "invalid file handle");
108 return f;
109}
110
111
112static FILE *getfileparam (char *name, int *arg) {
113 FILE *f = getfile(*arg);
114 if (f) {
92 (*arg)++;115 (*arg)++;
93 return lua_getuserdata(f);116 return f;
94 }117 }
95 else118 else
96 return getfile(name);119 return getfilebyname(name);
120}
121
122
123static 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
133static void io_close (void) {
134 closefile(getnonullfile(FIRSTARG));
135}
136
137
138static void gc_close (void) {
139 FILE *f = getnonullfile(FIRSTARG);
140 if (f != stdin && f != stdout && f != stderr) {
141 CLOSEFILE(f);
142 }
97}143}
98 144
99 145
100static void closefile (char *name)146static void io_open (void) {
101{147 FILE *f = fopen(luaL_check_string(FIRSTARG), luaL_check_string(FIRSTARG+1));
102 FILE *f = getfile(name);148 if (f) lua_pushusertag(f, gettag());
103 if (f == stdin || f == stdout) return;149 else pushresult(0);
104 if (pclose(f) == -1)
105 fclose(f);
106 lua_pushobject(lua_getglobal(name));
107 lua_settag(gettag(CLOSEDTAG));
108}150}
109 151
110 152
111static void setfile (FILE *f, char *name, int tag)153static void setfile (FILE *f, char *name, int tag) {
112{
113 lua_pushusertag(f, tag);154 lua_pushusertag(f, tag);
114 lua_setglobal(name);155 lua_setglobal(name);
115}156}
116 157
117 158
118static void setreturn (FILE *f, char *name)159static void setreturn (FILE *f, char *name) {
119{160 if (f == NULL)
120 int tag = gettag(IOTAG);161 pushresult(0);
121 setfile(f, name, tag);162 else {
122 lua_pushusertag(f, tag);163 int tag = gettag();
164 setfile(f, name, tag);
165 lua_pushusertag(f, tag);
166 }
123}167}
124 168
125 169
126static void io_readfrom (void)170static void io_readfrom (void) {
127{
128 FILE *current;171 FILE *current;
129 lua_Object f = lua_getparam(FIRSTARG);172 lua_Object f = lua_getparam(FIRSTARG);
130 if (f == LUA_NOOBJECT) {173 if (f == LUA_NOOBJECT) {
131 closefile(FINPUT);174 closefile(getfilebyname(FINPUT));
132 current = stdin;175 current = stdin;
133 }176 }
134 else if (lua_tag(f) == gettag(IOTAG))177 else if (lua_tag(f) == gettag()) /* deprecated option */
135 current = lua_getuserdata(f);178 current = lua_getuserdata(f);
136 else {179 else {
137 char *s = luaL_check_string(FIRSTARG);180 char *s = luaL_check_string(FIRSTARG);
138 current = (*s == '|') ? popen(s+1, "r") : fopen(s, "r");181 current = (*s == '|') ? popen(s+1, "r") : fopen(s, "r");
139 if (current == NULL) {
140 pushresult(0);
141 return;
142 }
143 }182 }
144 setreturn(current, FINPUT);183 setreturn(current, FINPUT);
145}184}
146 185
147 186
148static void io_writeto (void)187static void io_writeto (void) {
149{
150 FILE *current;188 FILE *current;
151 lua_Object f = lua_getparam(FIRSTARG);189 lua_Object f = lua_getparam(FIRSTARG);
152 if (f == LUA_NOOBJECT) {190 if (f == LUA_NOOBJECT) {
153 closefile(FOUTPUT);191 closefile(getfilebyname(FOUTPUT));
154 current = stdout;192 current = stdout;
155 }193 }
156 else if (lua_tag(f) == gettag(IOTAG))194 else if (lua_tag(f) == gettag()) /* deprecated option */
157 current = lua_getuserdata(f);195 current = lua_getuserdata(f);
158 else {196 else {
159 char *s = luaL_check_string(FIRSTARG);197 char *s = luaL_check_string(FIRSTARG);
160 current = (*s == '|') ? popen(s+1,"w") : fopen(s,"w");198 current = (*s == '|') ? popen(s+1,"w") : fopen(s, "w");
161 if (current == NULL) {
162 pushresult(0);
163 return;
164 }
165 }199 }
166 setreturn(current, FOUTPUT);200 setreturn(current, FOUTPUT);
167}201}
168 202
169 203
170static void io_appendto (void)204static void io_appendto (void) {
171{205 FILE *current = fopen(luaL_check_string(FIRSTARG), "a");
172 char *s = luaL_check_string(FIRSTARG);206 setreturn(current, FOUTPUT);
173 FILE *fp = fopen (s, "a");
174 if (fp != NULL)
175 setreturn(fp, FOUTPUT);
176 else
177 pushresult(0);
178}207}
179 208
180 209
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*/
181#define NEED_OTHER (EOF-1) /* just some flag different from EOF */222#define NEED_OTHER (EOF-1) /* just some flag different from EOF */
182 223
183 224
184static void read_until (FILE *f, int lim) {225static int read_pattern (FILE *f, char *p) {
185 int l = 0;226 int inskip = 0; /* {skip} level */
186 int c;227 int c = NEED_OTHER;
187 for (c = getc(f); c != EOF && c != lim; c = getc(f)) {228 while (*p != '\0') {
188 luaL_addchar(c);229 switch (*p) {
189 l++;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
274static int read_number (FILE *f) {
275 double d;
276 if (fscanf(f, "%lf", &d) == 1) {
277 lua_pushnumber(d);
278 return 1;
190 }279 }
191 if (l > 0 || c == lim) /* read anything? */280 else return 0; /* read fails */
192 lua_pushlstring(luaL_buffer(), l);281}
282
283
284#define HUNK_LINE 1024
285#define HUNK_FILE BUFSIZ
286
287static 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
302static 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);
193}310}
194 311
312
195static void io_read (void) {313static void io_read (void) {
314 static char *options[] = {"*n", "*l", "*a", ".*", "*w", NULL};
196 int arg = FIRSTARG;315 int arg = FIRSTARG;
197 FILE *f = getfileparam(FINPUT, &arg);316 FILE *f = getfileparam(FINPUT, &arg);
198 char *p = luaL_opt_string(arg, NULL);317 char *p = luaL_opt_string(arg++, "*l");
199 luaL_resetbuffer();318 do { /* repeat for each part */
200 if (p == NULL) /* default: read a line */319 long l;
201 read_until(f, '\n');320 int success;
202 else if (p[0] == '.' && p[1] == '*' && p[2] == 0) /* p = ".*" */321 luaL_resetbuffer();
203 read_until(f, EOF);322 switch (luaL_findstring(p, options)) {
204 else {323 case 0: /* number */
205 int l = 0; /* number of chars read in buffer */324 if (!read_number(f)) return; /* read fails */
206 int inskip = 0; /* to control {skips} */325 continue; /* number is already pushed; avoid the "pushstring" */
207 int c = NEED_OTHER;326 case 1: /* line */
208 while (*p) {327 success = read_line(f);
209 switch (*p) {328 break;
210 case '{':329 case 2: case 3: /* file */
211 inskip++;330 read_file(f);
212 p++;331 success = 1; /* always success */
213 continue;332 break;
214 case '}':333 case 4: /* word */
215 if (inskip == 0)334 success = read_pattern(f, "{%s*}%S+");
216 lua_error("unbalanced braces in read pattern");335 break;
217 inskip--;336 default:
218 p++;337 success = read_pattern(f, p);
219 continue;338 }
220 default: {339 l = luaL_getsize();
221 char *ep; /* get what is next */340 if (!success && l==0) return; /* read fails */
222 int m; /* match result */341 lua_pushlstring(luaL_buffer(), l);
223 if (c == NEED_OTHER) c = getc(f);342 } while ((p = luaL_opt_string(arg++, NULL)) != NULL);
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 }
258}343}
259 344
345/* }====================================================== */
346
260 347
261static void io_write (void)348static void io_write (void) {
262{
263 int arg = FIRSTARG;349 int arg = FIRSTARG;
264 FILE *f = getfileparam(FOUTPUT, &arg);350 FILE *f = getfileparam(FOUTPUT, &arg);
265 int status = 1;351 int status = 1;
266 char *s;352 char *s;
267 long l;353 long l;
268 while ((s = luaL_opt_lstr(arg++, NULL, &l)) != NULL)354 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);
270 pushresult(status);356 pushresult(status);
271}357}
272 358
273 359
274static void io_execute (void)360static void io_seek (void) {
275{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
375static 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
391static void io_execute (void) {
276 lua_pushnumber(system(luaL_check_string(1)));392 lua_pushnumber(system(luaL_check_string(1)));
277}393}
278 394
279 395
280static void io_remove (void)396static void io_remove (void) {
281{
282 pushresult(remove(luaL_check_string(1)) == 0);397 pushresult(remove(luaL_check_string(1)) == 0);
283}398}
284 399
285 400
286static void io_rename (void)401static void io_rename (void) {
287{
288 pushresult(rename(luaL_check_string(1),402 pushresult(rename(luaL_check_string(1),
289 luaL_check_string(2)) == 0);403 luaL_check_string(2)) == 0);
290}404}
291 405
292 406
293static void io_tmpname (void)407static void io_tmpname (void) {
294{
295 lua_pushstring(tmpnam(NULL));408 lua_pushstring(tmpnam(NULL));
296}409}
297 410
298 411
299 412
300static void io_getenv (void)413static void io_getenv (void) {
301{
302 lua_pushstring(getenv(luaL_check_string(1))); /* if NULL push nil */414 lua_pushstring(getenv(luaL_check_string(1))); /* if NULL push nil */
303}415}
304 416
@@ -308,12 +420,11 @@ static void io_clock (void) { · 3 unmodified lines
308}420}
309 421
310 422
311static void io_date (void)423static void io_date (void) {
312{424 char b[256];
313 time_t t;
314 struct tm *tm;
315 char *s = luaL_opt_string(1, "%c");425 char *s = luaL_opt_string(1, "%c");
316 char b[BUFSIZ];426 struct tm *tm;
427 time_t t;
317 time(&t); tm = localtime(&t);428 time(&t); tm = localtime(&t);
318 if (strftime(b,sizeof(b),s,tm))429 if (strftime(b,sizeof(b),s,tm))
319 lua_pushstring(b);430 lua_pushstring(b);
@@ -322,8 +433,7 @@ static void io_date (void) · 2 unmodified lines
322}433}
323 434
324 435
325static void setloc (void)436static void setloc (void) {
326{
327 static int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY, LC_NUMERIC,437 static int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY, LC_NUMERIC,
328 LC_TIME};438 LC_TIME};
329 static char *catnames[] = {"all", "collate", "ctype", "monetary",439 static char *catnames[] = {"all", "collate", "ctype", "monetary",
@@ -334,115 +444,140 @@ static void setloc (void) · 4 unmodified lines
334}444}
335 445
336 446
337static void io_exit (void)447static void io_exit (void) {
338{
339 lua_Object o = lua_getparam(1);448 lua_Object o = lua_getparam(1);
340 exit(lua_isnumber(o) ? (int)lua_getnumber(o) : 1);449 exit(lua_isnumber(o) ? (int)lua_getnumber(o) : 1);
341}450}
342 451
452/* }====================================================== */
453
454
343 455
344static void io_debug (void)456static void io_debug (void) {
345{457 for (;;) {
346 while (1) {
347 char buffer[250];458 char buffer[250];
348 fprintf(stderr, "lua_debug> ");459 fprintf(stderr, "lua_debug> ");
349 if (fgets(buffer, sizeof(buffer), stdin) == 0) return;460 if (fgets(buffer, sizeof(buffer), stdin) == 0 ||
350 if (strcmp(buffer, "cont\n") == 0) return;461 strcmp(buffer, "cont\n") == 0)
462 return;
351 lua_dostring(buffer);463 lua_dostring(buffer);
352 }464 }
353}465}
354 466
355 467
356static void lua_printstack (FILE *f)468
357{469#define MESSAGESIZE 150
470#define MAXMESSAGE (MESSAGESIZE*10)
471
472
473#define MAXSRC 60
474
475
476static void errorfb (void) {
477 char buff[MAXMESSAGE];
358 int level = 1; /* skip level 0 (it's this function) */478 int level = 1; /* skip level 0 (it's this function) */
359 lua_Object func;479 lua_Object func;
480 sprintf(buff, "lua error: %.200s\n", lua_getstring(lua_getparam(1)));
360 while ((func = lua_stackedfunction(level++)) != LUA_NOOBJECT) {481 while ((func = lua_stackedfunction(level++)) != LUA_NOOBJECT) {
361 char *name;482 char *name;
362 int currentline;483 int currentline;
363 char *filename;484 char *chunkname;
485 char buffchunk[MAXSRC];
364 int linedefined;486 int linedefined;
365 lua_funcinfo(func, &filename, &linedefined);487 lua_funcinfo(func, &chunkname, &linedefined);
366 fprintf(f, (level==2) ? "Active Stack:\n\t" : "\t");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 }
367 switch (*lua_getobjname(func, &name)) {495 switch (*lua_getobjname(func, &name)) {
368 case 'g':496 case 'g':
369 fprintf(f, "function %s", name);497 sprintf(buff+strlen(buff), "function `%.50s'", name);
370 break;498 break;
371 case 't':499 case 't':
372 fprintf(f, "`%s' tag method", name);500 sprintf(buff+strlen(buff), "`%.50s' tag method", name);
373 break;501 break;
374 default: {502 default: {
375 if (linedefined == 0)503 if (linedefined == 0)
376 fprintf(f, "main of %s", filename);504 sprintf(buff+strlen(buff), "main of %.70s", buffchunk);
377 else if (linedefined < 0)505 else if (linedefined < 0)
378 fprintf(f, "%s", filename);506 sprintf(buff+strlen(buff), "%.70s", buffchunk);
379 else507 else
380 fprintf(f, "function (%s:%d)", filename, linedefined);508 sprintf(buff+strlen(buff), "function <%d:%.70s>",
381 filename = NULL;509 linedefined, buffchunk);
510 chunkname = NULL;
382 }511 }
383 }512 }
384 if ((currentline = lua_currentline(func)) > 0)513 if ((currentline = lua_currentline(func)) > 0)
385 fprintf(f, " at line %d", currentline);514 sprintf(buff+strlen(buff), " at line %d", currentline);
386 if (filename)515 if (chunkname)
387 fprintf(f, " [in file %s]", filename);516 sprintf(buff+strlen(buff), " [%.70s]", buffchunk);
388 fprintf(f, "\n");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);
389 }523 }
390}
391
392
393static void errorfb (void)
394{
395 fprintf(stderr, "lua: %s\n", lua_getstring(lua_getparam(1)));
396 lua_printstack(stderr);
397}524}
398 525
399 526
400 527
401static struct luaL_reg iolib[] = {528static struct luaL_reg iolib[] = {
402{"setlocale", setloc},529 {"_ERRORMESSAGE", errorfb},
403{"execute", io_execute},530 {"clock", io_clock},
404{"remove", io_remove},531 {"date", io_date},
405{"rename", io_rename},532 {"debug", io_debug},
406{"tmpname", io_tmpname},533 {"execute", io_execute},
407{"getenv", io_getenv},534 {"exit", io_exit},
408{"date", io_date},535 {"getenv", io_getenv},
409{"clock", io_clock},536 {"remove", io_remove},
410{"exit", io_exit},537 {"rename", io_rename},
411{"debug", io_debug},538 {"setlocale", setloc},
412{"print_stack", errorfb}539 {"tmpname", io_tmpname}
413};540};
414 541
542
415static struct luaL_reg iolibtag[] = {543static struct luaL_reg iolibtag[] = {
416{"readfrom", io_readfrom},544 {"appendto", io_appendto},
417{"writeto", io_writeto},545 {"closefile", io_close},
418{"appendto", io_appendto},546 {"flush", io_flush},
419{"read", io_read},547 {"openfile", io_open},
420{"write", io_write}548 {"read", io_read},
549 {"readfrom", io_readfrom},
550 {"seek", io_seek},
551 {"write", io_write},
552 {"writeto", io_writeto}
421};553};
422 554
423static void openwithtags (void)555
424{556static void openwithtags (void) {
425 int iotag = lua_newtag();
426 int closedtag = lua_newtag();
427 int i;557 int i;
558 int iotag = lua_newtag();
559 lua_newtag(); /* alloc CLOSEDTAG: assume that CLOSEDTAG = iotag-1 */
428 for (i=0; i<sizeof(iolibtag)/sizeof(iolibtag[0]); i++) {560 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 */
430 lua_pushnumber(iotag);562 lua_pushnumber(iotag);
431 lua_pushnumber(closedtag);563 lua_pushcclosure(iolibtag[i].func, 1);
432 lua_pushcclosure(iolibtag[i].func, 2);
433 lua_setglobal(iolibtag[i].name);564 lua_setglobal(iolibtag[i].name);
434 }565 }
566 /* predefined file handles */
435 setfile(stdin, FINPUT, iotag);567 setfile(stdin, FINPUT, iotag);
436 setfile(stdout, FOUTPUT, iotag);568 setfile(stdout, FOUTPUT, iotag);
437 setfile(stdin, "_STDIN", iotag);569 setfile(stdin, "_STDIN", iotag);
438 setfile(stdout, "_STDOUT", iotag);570 setfile(stdout, "_STDOUT", iotag);
439 setfile(stderr, "_STDERR", iotag);571 setfile(stderr, "_STDERR", iotag);
572 /* close file when collected */
573 lua_pushnumber(iotag);
574 lua_pushcclosure(gc_close, 1);
575 lua_settagmethod(iotag, "gc");
440}576}
441 577
442void lua_iolibopen (void)578void lua_iolibopen (void) {
443{579 /* register lib functions */
444 luaL_openlib(iolib, (sizeof(iolib)/sizeof(iolib[0])));580 luaL_openlib(iolib, (sizeof(iolib)/sizeof(iolib[0])));
445 openwithtags();581 openwithtags();
446 lua_pushcfunction(errorfb);
447 lua_seterrormethod();
448}582}
583
src/lib/lmathlib.c+57−67
@@ -1,5 +1,5 @@
1/*1/*
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 $
3** Lua standard mathematical library3** Lua standard mathematical library
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -12,107 +12,96 @@ · 6 unmodified lines
12#include "lua.h"12#include "lua.h"
13#include "lualib.h"13#include "lualib.h"
14 14
15#ifdef M_PI
16#define PI M_PI
17#else
18#define PI ((double)3.14159265358979323846)
19#endif
20 15
16#undef PI
17#define PI (3.14159265358979323846)
18#define RADIANS_PER_DEGREE (PI/180.0)
21 19
22#define FROMRAD(a) ((a)*(180.0/PI))
23#define TORAD(a) ((a)*(PI/180.0))
24 20
25 21
26static void math_abs (void)22/*
27{23** If you want Lua to operate in radians (instead of degrees),
28 double d = luaL_check_number(1);24** define RADIANS
29 if (d < 0) d = -d;25*/
30 lua_pushnumber(d);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
35static void math_abs (void) {
36 lua_pushnumber(fabs(luaL_check_number(1)));
31}37}
32 38
33static void math_sin (void)39static void math_sin (void) {
34{
35 lua_pushnumber(sin(TORAD(luaL_check_number(1))));40 lua_pushnumber(sin(TORAD(luaL_check_number(1))));
36}41}
37 42
38static void math_cos (void)43static void math_cos (void) {
39{
40 lua_pushnumber(cos(TORAD(luaL_check_number(1))));44 lua_pushnumber(cos(TORAD(luaL_check_number(1))));
41}45}
42 46
43static void math_tan (void)47static void math_tan (void) {
44{
45 lua_pushnumber(tan(TORAD(luaL_check_number(1))));48 lua_pushnumber(tan(TORAD(luaL_check_number(1))));
46}49}
47 50
48static void math_asin (void)51static void math_asin (void) {
49{
50 lua_pushnumber(FROMRAD(asin(luaL_check_number(1))));52 lua_pushnumber(FROMRAD(asin(luaL_check_number(1))));
51}53}
52 54
53static void math_acos (void)55static void math_acos (void) {
54{
55 lua_pushnumber(FROMRAD(acos(luaL_check_number(1))));56 lua_pushnumber(FROMRAD(acos(luaL_check_number(1))));
56}57}
57 58
58static void math_atan (void)59static void math_atan (void) {
59{
60 lua_pushnumber(FROMRAD(atan(luaL_check_number(1))));60 lua_pushnumber(FROMRAD(atan(luaL_check_number(1))));
61}61}
62 62
63static void math_atan2 (void)63static void math_atan2 (void) {
64{
65 lua_pushnumber(FROMRAD(atan2(luaL_check_number(1), luaL_check_number(2))));64 lua_pushnumber(FROMRAD(atan2(luaL_check_number(1), luaL_check_number(2))));
66}65}
67 66
68static void math_ceil (void)67static void math_ceil (void) {
69{
70 lua_pushnumber(ceil(luaL_check_number(1)));68 lua_pushnumber(ceil(luaL_check_number(1)));
71}69}
72 70
73static void math_floor (void)71static void math_floor (void) {
74{
75 lua_pushnumber(floor(luaL_check_number(1)));72 lua_pushnumber(floor(luaL_check_number(1)));
76}73}
77 74
78static void math_mod (void)75static void math_mod (void) {
79{
80 lua_pushnumber(fmod(luaL_check_number(1), luaL_check_number(2)));76 lua_pushnumber(fmod(luaL_check_number(1), luaL_check_number(2)));
81}77}
82 78
83static void math_sqrt (void)79static void math_sqrt (void) {
84{
85 lua_pushnumber(sqrt(luaL_check_number(1)));80 lua_pushnumber(sqrt(luaL_check_number(1)));
86}81}
87 82
88static void math_pow (void)83static void math_pow (void) {
89{
90 lua_pushnumber(pow(luaL_check_number(1), luaL_check_number(2)));84 lua_pushnumber(pow(luaL_check_number(1), luaL_check_number(2)));
91}85}
92 86
93static void math_log (void)87static void math_log (void) {
94{
95 lua_pushnumber(log(luaL_check_number(1)));88 lua_pushnumber(log(luaL_check_number(1)));
96}89}
97 90
98static void math_log10 (void)91static void math_log10 (void) {
99{
100 lua_pushnumber(log10(luaL_check_number(1)));92 lua_pushnumber(log10(luaL_check_number(1)));
101}93}
102 94
103static void math_exp (void)95static void math_exp (void) {
104{
105 lua_pushnumber(exp(luaL_check_number(1)));96 lua_pushnumber(exp(luaL_check_number(1)));
106}97}
107 98
108static void math_deg (void)99static void math_deg (void) {
109{100 lua_pushnumber(luaL_check_number(1)/RADIANS_PER_DEGREE);
110 lua_pushnumber(luaL_check_number(1)*(180.0/PI));
111}101}
112 102
113static void math_rad (void)103static void math_rad (void) {
114{104 lua_pushnumber(luaL_check_number(1)*RADIANS_PER_DEGREE);
115 lua_pushnumber(luaL_check_number(1)*(PI/180.0));
116}105}
117 106
118static void math_frexp (void) {107static void math_frexp (void) {
@@ -122,13 +111,12 @@ static void math_frexp (void) { · 3 unmodified lines
122}111}
123 112
124static void math_ldexp (void) {113static 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)));
126}115}
127 116
128 117
129 118
130static void math_min (void)119static void math_min (void) {
131{
132 int i = 1;120 int i = 1;
133 double dmin = luaL_check_number(i);121 double dmin = luaL_check_number(i);
134 while (lua_getparam(++i) != LUA_NOOBJECT) {122 while (lua_getparam(++i) != LUA_NOOBJECT) {
@@ -140,8 +128,7 @@ static void math_min (void) · 5 unmodified lines
140}128}
141 129
142 130
143static void math_max (void)131static void math_max (void) {
144{
145 int i = 1;132 int i = 1;
146 double dmax = luaL_check_number(i);133 double dmax = luaL_check_number(i);
147 while (lua_getparam(++i) != LUA_NOOBJECT) {134 while (lua_getparam(++i) != LUA_NOOBJECT) {
@@ -153,22 +140,27 @@ static void math_max (void) · 5 unmodified lines
153}140}
154 141
155 142
156static void math_random (void)143static void math_random (void) {
157{144 /* the '%' avoids the (rare) case of r==1, and is needed also because on
158 /* the '%' is needed because on some systems (SunOS!) "rand()" may */145 some systems (SunOS!) "rand()" may return a value bigger than RAND_MAX */
159 /* return a value bigger than RAND_MAX... */
160 double r = (double)(rand()%RAND_MAX) / (double)RAND_MAX;146 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);
162 if (l == 0)148 if (l == 0)
163 lua_pushnumber(r);149 lua_pushnumber(r);
164 else150 else {
165 lua_pushnumber((int)(r*l)+1);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 }
166}159}
167 160
168 161
169static void math_randomseed (void)162static void math_randomseed (void) {
170{163 srand(luaL_check_int(1));
171 srand(luaL_check_number(1));
172}164}
173 165
174 166
@@ -201,10 +193,8 @@ static struct luaL_reg mathlib[] = { · 26 unmodified lines
201/*193/*
202** Open math library194** Open math library
203*/195*/
204void lua_mathlibopen (void)196void lua_mathlibopen (void) {
205{
206 luaL_openlib(mathlib, (sizeof(mathlib)/sizeof(mathlib[0])));197 luaL_openlib(mathlib, (sizeof(mathlib)/sizeof(mathlib[0])));
207 lua_pushstring("deg"); lua_setglobal("_TRIGMODE");
208 lua_pushcfunction(math_pow);198 lua_pushcfunction(math_pow);
209 lua_pushnumber(0); /* to get its tag */199 lua_pushnumber(0); /* to get its tag */
210 lua_settagmethod(lua_tag(lua_pop()), "pow");200 lua_settagmethod(lua_tag(lua_pop()), "pow");
src/lib/lstrlib.c+230−177
@@ -1,5 +1,5 @@
1/*1/*
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 $
3** Standard library for strings and pattern-matching3** Standard library for strings and pattern-matching
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -32,33 +32,31 @@ static void str_len (void) · 26 unmodified lines
32}32}
33 33
34 34
35static void closeandpush (void)35static void closeandpush (void) {
36{
37 lua_pushlstring(luaL_buffer(), luaL_getsize());36 lua_pushlstring(luaL_buffer(), luaL_getsize());
38}37}
39 38
40 39
41static long posrelat (long pos, long len)40static long posrelat (long pos, long len) {
42{
43 /* relative string position: negative means back from end */41 /* relative string position: negative means back from end */
44 return (pos>=0) ? pos : len+pos+1;42 return (pos>=0) ? pos : len+pos+1;
45}43}
46 44
47 45
48static void str_sub (void)46static void str_sub (void) {
49{
50 long l;47 long l;
51 char *s = luaL_check_lstr(1, &l);48 char *s = luaL_check_lstr(1, &l);
52 long start = posrelat(luaL_check_number(2), l);49 long start = posrelat(luaL_check_long(2), l);
53 long end = posrelat(luaL_opt_number(3, -1), l);50 long end = posrelat(luaL_opt_long(3, -1), l);
54 if (1 <= start && start <= end && end <= l)51 if (start < 1) start = 1;
52 if (end > l) end = l;
53 if (start <= end)
55 lua_pushlstring(s+start-1, end-start+1);54 lua_pushlstring(s+start-1, end-start+1);
56 else lua_pushstring("");55 else lua_pushstring("");
57}56}
58 57
59 58
60static void str_lower (void)59static void str_lower (void) {
61{
62 long l;60 long l;
63 int i;61 int i;
64 char *s = luaL_check_lstr(1, &l);62 char *s = luaL_check_lstr(1, &l);
@@ -69,8 +67,7 @@ static void str_lower (void) · 4 unmodified lines
69}67}
70 68
71 69
72static void str_upper (void)70static void str_upper (void) {
73{
74 long l;71 long l;
75 int i;72 int i;
76 char *s = luaL_check_lstr(1, &l);73 char *s = luaL_check_lstr(1, &l);
@@ -84,7 +81,7 @@ static void str_rep (void) · 7 unmodified lines
84{81{
85 long l;82 long l;
86 char *s = luaL_check_lstr(1, &l);83 char *s = luaL_check_lstr(1, &l);
87 int n = (int)luaL_check_number(2);84 int n = luaL_check_int(2);
88 luaL_resetbuffer();85 luaL_resetbuffer();
89 while (n-- > 0)86 while (n-- > 0)
90 addnchar(s, l);87 addnchar(s, l);
@@ -92,38 +89,42 @@ static void str_rep (void) · 1 unmodified line
92}89}
93 90
94 91
95static void str_byte (void)92static void str_byte (void) {
96{
97 long l;93 long l;
98 char *s = luaL_check_lstr(1, &l);94 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);
100 luaL_arg_check(0<pos && pos<=l, 2, "out of range");96 luaL_arg_check(0<pos && pos<=l, 2, "out of range");
101 lua_pushnumber((unsigned char)s[pos-1]);97 lua_pushnumber((unsigned char)s[pos-1]);
102}98}
103 99
100
104static void str_char (void) {101static void str_char (void) {
105 int i = 0;102 int i = 0;
106 luaL_resetbuffer();103 luaL_resetbuffer();
107 while (lua_getparam(++i) != LUA_NOOBJECT) {104 while (lua_getparam(++i) != LUA_NOOBJECT) {
108 double c = luaL_check_number(i);105 double c = luaL_check_number(i);
109 luaL_arg_check((unsigned char)c == c, i, "invalid value");106 luaL_arg_check((unsigned char)c == c, i, "invalid value");
110 luaL_addchar((int)c);107 luaL_addchar((unsigned char)c);
111 }108 }
112 closeandpush();109 closeandpush();
113}110}
114 111
115 112
113
116/*114/*
117** =======================================================115** {======================================================
118** PATTERN MATCHING116** PATTERN MATCHING
119** =======================================================117** =======================================================
120*/118*/
121 119
122#define MAX_CAPT 9120#ifndef MAX_CAPT
121#define MAX_CAPT 32 /* arbitrary limit */
122#endif
123
123 124
124struct Capture {125struct Capture {
125 int level; /* total number of captures (finished or unfinished) */
126 char *src_end; /* end ('\0') of source string */126 char *src_end; /* end ('\0') of source string */
127 int level; /* total number of captures (finished or unfinished) */
127 struct {128 struct {
128 char *init;129 char *init;
129 int len; /* -1 signals unfinished capture */130 int len; /* -1 signals unfinished capture */
@@ -132,19 +133,20 @@ struct Capture { · 2 unmodified lines
132 133
133 134
134#define ESC '%'135#define ESC '%'
135#define SPECIALS "^$*?.([%-"136#define SPECIALS "^$*+?.([%-"
136 137
137 138
138static void push_captures (struct Capture *cap)139static void push_captures (struct Capture *cap) {
139{
140 int i;140 int i;
141 for (i=0; i<cap->level; i++)141 for (i=0; i<cap->level; i++) {
142 lua_pushlstring(cap->capture[i].init, cap->capture[i].len);142 int l = cap->capture[i].len;
143 if (l == -1) lua_error("unfinished capture");
144 lua_pushlstring(cap->capture[i].init, l);
145 }
143}146}
144 147
145 148
146static int check_cap (int l, struct Capture *cap)149static int check_cap (int l, struct Capture *cap) {
147{
148 l -= '1';150 l -= '1';
149 if (!(0 <= l && l < cap->level && cap->capture[l].len != -1))151 if (!(0 <= l && l < cap->level && cap->capture[l].len != -1))
150 lua_error("invalid capture index");152 lua_error("invalid capture index");
@@ -152,8 +154,7 @@ static int check_cap (int l, struct Capture *cap) · 1 unmodified line
152}154}
153 155
154 156
155static int capture_to_close (struct Capture *cap)157static int capture_to_close (struct Capture *cap) {
156{
157 int level = cap->level;158 int level = cap->level;
158 for (level--; level>=0; level--)159 for (level--; level>=0; level--)
159 if (cap->capture[level].len == -1) return level;160 if (cap->capture[level].len == -1) return level;
@@ -162,14 +163,25 @@ static int capture_to_close (struct Capture *cap) · 2 unmodified lines
162}163}
163 164
164 165
165static char *bracket_end (char *p)166char *luaI_classend (char *p) {
166{167 switch (*p++) {
167 return (*p == 0) ? NULL : strchr((*p=='^') ? p+2 : p+1, ']');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 }
168}181}
169 182
170 183
171static int matchclass (int c, int cl)184static int matchclass (int c, int cl) {
172{
173 int res;185 int res;
174 switch (tolower(cl)) {186 switch (tolower(cl)) {
175 case 'a' : res = isalpha(c); break;187 case 'a' : res = isalpha(c); break;
@@ -180,57 +192,63 @@ static int matchclass (int c, int cl) · 4 unmodified lines
180 case 's' : res = isspace(c); break;192 case 's' : res = isspace(c); break;
181 case 'u' : res = isupper(c); break;193 case 'u' : res = isupper(c); break;
182 case 'w' : res = isalnum(c); break;194 case 'w' : res = isalnum(c); break;
195 case 'x' : res = isxdigit(c); break;
183 case 'z' : res = (c == '\0'); break;196 case 'z' : res = (c == '\0'); break;
184 default: return (cl == c);197 default: return (cl == c);
185 }198 }
186 return (islower((unsigned char)cl) ? res : !res);199 return (islower(cl) ? res : !res);
187}200}
188 201
189 202
190int luaI_singlematch (int c, char *p, char **ep)203
191{204static 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
228int luaI_singlematch (int c, char *p, char *ep) {
192 switch (*p) {229 switch (*p) {
193 case '.': /* matches any char */230 case '.': /* matches any char */
194 *ep = p+1;
195 return 1;231 return 1;
196 case '\0': /* end of pattern; matches nothing */
197 *ep = p;
198 return 0;
199 case ESC:232 case ESC:
200 if (*(++p) == '\0')233 return matchclass(c, (unsigned char)*(p+1));
201 luaL_verror("incorrect pattern (ends with `%c')", ESC);234 case '[':
202 *ep = p+1;235 return matchbracketclass(c, p, ep-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 }
223 default:236 default:
224 *ep = p+1;
225 return ((unsigned char)*p == c);237 return ((unsigned char)*p == c);
226 }238 }
227}239}
228 240
229 241
230static char *matchbalance (char *s, int b, int e, struct Capture *cap)242static char *match (char *s, char *p, struct Capture *cap);
231{243
232 if (*s != b) return NULL;244
245static 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;
233 else {249 else {
250 int b = *p;
251 int e = *(p+1);
234 int cont = 1;252 int cont = 1;
235 while (++s < cap->src_end) {253 while (++s < cap->src_end) {
236 if (*s == e) {254 if (*s == e) {
@@ -243,101 +261,120 @@ static char *matchbalance (char *s, int b, int e, struct Capture *cap) · 6 unmodified lines
243}261}
244 262
245 263
246static char *matchitem (char *s, char *p, struct Capture *cap, char **ep)264static char *max_expand (char *s, char *p, char *ep, struct Capture *cap) {
247{265 int i = 0; /* counts maximum expand for item */
248 if (*p == ESC) {266 while ((s+i)<cap->src_end && luaI_singlematch((unsigned char)*(s+i), p, ep))
249 p++;267 i++;
250 if (isdigit((unsigned char)*p)) { /* capture */268 /* keeps trying to match mith the maximum repetitions */
251 int l = check_cap(*p, cap);269 while (i>=0) {
252 int len = cap->capture[l].len;270 char *res = match((s+i), ep+1, cap);
253 *ep = p+1;271 if (res) return res;
254 if (cap->src_end-s >= len && memcmp(cap->capture[l].init, s, len) == 0)272 i--; /* else didn't match; reduce 1 repetition to try again */
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 */
266 }273 }
267 /* "luaI_singlematch" sets "ep" (so must be called even when *s == 0) */274 return NULL;
268 return (luaI_singlematch((unsigned char)*s, p, ep) && s<cap->src_end) ?
269 s+1 : NULL;
270}275}
271 276
272 277
273static char *match (char *s, char *p, struct Capture *cap)278static char *min_expand (char *s, char *p, char *ep, struct Capture *cap) {
274{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
290static 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
303static 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
313static 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
323static char *match (char *s, char *p, struct Capture *cap) {
275 init: /* using goto's to optimize tail recursion */324 init: /* using goto's to optimize tail recursion */
276 switch (*p) {325 switch (*p) {
277 case '(': { /* start capture */326 case '(': /* start capture */
278 char *res;327 return start_capt(s, p, cap);
279 if (cap->level >= MAX_CAPT) lua_error("too many captures");328 case ')': /* end capture */
280 cap->capture[cap->level].init = s;329 return end_capt(s, p, cap);
281 cap->capture[cap->level].len = -1;330 case ESC: /* may be %[0-9] or %b */
282 cap->level++;331 if (isdigit((unsigned char)(*(p+1)))) { /* capture? */
283 if ((res=match(s, p+1, cap)) == NULL) /* match failed? */332 s = match_capture(s, *(p+1), cap);
284 cap->level--; /* undo capture */333 if (s == NULL) return NULL;
285 return res;334 p+=2; goto init; /* else return match(p+2, s, cap) */
286 }335 }
287 case ')': { /* end capture */336 else if (*(p+1) == 'b') { /* balanced string? */
288 int l = capture_to_close(cap);337 s = matchbalance(s, p+2, cap);
289 char *res;338 if (s == NULL) return NULL;
290 cap->capture[l].len = s - cap->capture[l].init; /* close capture */339 p+=4; goto init; /* else return match(p+4, s, cap); */
291 if ((res = match(s, p+1, cap)) == NULL) /* match failed? */340 }
292 cap->capture[l].len = -1; /* undo capture */341 else goto dflt; /* case default */
293 return res;342 case '\0': /* end of pattern */
294 }343 return s; /* match succeeded */
295 case '\0': case '$': /* (possibly) end of pattern */344 case '$':
296 if (*p == 0 || (*(p+1) == 0 && s == cap->src_end))345 if (*(p+1) == '\0') /* is the '$' the last char in pattern? */
297 return s;346 return (s == cap->src_end) ? s : NULL; /* check end of string */
298 /* else go through */347 else goto dflt;
299 default: { /* it is a pattern item */348 default: dflt: { /* it is a pattern item */
300 char *ep; /* get what is next */349 char *ep = luaI_classend(p); /* points to what is next */
301 char *s1 = matchitem(s, p, cap, &ep);350 int m = s<cap->src_end && luaI_singlematch((unsigned char)*s, p, ep);
302 switch (*ep) {351 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 }
309 case '?': { /* optional */352 case '?': { /* optional */
310 char *res;353 char *res;
311 if (s1 && ((res=match(s1, ep+1, cap)) != NULL))354 if (m && ((res=match(s+1, ep+1, cap)) != NULL))
312 return res;355 return res;
313 p=ep+1; goto init; /* else return match(s, ep+1, cap); */356 p=ep+1; goto init; /* else return match(s, ep+1, cap); */
314 }357 }
315 case '-': { /* repetition */358 case '*': /* 0 or more repetitions */
316 char *res;359 return max_expand(s, p, ep, cap);
317 if ((res = match(s, ep+1, cap)) != NULL)360 case '+': /* 1 or more repetitions */
318 return res;361 return (m ? max_expand(s+1, p, ep, cap) : NULL);
319 else if (s1 && s1>s) {362 case '-': /* 0 or more repetitions (minimum) */
320 s = s1;363 return min_expand(s, p, ep, cap);
321 goto init; /* return match(s1, p, cap); */
322 }
323 else
324 return NULL;
325 }
326 default:364 default:
327 if (s1) { s=s1; p=ep; goto init; } /* return match(s1, ep, cap); */365 if (!m) return NULL;
328 else return NULL;366 s++; p=ep; goto init; /* else return match(s+1, ep, cap); */
329 }367 }
330 }368 }
331 }369 }
332}370}
333 371
334 372
335static void str_find (void)373static void str_find (void) {
336{
337 long l;374 long l;
338 char *s = luaL_check_lstr(1, &l);375 char *s = luaL_check_lstr(1, &l);
339 char *p = luaL_check_string(2);376 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;
341 struct Capture cap;378 struct Capture cap;
342 luaL_arg_check(0 <= init && init <= l, 3, "out of range");379 luaL_arg_check(0 <= init && init <= l, 3, "out of range");
343 if (lua_getparam(4) != LUA_NOOBJECT ||380 if (lua_getparam(4) != LUA_NOOBJECT ||
@@ -368,8 +405,7 @@ static void str_find (void) · 24 unmodified lines
368}405}
369 406
370 407
371static void add_s (lua_Object newp, struct Capture *cap)408static void add_s (lua_Object newp, struct Capture *cap) {
372{
373 if (lua_isstring(newp)) {409 if (lua_isstring(newp)) {
374 char *news = lua_getstring(newp);410 char *news = lua_getstring(newp);
375 int l = lua_strlen(newp);411 int l = lua_strlen(newp);
@@ -411,13 +447,12 @@ static void add_s (lua_Object newp, struct Capture *cap) · 35 unmodified lines
411}447}
412 448
413 449
414static void str_gsub (void)450static void str_gsub (void) {
415{
416 long srcl;451 long srcl;
417 char *src = luaL_check_lstr(1, &srcl);452 char *src = luaL_check_lstr(1, &srcl);
418 char *p = luaL_check_string(2);453 char *p = luaL_check_string(2);
419 lua_Object newp = lua_getparam(3);454 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);
421 int anchor = (*p == '^') ? (p++, 1) : 0;456 int anchor = (*p == '^') ? (p++, 1) : 0;
422 int n = 0;457 int n = 0;
423 struct Capture cap;458 struct Capture cap;
@@ -445,26 +480,33 @@ static void str_gsub (void) · 21 unmodified lines
445 lua_pushnumber(n); /* number of substitutions */480 lua_pushnumber(n); /* number of substitutions */
446}481}
447 482
483/* }====================================================== */
448 484
449static void luaI_addquoted (char *s)485
450{486static void luaI_addquoted (int arg) {
487 long l;
488 char *s = luaL_check_lstr(arg, &l);
451 luaL_addchar('"');489 luaL_addchar('"');
452 for (; *s; s++) {490 while (l--) {
453 if (strchr("\"\\\n", *s))491 switch (*s) {
454 luaL_addchar('\\');492 case '"': case '\\': case '\n':
455 luaL_addchar(*s);493 luaL_addchar('\\');
494 luaL_addchar(*s);
495 break;
496 case '\0': addnchar("\\000", 4); break;
497 default: luaL_addchar(*s);
498 }
499 s++;
456 }500 }
457 luaL_addchar('"');501 luaL_addchar('"');
458}502}
459 503
460#define MAX_FORMAT 200504/* maximum size of each format specification (such as '%-099.99d') */
505#define MAX_FORMAT 20 /* arbitrary limit */
461 506
462static void str_format (void)507static void str_format (void) {
463{
464 int arg = 1;508 int arg = 1;
465 char *strfrmt = luaL_check_string(arg);509 char *strfrmt = luaL_check_string(arg);
466 struct Capture cap;
467 cap.src_end = strfrmt+strlen(strfrmt)+1;
468 luaL_resetbuffer();510 luaL_resetbuffer();
469 while (*strfrmt) {511 while (*strfrmt) {
470 if (*strfrmt != '%')512 if (*strfrmt != '%')
@@ -472,34 +514,28 @@ static void str_format (void) · 1 unmodified line
472 else if (*++strfrmt == '%')514 else if (*++strfrmt == '%')
473 luaL_addchar(*strfrmt++); /* %% */515 luaL_addchar(*strfrmt++); /* %% */
474 else { /* format item */516 else { /* format item */
475 char form[MAX_FORMAT]; /* store the format ('%...') */517 struct Capture cap;
476 char *buff;518 char form[MAX_FORMAT]; /* to store the format ('%...') */
519 char *buff; /* to store the formatted item */
477 char *initf = strfrmt;520 char *initf = strfrmt;
478 form[0] = '%';521 form[0] = '%';
479 cap.level = 0;522 if (isdigit((unsigned char)*initf) && *(initf+1) == '$') {
480 if (isdigit((unsigned char)initf[0]) && initf[1] == '$') {523 arg = *initf - '0';
481 arg = initf[0] - '0';
482 initf += 2; /* skip the 'n$' */524 initf += 2; /* skip the 'n$' */
483 }525 }
484 arg++;526 arg++;
527 cap.src_end = strfrmt+strlen(strfrmt)+1;
528 cap.level = 0;
485 strfrmt = match(initf, "[-+ #0]*(%d*)%.?(%d*)", &cap);529 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)
487 lua_error("invalid format (width or precision too long)");532 lua_error("invalid format (width or precision too long)");
488 strncpy(form+1, initf, strfrmt-initf+1); /* +1 to include conversion */533 strncpy(form+1, initf, strfrmt-initf+1); /* +1 to include conversion */
489 form[strfrmt-initf+2] = 0;534 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) */
491 switch (*strfrmt++) {536 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 }
501 case 'c': case 'd': case 'i':537 case 'c': case 'd': case 'i':
502 sprintf(buff, form, (int)luaL_check_number(arg));538 sprintf(buff, form, luaL_check_int(arg));
503 break;539 break;
504 case 'o': case 'u': case 'x': case 'X':540 case 'o': case 'u': case 'x': case 'X':
505 sprintf(buff, form, (unsigned int)luaL_check_number(arg));541 sprintf(buff, form, (unsigned int)luaL_check_number(arg));
@@ -507,6 +543,23 @@ static void str_format (void) · 1 unmodified line
507 case 'e': case 'E': case 'f': case 'g': case 'G':543 case 'e': case 'E': case 'f': case 'g': case 'G':
508 sprintf(buff, form, luaL_check_number(arg));544 sprintf(buff, form, luaL_check_number(arg));
509 break;545 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 }
510 default: /* also treat cases 'pnLlh' */563 default: /* also treat cases 'pnLlh' */
511 lua_error("invalid option in `format'");564 lua_error("invalid option in `format'");
512 }565 }
@@ -524,7 +577,7 @@ static struct luaL_reg strlib[] = { · 11 unmodified lines
524{"strupper", str_upper},577{"strupper", str_upper},
525{"strchar", str_char},578{"strchar", str_char},
526{"strrep", str_rep},579{"strrep", str_rep},
527{"ascii", str_byte}, /* for compatibility */580{"ascii", str_byte}, /* for compatibility with 3.0 and earlier */
528{"strbyte", str_byte},581{"strbyte", str_byte},
529{"format", str_format},582{"format", str_format},
530{"strfind", str_find},583{"strfind", str_find},
src/llex.c+52−78
@@ -1,6 +1,6 @@
1/*1/*
2** $Id: llex.c,v 1.23 1998/07/06 22:04:58 roberto Exp $2** $Id: llex.c,v 1.36 1999/06/17 17:04:03 roberto Exp $
3** Lexical Analizer3** Lexical Analyzer
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
6 6
@@ -20,9 +20,6 @@ · 13 unmodified lines
20 20
21 21
22 22
23int lua_debug=0;
24
25
26#define next(LS) (LS->current = zgetc(LS->lex_z))23#define next(LS) (LS->current = zgetc(LS->lex_z))
27 24
28 25
@@ -35,8 +32,7 @@ char *reserved [] = {"and", "do", "else", "elseif", "end", "function", · 6 unmodified lines
35 "until", "while"};32 "until", "while"};
36 33
37 34
38void luaX_init (void)35void luaX_init (void) {
39{
40 int i;36 int i;
41 for (i=0; i<(sizeof(reserved)/sizeof(reserved[0])); i++) {37 for (i=0; i<(sizeof(reserved)/sizeof(reserved[0])); i++) {
42 TaggedString *ts = luaS_new(reserved[i]);38 TaggedString *ts = luaS_new(reserved[i]);
@@ -45,24 +41,28 @@ void luaX_init (void) · 2 unmodified lines
45}41}
46 42
47 43
44#define MAXSRC 80
45
48void luaX_syntaxerror (LexState *ls, char *s, char *token) {46void 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')
50 token = "<eof>";50 token = "<eof>";
51 luaL_verror("%.100s;\n last token read: `%.50s' at line %d in chunk `%.50s'",51 luaL_verror("%.100s;\n last token read: `%.50s' at line %d in %.80s",
52 s, token, ls->linenumber, zname(ls->lex_z));52 s, token, ls->linenumber, buff);
53}53}
54 54
55 55
56void luaX_error (LexState *ls, char *s) {56void luaX_error (LexState *ls, char *s) {
57 save(0);57 save('\0');
58 luaX_syntaxerror(ls, s, luaL_buffer());58 luaX_syntaxerror(ls, s, luaL_buffer());
59}59}
60 60
61 61
62void luaX_token2str (LexState *ls, int token, char *s) {62void luaX_token2str (int token, char *s) {
63 if (token < 255) {63 if (token < 255) {
64 s[0] = token;64 s[0] = (char)token;
65 s[1] = 0;65 s[1] = '\0';
66 }66 }
67 else67 else
68 strcpy(s, reserved[token-FIRST_RESERVED]);68 strcpy(s, reserved[token-FIRST_RESERVED]);
@@ -70,8 +70,8 @@ void luaX_token2str (LexState *ls, int token, char *s) { · 1 unmodified line
70 70
71 71
72static void luaX_invalidchar (LexState *ls, int c) {72static void luaX_invalidchar (LexState *ls, int c) {
73 char buff[10];73 char buff[8];
74 sprintf(buff, "0x%X", c);74 sprintf(buff, "0x%02X", c);
75 luaX_syntaxerror(ls, "invalid control char", buff);75 luaX_syntaxerror(ls, "invalid control char", buff);
76}76}
77 77
@@ -106,17 +106,17 @@ void luaX_setinput (LexState *LS, ZIO *z) · 28 unmodified lines
106** =======================================================106** =======================================================
107*/107*/
108 108
109#define PRAGMASIZE 20109#ifndef PRAGMASIZE
110#define PRAGMASIZE 80 /* arbitrary limit */
111#endif
110 112
111static void skipspace (LexState *LS)113static void skipspace (LexState *LS) {
112{
113 while (LS->current == ' ' || LS->current == '\t' || LS->current == '\r')114 while (LS->current == ' ' || LS->current == '\t' || LS->current == '\r')
114 next(LS);115 next(LS);
115}116}
116 117
117 118
118static int checkcond (LexState *LS, char *buff)119static int checkcond (LexState *LS, char *buff) {
119{
120 static char *opts[] = {"nil", "1", NULL};120 static char *opts[] = {"nil", "1", NULL};
121 int i = luaL_findstring(buff, opts);121 int i = luaL_findstring(buff, opts);
122 if (i >= 0) return i;122 if (i >= 0) return i;
@@ -129,8 +129,7 @@ static int checkcond (LexState *LS, char *buff) · 6 unmodified lines
129}129}
130 130
131 131
132static void readname (LexState *LS, char *buff)132static void readname (LexState *LS, char *buff) {
133{
134 int i = 0;133 int i = 0;
135 skipspace(LS);134 skipspace(LS);
136 while (isalnum(LS->current) || LS->current == '_') {135 while (isalnum(LS->current) || LS->current == '_') {
@@ -138,7 +137,7 @@ static void readname (LexState *LS, char *buff) · 1 unmodified line
138 buff[PRAGMASIZE] = 0;137 buff[PRAGMASIZE] = 0;
139 luaX_syntaxerror(LS, "pragma too long", buff);138 luaX_syntaxerror(LS, "pragma too long", buff);
140 }139 }
141 buff[i++] = LS->current;140 buff[i++] = (char)LS->current;
142 next(LS);141 next(LS);
143 }142 }
144 buff[i] = 0;143 buff[i] = 0;
@@ -148,8 +147,7 @@ static void readname (LexState *LS, char *buff) · 3 unmodified lines
148static void inclinenumber (LexState *LS);147static void inclinenumber (LexState *LS);
149 148
150 149
151static void ifskip (LexState *LS)150static void ifskip (LexState *LS) {
152{
153 while (LS->ifstate[LS->iflevel].skip) {151 while (LS->ifstate[LS->iflevel].skip) {
154 if (LS->current == '\n')152 if (LS->current == '\n')
155 inclinenumber(LS);153 inclinenumber(LS);
@@ -160,8 +158,7 @@ static void ifskip (LexState *LS) · 4 unmodified lines
160}158}
161 159
162 160
163static void inclinenumber (LexState *LS)161static void inclinenumber (LexState *LS) {
164{
165 static char *pragmas [] =162 static char *pragmas [] =
166 {"debug", "nodebug", "endinput", "end", "ifnot", "if", "else", NULL};163 {"debug", "nodebug", "endinput", "end", "ifnot", "if", "else", NULL};
167 next(LS); /* skip '\n' */164 next(LS); /* skip '\n' */
@@ -174,10 +171,10 @@ static void inclinenumber (LexState *LS) · 6 unmodified lines
174 readname(LS, buff);171 readname(LS, buff);
175 switch (luaL_findstring(buff, pragmas)) {172 switch (luaL_findstring(buff, pragmas)) {
176 case 0: /* debug */173 case 0: /* debug */
177 if (!skip) lua_debug = 1;174 if (!skip) L->debug = 1;
178 break;175 break;
179 case 1: /* nodebug */176 case 1: /* nodebug */
180 if (!skip) lua_debug = 0;177 if (!skip) L->debug = 0;
181 break;178 break;
182 case 2: /* endinput */179 case 2: /* endinput */
183 if (!skip) {180 if (!skip) {
@@ -221,6 +218,7 @@ static void inclinenumber (LexState *LS) · 37 unmodified lines
221}218}
222 219
223 220
221
224/*222/*
225** =======================================================223** =======================================================
226** LEXICAL ANALIZER224** LEXICAL ANALIZER
@@ -229,12 +227,9 @@ static void inclinenumber (LexState *LS) · 2 unmodified lines
229 227
230 228
231 229
232 230static int read_long_string (LexState *LS) {
233
234static int read_long_string (LexState *LS)
235{
236 int cont = 0;231 int cont = 0;
237 while (1) {232 for (;;) {
238 switch (LS->current) {233 switch (LS->current) {
239 case EOZ:234 case EOZ:
240 luaX_error(LS, "unfinished long string");235 luaX_error(LS, "unfinished long string");
@@ -262,17 +257,16 @@ static int read_long_string (LexState *LS) · 21 unmodified lines
262 save_and_next(LS);257 save_and_next(LS);
263 }258 }
264 } endloop:259 } endloop:
265 save_and_next(LS); /* pass the second ']' */260 save_and_next(LS); /* skip the second ']' */
266 LS->seminfo.ts = luaS_newlstr(L->Mbuffbase+2,261 LS->seminfo.ts = luaS_newlstr(L->Mbuffer+(L->Mbuffbase+2),
267 L->Mbuffnext-(L->Mbuffbase-L->Mbuffer)-4);262 L->Mbuffnext-L->Mbuffbase-4);
268 return STRING;263 return STRING;
269}264}
270 265
271 266
272int luaX_lex (LexState *LS) {267int luaX_lex (LexState *LS) {
273 double a;
274 luaL_resetbuffer();268 luaL_resetbuffer();
275 while (1) {269 for (;;) {
276 switch (LS->current) {270 switch (LS->current) {
277 271
278 case ' ': case '\t': case '\r': /* CR: to avoid problems with DOS */272 case ' ': case '\t': case '\r': /* CR: to avoid problems with DOS */
@@ -347,7 +341,7 @@ int luaX_lex (LexState *LS) { · 68 unmodified lines
347 c = 10*c + (LS->current-'0');341 c = 10*c + (LS->current-'0');
348 next(LS);342 next(LS);
349 } while (++i<3 && isdigit(LS->current));343 } while (++i<3 && isdigit(LS->current));
350 if (c >= 256)344 if (c != (unsigned char)c)
351 luaX_error(LS, "escape sequence too large");345 luaX_error(LS, "escape sequence too large");
352 save(c);346 save(c);
353 }347 }
@@ -364,8 +358,8 @@ int luaX_lex (LexState *LS) { · 10 unmodified lines
364 }358 }
365 }359 }
366 save_and_next(LS); /* skip delimiter */360 save_and_next(LS); /* skip delimiter */
367 LS->seminfo.ts = luaS_newlstr(L->Mbuffbase+1,361 LS->seminfo.ts = luaS_newlstr(L->Mbuffer+(L->Mbuffbase+1),
368 L->Mbuffnext-(L->Mbuffbase-L->Mbuffer)-2);362 L->Mbuffnext-L->Mbuffbase-2);
369 return STRING;363 return STRING;
370 }364 }
371 365
@@ -382,15 +376,11 @@ int luaX_lex (LexState *LS) { · 10 unmodified lines
382 else return CONC; /* .. */376 else return CONC; /* .. */
383 }377 }
384 else if (!isdigit(LS->current)) return '.';378 else if (!isdigit(LS->current)) return '.';
385 /* LS->current is a digit: goes through to number */379 goto fraction; /* LS->current is a digit: goes through to number */
386 a=0.0;
387 goto fraction;
388 380
389 case '0': case '1': case '2': case '3': case '4':381 case '0': case '1': case '2': case '3': case '4':
390 case '5': case '6': case '7': case '8': case '9':382 case '5': case '6': case '7': case '8': case '9':
391 a=0.0;
392 do {383 do {
393 a = 10.0*a + (LS->current-'0');
394 save_and_next(LS);384 save_and_next(LS);
395 } while (isdigit(LS->current));385 } while (isdigit(LS->current));
396 if (LS->current == '.') {386 if (LS->current == '.') {
@@ -402,35 +392,19 @@ int luaX_lex (LexState *LS) { · 5 unmodified lines
402 }392 }
403 }393 }
404 fraction:394 fraction:
405 { double da=0.1;395 while (isdigit(LS->current))
406 while (isdigit(LS->current))396 save_and_next(LS);
407 {397 if (toupper(LS->current) == 'E') {
408 a += (LS->current-'0')*da;398 save_and_next(LS); /* read 'E' */
409 da /= 10.0;399 save_and_next(LS); /* read '+', '-' or first digit */
410 save_and_next(LS);400 while (isdigit(LS->current))
411 }
412 if (toupper(LS->current) == 'E') {
413 int e = 0;
414 int neg;
415 double ea;
416 save_and_next(LS);401 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;
433 }402 }
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;
434 408
435 case EOZ:409 case EOZ:
436 if (LS->iflevel > 0)410 if (LS->iflevel > 0)
@@ -450,9 +424,9 @@ int luaX_lex (LexState *LS) { · 13 unmodified lines
450 do {424 do {
451 save_and_next(LS);425 save_and_next(LS);
452 } while (isalnum(LS->current) || LS->current == '_');426 } while (isalnum(LS->current) || LS->current == '_');
453 save(0);427 save('\0');
454 ts = luaS_new(L->Mbuffbase);428 ts = luaS_new(L->Mbuffer+L->Mbuffbase);
455 if (ts->head.marked >= 'A')429 if (ts->head.marked >= FIRST_RESERVED)
456 return ts->head.marked; /* reserved word */430 return ts->head.marked; /* reserved word */
457 LS->seminfo.ts = ts;431 LS->seminfo.ts = ts;
458 return NAME;432 return NAME;
src/llex.h+7−5
@@ -1,6 +1,6 @@
1/*1/*
2** $Id: llex.h,v 1.9 1998/06/19 16:14:09 roberto Exp $2** $Id: llex.h,v 1.12 1999/06/17 17:04:03 roberto Exp $
3** Lexical Analizer3** Lexical Analyzer
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
6 6
@@ -25,12 +25,14 @@ enum RESERVED { · 18 unmodified lines
25 NAME, CONC, DOTS, EQ, GE, LE, NE, NUMBER, STRING, EOS};25 NAME, CONC, DOTS, EQ, GE, LE, NE, NUMBER, STRING, EOS};
26 26
27 27
28#define MAX_IFS 528#ifndef MAX_IFS
29#define MAX_IFS 5 /* arbitrary limit */
30#endif
29 31
30/* "ifstate" keeps the state of each nested $if the lexical is dealing with. */32/* "ifstate" keeps the state of each nested $if the lexical is dealing with. */
31 33
32struct ifState {34struct ifState {
33 int elsepart; /* true if its in the $else part */35 int elsepart; /* true if it's in the $else part */
34 int condition; /* true if $if condition is true */36 int condition; /* true if $if condition is true */
35 int skip; /* true if part must be skipped */37 int skip; /* true if part must be skipped */
36};38};
@@ -56,7 +58,7 @@ void luaX_setinput (LexState *LS, ZIO *z); · 19 unmodified lines
56int luaX_lex (LexState *LS);58int luaX_lex (LexState *LS);
57void luaX_syntaxerror (LexState *ls, char *s, char *token);59void luaX_syntaxerror (LexState *ls, char *s, char *token);
58void luaX_error (LexState *ls, char *s);60void luaX_error (LexState *ls, char *s);
59void luaX_token2str (LexState *ls, int token, char *s);61void luaX_token2str (int token, char *s);
60 62
61 63
62#endif64#endif
src/lmem.c+80−53
@@ -1,5 +1,5 @@
1/*1/*
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 $
3** Interface to Memory Manager3** Interface to Memory Manager
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -12,41 +12,54 @@ · 6 unmodified lines
12#include "lua.h"12#include "lua.h"
13 13
14 14
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
15 28
16int luaM_growaux (void **block, unsigned long nelems, int size,29
17 char *errormsg, unsigned long limit)30static unsigned long power2 (unsigned long n) {
18{31 unsigned long p = MINSIZE;
19 if (nelems >= limit)32 while (p<=n) p<<=1;
20 lua_error(errormsg);33 return p;
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;
26}34}
27 35
28 36
37void *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
29 48
30#ifndef DEBUG49#ifndef DEBUG
31 50
32/*51/*
33** generic allocation routine.52** 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...
37*/53*/
38void *luaM_realloc (void *block, unsigned long size)54void *luaM_realloc (void *block, unsigned long size) {
39{
40 size_t s = (size_t)size;55 size_t s = (size_t)size;
41 if (s != size)56 if (s != size)
42 lua_error("Allocation Error: Block too big");57 lua_error("memory allocation error: block too big");
43 if (size == 0) {58 if (size == 0) {
44 if (block) {59 free(block); /* block may be NULL, that is OK for free */
45 free(block);
46 }
47 return NULL;60 return NULL;
48 }61 }
49 block = block ? realloc(block, s) : malloc(s);62 block = realloc(block, s);
50 if (block == NULL)63 if (block == NULL)
51 lua_error(memEM);64 lua_error(memEM);
52 return block;65 return block;
@@ -61,52 +74,66 @@ void *luaM_realloc (void *block, unsigned long size) · 8 unmodified lines
61 74
62 75
63#define HEADER (sizeof(double))76#define HEADER (sizeof(double))
77#define MARKSIZE 16
64 78
65#define MARK 5579#define MARK 55
66 80
81
82#define blocksize(b) ((unsigned long *)((char *)(b) - HEADER))
83
67unsigned long numblocks = 0;84unsigned long numblocks = 0;
68unsigned long totalmem = 0;85unsigned long totalmem = 0;
69 86
70 87
71static void *checkblock (void *block)88static void *checkblock (void *block) {
72{89 if (block == NULL)
73 unsigned long *b = (unsigned long *)((char *)block - HEADER);90 return NULL;
74 unsigned long size = *b;91 else {
75 LUA_ASSERT(*(((char *)b)+size+HEADER) == MARK, 92 unsigned long *b = blocksize(block);
76 "corrupted block");93 unsigned long size = *b;
77 numblocks--;94 int i;
78 totalmem -= size;95 for (i=0;i<MARKSIZE;i++)
79 return b;96 LUA_ASSERT(*(((char *)b)+HEADER+size+i) == MARK+i, "corrupted block");
97 numblocks--;
98 totalmem -= size;
99 return b;
100 }
80}101}
81 102
82 103
83void *luaM_realloc (void *block, unsigned long size)104static void freeblock (void *block) {
84{105 if (block)
85 unsigned long realsize = HEADER+size+1;106 memset(block, -1, *blocksize(block)); /* erase block */
107 free(checkblock(block));
108}
109
110
111void *luaM_realloc (void *block, unsigned long size) {
112 unsigned long realsize = HEADER+size+MARKSIZE;
86 if (realsize != (size_t)realsize)113 if (realsize != (size_t)realsize)
87 lua_error("Allocation Error: Block too big");114 lua_error("memory allocation error: block too big");
88 if (size == 0) { /* ANSI dosen't need this, but some machines... */115 if (size == 0) {
89 if (block) {116 freeblock(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 }
95 return NULL;117 return NULL;
96 }118 }
97 if (block) {119 else {
98 block = checkblock(block);120 char *newblock = malloc(realsize);
99 block = (unsigned long *)realloc(block, 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;
100 }136 }
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);
110}137}
111 138
112 139
src/lmem.h+7−9
@@ -1,5 +1,5 @@
1/*1/*
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 $
3** Interface to Memory Manager3** Interface to Memory Manager
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -8,10 +8,7 @@ · 2 unmodified lines
8#define lmem_h8#define lmem_h
9 9
10 10
11#ifndef NULL11#include <stdlib.h>
12#define NULL 0
13#endif
14
15 12
16/* memory error messages */13/* memory error messages */
17#define codeEM "code size overflow"14#define codeEM "code size overflow"
@@ -19,18 +16,19 @@ · 1 unmodified line
19#define refEM "reference table overflow"16#define refEM "reference table overflow"
20#define tableEM "table overflow"17#define tableEM "table overflow"
21#define memEM "not enough memory"18#define memEM "not enough memory"
19#define arrEM "internal array bigger than `int' limit"
22 20
23void *luaM_realloc (void *oldblock, unsigned long size);21void *luaM_realloc (void *oldblock, unsigned long size);
24int luaM_growaux (void **block, unsigned long nelems, int size,22void *luaM_growaux (void *block, unsigned long nelems, int inc, int size,
25 char *errormsg, unsigned long limit);23 char *errormsg, unsigned long limit);
26 24
27#define luaM_free(b) luaM_realloc((b), 0)25#define luaM_free(b) luaM_realloc((b), 0)
28#define luaM_malloc(t) luaM_realloc(NULL, (t))26#define luaM_malloc(t) luaM_realloc(NULL, (t))
29#define luaM_new(t) ((t *)luaM_malloc(sizeof(t)))27#define luaM_new(t) ((t *)luaM_malloc(sizeof(t)))
30#define luaM_newvector(n,t) ((t *)luaM_malloc((n)*sizeof(t)))28#define luaM_newvector(n,t) ((t *)luaM_malloc((n)*sizeof(t)))
31#define luaM_growvector(old,n,t,e,l) \29#define luaM_growvector(v,nelems,inc,t,e,l) \
32 (luaM_growaux((void**)old,n,sizeof(t),e,l))30 ((v)=(t *)luaM_growaux(v,nelems,inc,sizeof(t),e,l))
33#define luaM_reallocvector(v,n,t) ((t *)luaM_realloc(v,(n)*sizeof(t)))31#define luaM_reallocvector(v,n,t) ((v)=(t *)luaM_realloc(v,(n)*sizeof(t)))
34 32
35 33
36#ifdef DEBUG34#ifdef DEBUG
src/lobject.c+61−15
@@ -1,9 +1,10 @@
1/*1/*
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 $
3** Some generic functions over Lua objects3** Some generic functions over Lua objects
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
6 6
7#include <ctype.h>
7#include <stdlib.h>8#include <stdlib.h>
8 9
9#include "lobject.h"10#include "lobject.h"
@@ -34,14 +35,12 @@ int luaO_redimension (int oldsize) · 24 unmodified lines
34 if (dimensions[i] > oldsize)35 if (dimensions[i] > oldsize)
35 return dimensions[i];36 return dimensions[i];
36 }37 }
37 lua_error("table overflow");38 lua_error("tableEM");
38 return 0; /* to avoid warnings */39 return 0; /* to avoid warnings */
39}40}
40 41
41 42
42int luaO_equalObj (TObject *t1, TObject *t2)43int luaO_equalval (TObject *t1, TObject *t2) {
43{
44 if (ttype(t1) != ttype(t2)) return 0;
45 switch (ttype(t1)) {44 switch (ttype(t1)) {
46 case LUA_T_NIL: return 1;45 case LUA_T_NIL: return 1;
47 case LUA_T_NUMBER: return nvalue(t1) == nvalue(t2);46 case LUA_T_NUMBER: return nvalue(t1) == nvalue(t2);
@@ -64,20 +63,67 @@ void luaO_insertlist (GCnode *root, GCnode *node) · 16 unmodified lines
64 node->marked = 0;63 node->marked = 0;
65}64}
66 65
66
67#ifdef OLD_ANSI67#ifdef OLD_ANSI
68void luaO_memup (void *dest, void *src, int size)68void luaO_memup (void *dest, void *src, int size) {
69{69 while (size--)
70 char *d = dest;70 ((char *)dest)[size]=((char *)src)[size];
71 char *s = src;
72 while (size--) d[size]=s[size];
73}71}
74 72
75void luaO_memdown (void *dest, void *src, int size)73void luaO_memdown (void *dest, void *src, int size) {
76{
77 char *d = dest;
78 char *s = src;
79 int i;74 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];
81}77}
82#endif78#endif
83 79
80
81
82static 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
93double 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 @@
1/*1/*
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 $
3** Type definitions for Lua objects3** Type definitions for Lua objects
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -32,10 +32,6 @@ · 26 unmodified lines
32#define LUA_NUM_TYPE double32#define LUA_NUM_TYPE double
33#endif33#endif
34 34
35/*
36** format to convert number to strings
37*/
38#define NUMBER_FMT "%g"
39 35
40typedef LUA_NUM_TYPE real;36typedef LUA_NUM_TYPE real;
41 37
@@ -45,13 +41,6 @@ typedef unsigned char Byte; /* unsigned 8 bits */ · 3 unmodified lines
45 41
46#define MAX_INT (INT_MAX-2) /* maximum value of an int (-2 for safety) */42#define MAX_INT (INT_MAX-2) /* maximum value of an int (-2 for safety) */
47 43
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
55typedef unsigned int IntPoint; /* unsigned with same size as a pointer (for hashing) */44typedef unsigned int IntPoint; /* unsigned with same size as a pointer (for hashing) */
56 45
57 46
@@ -75,7 +64,6 @@ typedef enum { · 17 unmodified lines
75 LUA_T_LINE = -1164 LUA_T_LINE = -11
76} lua_Type;65} lua_Type;
77 66
78#define NUM_TYPES 11
79#define NUM_TAGS 767#define NUM_TAGS 7
80 68
81 69
@@ -139,7 +127,7 @@ typedef struct TProtoFunc { · 57 unmodified lines
139 int nconsts;127 int nconsts;
140 Byte *code; /* ends with opcode ENDCODE */128 Byte *code; /* ends with opcode ENDCODE */
141 int lineDefined;129 int lineDefined;
142 TaggedString *fileName;130 TaggedString *source;
143 struct LocVar *locvars; /* ends with line = -1 */131 struct LocVar *locvars; /* ends with line = -1 */
144} TProtoFunc;132} TProtoFunc;
145 133
@@ -192,11 +180,17 @@ typedef struct Hash { · 46 unmodified lines
192 180
193extern char *luaO_typenames[];181extern char *luaO_typenames[];
194 182
183#define luaO_typename(o) luaO_typenames[-ttype(o)]
184
185
195extern TObject luaO_nilobject;186extern TObject luaO_nilobject;
196 187
197int luaO_equalObj (TObject *t1, TObject *t2);188#define luaO_equalObj(t1,t2) ((ttype(t1) != ttype(t2)) ? 0 \
189 : luaO_equalval(t1,t2))
190int luaO_equalval (TObject *t1, TObject *t2);
198int luaO_redimension (int oldsize);191int luaO_redimension (int oldsize);
199void luaO_insertlist (GCnode *root, GCnode *node);192void luaO_insertlist (GCnode *root, GCnode *node);
193double luaO_str2d (char *s);
200 194
201#ifdef OLD_ANSI195#ifdef OLD_ANSI
202void luaO_memup (void *dest, void *src, int size);196void luaO_memup (void *dest, void *src, int size);
src/lopcodes.h+113−156
@@ -1,5 +1,5 @@
1/*1/*
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 $
3** Opcodes for Lua virtual machine3** Opcodes for Lua virtual machine
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -10,172 +10,129 @@ · 4 unmodified lines
10 10
11/*11/*
12** NOTICE: variants of the same opcode must be consecutive: First, those12** NOTICE: variants of the same opcode must be consecutive: First, those
13** with byte parameter, then with built-in parameters, and last with13** with word parameter, then with byte parameter.
14** word parameter.
15*/14*/
16 15
17 16
18typedef enum {17typedef enum {
19/* name parm before after side effect18/* name parm before after side effect
20-----------------------------------------------------------------------------*/19-----------------------------------------------------------------------------*/
21ENDCODE,/* - - - */20ENDCODE,/* - - (return) */
22 21RETCODE,/* b - (return) */
23PUSHNIL,/* b - nil_0...nil_b */22
24PUSHNIL0,/* - - nil */23CALL,/* b c v_c...v_1 f r_b...r_1 f(v1,...,v_c) */
25 24
26PUSHNUMBER,/* b - (float)b */25TAILCALL,/* b c v_c...v_1 f (return) f(v1,...,v_c) */
27PUSHNUMBER0,/* - - 0.0 */26
28PUSHNUMBER1,/* - - 1.0 */27PUSHNIL,/* b - nil_0...nil_b */
29PUSHNUMBER2,/* - - 2.0 */28POP,/* b a_b...a_1 - */
30PUSHNUMBERW,/* w - (float)w */29
31 30PUSHNUMBERW,/* w - (float)w */
32PUSHCONSTANT,/* b - CNST[b] */31PUSHNUMBER,/* b - (float)b */
33PUSHCONSTANT0,/*- - CNST[0] */32
34PUSHCONSTANT1,/*- - CNST[1] */33PUSHNUMBERNEGW,/* w - (float)-w */
35PUSHCONSTANT2,/*- - CNST[2] */34PUSHNUMBERNEG,/* b - (float)-b */
36PUSHCONSTANT3,/*- - CNST[3] */35
37PUSHCONSTANT4,/*- - CNST[4] */36PUSHCONSTANTW,/*w - CNST[w] */
38PUSHCONSTANT5,/*- - CNST[5] */37PUSHCONSTANT,/* b - CNST[b] */
39PUSHCONSTANT6,/*- - CNST[6] */38
40PUSHCONSTANT7,/*- - CNST[7] */39PUSHUPVALUE,/* b - Closure[b] */
41PUSHCONSTANTW,/*w - CNST[w] */40
42 41PUSHLOCAL,/* b - LOC[b] */
43PUSHUPVALUE,/* b - Closure[b] */42
44PUSHUPVALUE0,/* - - Closure[0] */43GETGLOBALW,/* w - VAR[CNST[w]] */
45PUSHUPVALUE1,/* - - Closure[1] */44GETGLOBAL,/* b - VAR[CNST[b]] */
46 45
47PUSHLOCAL,/* b - LOC[b] */46GETTABLE,/* - i t t[i] */
48PUSHLOCAL0,/* - - LOC[0] */47
49PUSHLOCAL1,/* - - LOC[1] */48GETDOTTEDW,/* w t t[CNST[w]] */
50PUSHLOCAL2,/* - - LOC[2] */49GETDOTTED,/* b t t[CNST[b]] */
51PUSHLOCAL3,/* - - LOC[3] */50
52PUSHLOCAL4,/* - - LOC[4] */51PUSHSELFW,/* w t t t[CNST[w]] */
53PUSHLOCAL5,/* - - LOC[5] */52PUSHSELF,/* b t t t[CNST[b]] */
54PUSHLOCAL6,/* - - LOC[6] */53
55PUSHLOCAL7,/* - - LOC[7] */54CREATEARRAYW,/* w - newarray(size = w) */
56 55CREATEARRAY,/* b - newarray(size = b) */
57GETGLOBAL,/* b - VAR[CNST[b]] */56
58GETGLOBAL0,/* - - VAR[CNST[0]] */57SETLOCAL,/* b x - LOC[b]=x */
59GETGLOBAL1,/* - - VAR[CNST[1]] */58
60GETGLOBAL2,/* - - VAR[CNST[2]] */59SETGLOBALW,/* w x - VAR[CNST[w]]=x */
61GETGLOBAL3,/* - - VAR[CNST[3]] */60SETGLOBAL,/* b x - VAR[CNST[b]]=x */
62GETGLOBAL4,/* - - VAR[CNST[4]] */61
63GETGLOBAL5,/* - - VAR[CNST[5]] */62SETTABLEPOP,/* - v i t - t[i]=v */
64GETGLOBAL6,/* - - VAR[CNST[6]] */63
65GETGLOBAL7,/* - - VAR[CNST[7]] */64SETTABLE,/* b v a_b...a_1 i t a_b...a_1 i t t[i]=v */
66GETGLOBALW,/* w - VAR[CNST[w]] */65
67 66SETLISTW,/* w c v_c...v_1 t t t[i+w*FPF]=v_i */
68GETTABLE,/* - i t t[i] */67SETLIST,/* b c v_c...v_1 t t t[i+b*FPF]=v_i */
69 68
70GETDOTTED,/* b t t[CNST[b]] */69SETMAP,/* b v_b k_b ...v_0 k_0 t t t[k_i]=v_i */
71GETDOTTED0,/* - t t[CNST[0]] */70
72GETDOTTED1,/* - t t[CNST[1]] */71NEQOP,/* - y x (x~=y)? 1 : nil */
73GETDOTTED2,/* - t t[CNST[2]] */72EQOP,/* - y x (x==y)? 1 : nil */
74GETDOTTED3,/* - t t[CNST[3]] */73LTOP,/* - y x (x<y)? 1 : nil */
75GETDOTTED4,/* - t t[CNST[4]] */74LEOP,/* - y x (x<y)? 1 : nil */
76GETDOTTED5,/* - t t[CNST[5]] */75GTOP,/* - y x (x>y)? 1 : nil */
77GETDOTTED6,/* - t t[CNST[6]] */76GEOP,/* - y x (x>=y)? 1 : nil */
78GETDOTTED7,/* - t t[CNST[7]] */77ADDOP,/* - y x x+y */
79GETDOTTEDW,/* w t t[CNST[w]] */78SUBOP,/* - y x x-y */
80 79MULTOP,/* - y x x*y */
81PUSHSELF,/* b t t t[CNST[b]] */80DIVOP,/* - y x x/y */
82PUSHSELF0,/* - t t t[CNST[0]] */81POWOP,/* - y x x^y */
83PUSHSELF1,/* - t t t[CNST[1]] */82CONCOP,/* - y x x..y */
84PUSHSELF2,/* - t t t[CNST[2]] */83MINUSOP,/* - x -x */
85PUSHSELF3,/* - t t t[CNST[3]] */84NOTOP,/* - x (x==nil)? 1 : nil */
86PUSHSELF4,/* - t t t[CNST[4]] */85
87PUSHSELF5,/* - t t t[CNST[5]] */86ONTJMPW,/* w x (x!=nil)? x : - (x!=nil)? PC+=w */
88PUSHSELF6,/* - t t t[CNST[6]] */87ONTJMP,/* b x (x!=nil)? x : - (x!=nil)? PC+=b */
89PUSHSELF7,/* - t t t[CNST[7]] */88ONFJMPW,/* w x (x==nil)? x : - (x==nil)? PC+=w */
90PUSHSELFW,/* w t t t[CNST[w]] */89ONFJMP,/* b x (x==nil)? x : - (x==nil)? PC+=b */
91 90JMPW,/* w - - PC+=w */
92CREATEARRAY,/* b - newarray(size = b) */91JMP,/* b - - PC+=b */
93CREATEARRAY0,/* - - newarray(size = 0) */92IFFJMPW,/* w x - (x==nil)? PC+=w */
94CREATEARRAY1,/* - - newarray(size = 1) */93IFFJMP,/* b x - (x==nil)? PC+=b */
95CREATEARRAYW,/* w - newarray(size = w) */94IFTUPJMPW,/* w x - (x!=nil)? PC-=w */
96 95IFTUPJMP,/* b x - (x!=nil)? PC-=b */
97SETLOCAL,/* b x - LOC[b]=x */96IFFUPJMPW,/* w x - (x==nil)? PC-=w */
98SETLOCAL0,/* - x - LOC[0]=x */97IFFUPJMP,/* b x - (x==nil)? PC-=b */
99SETLOCAL1,/* - x - LOC[1]=x */98
100SETLOCAL2,/* - x - LOC[2]=x */99CLOSUREW,/* w c v_c...v_1 closure(CNST[w], v_c...v_1) */
101SETLOCAL3,/* - x - LOC[3]=x */100CLOSURE,/* b c v_c...v_1 closure(CNST[b], v_c...v_1) */
102SETLOCAL4,/* - x - LOC[4]=x */101
103SETLOCAL5,/* - x - LOC[5]=x */102SETLINEW,/* w - - LINE=w */
104SETLOCAL6,/* - x - LOC[6]=x */103SETLINE,/* b - - LINE=b */
105SETLOCAL7,/* - x - LOC[7]=x */104
106 105LONGARGW,/* w (add w*(1<<16) to arg of next instruction) */
107SETGLOBAL,/* b x - VAR[CNST[b]]=x */106LONGARG,/* b (add b*(1<<16) to arg of next instruction) */
108SETGLOBAL0,/* - x - VAR[CNST[0]]=x */107
109SETGLOBAL1,/* - x - VAR[CNST[1]]=x */108CHECKSTACK /* b (assert #temporaries == b; only for internal debuging!) */
110SETGLOBAL2,/* - x - VAR[CNST[2]]=x */
111SETGLOBAL3,/* - x - VAR[CNST[3]]=x */
112SETGLOBAL4,/* - x - VAR[CNST[4]]=x */
113SETGLOBAL5,/* - x - VAR[CNST[5]]=x */
114SETGLOBAL6,/* - x - VAR[CNST[6]]=x */
115SETGLOBAL7,/* - x - VAR[CNST[7]]=x */
116SETGLOBALW,/* w x - VAR[CNST[w]]=x */
117
118SETTABLE0,/* - v i t - t[i]=v */
119
120SETTABLE,/* b v a_b...a_1 i t a_b...a_1 i t t[i]=v */
121
122SETLIST,/* b c v_c...v_1 t - t[i+b*FPF]=v_i */
123SETLIST0,/* b v_b...v_1 t - t[i]=v_i */
124SETLISTW,/* w c v_c...v_1 t - t[i+w*FPF]=v_i */
125
126SETMAP,/* b v_b k_b ...v_0 k_0 t t t[k_i]=v_i */
127SETMAP0,/* - v_0 k_0 t t t[k_0]=v_0 */
128
129EQOP,/* - y x (x==y)? 1 : nil */
130NEQOP,/* - y x (x~=y)? 1 : nil */
131LTOP,/* - y x (x<y)? 1 : nil */
132LEOP,/* - y x (x<y)? 1 : nil */
133GTOP,/* - y x (x>y)? 1 : nil */
134GEOP,/* - y x (x>=y)? 1 : nil */
135ADDOP,/* - y x x+y */
136SUBOP,/* - y x x-y */
137MULTOP,/* - y x x*y */
138DIVOP,/* - y x x/y */
139POWOP,/* - y x x^y */
140CONCOP,/* - y x x..y */
141MINUSOP,/* - x -x */
142NOTOP,/* - x (x==nil)? 1 : nil */
143
144ONTJMP,/* b x (x!=nil)? x : - (x!=nil)? PC+=b */
145ONTJMPW,/* w x (x!=nil)? x : - (x!=nil)? PC+=w */
146ONFJMP,/* b x (x==nil)? x : - (x==nil)? PC+=b */
147ONFJMPW,/* w x (x==nil)? x : - (x==nil)? PC+=w */
148JMP,/* b - - PC+=b */
149JMPW,/* w - - PC+=w */
150IFFJMP,/* b x - (x==nil)? PC+=b */
151IFFJMPW,/* w x - (x==nil)? PC+=w */
152IFTUPJMP,/* b x - (x!=nil)? PC-=b */
153IFTUPJMPW,/* w x - (x!=nil)? PC-=w */
154IFFUPJMP,/* b x - (x==nil)? PC-=b */
155IFFUPJMPW,/* w x - (x==nil)? PC-=w */
156
157CLOSURE,/* b c v_c...v_1 closure(CNST[b], v_c...v_1) */
158CLOSUREW,/* w c v_b...v_1 closure(CNST[w], v_c...v_1) */
159
160CALLFUNC,/* b c v_c...v_1 f r_b...r_1 f(v1,...,v_c) */
161CALLFUNC0,/* b v_b...v_1 f - f(v1,...,v_b) */
162CALLFUNC1,/* b v_b...v_1 f r_1 f(v1,...,v_b) */
163
164RETCODE,/* b - - */
165
166SETLINE,/* b - - LINE=b */
167SETLINEW,/* w - - LINE=w */
168
169POP,/* b - - TOP-=(b+1) */
170POP0,/* - - - TOP-=1 */
171POP1/* - - - TOP-=2 */
172 109
173} OpCode;110} OpCode;
174 111
175 112
176#define RFIELDS_PER_FLUSH 32 /* records (SETMAP) */113#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)
178 136
179#define ZEROVARARG 64
180 137
181#endif138#endif
src/lparser.c+314−256
@@ -1,11 +1,12 @@
1/*1/*
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 $
3** LL(1) Parser and code generator for Lua3** LL(1) Parser and code generator for Lua
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
6 6
7 7
8#include <stdio.h>8#include <stdio.h>
9#include <string.h>
9 10
10#include "lauxlib.h"11#include "lauxlib.h"
11#include "ldo.h"12#include "ldo.h"
@@ -21,35 +22,48 @@ · 9 unmodified lines
21#include "lzio.h"22#include "lzio.h"
22 23
23 24
24/* for limit numbers in error messages */
25#define MES_LIM(x) "(limit=" x ")"
26
27 25
28/* size of a "normal" jump instruction: OpCode + 1 byte */26/* size of a "normal" jump instruction: OpCode + 1 byte */
29#define JMPSIZE 227#define JMPSIZE 2
30 28
31/* maximum number of local variables */29/* maximum number of local variables */
32#define MAXLOCALS 3230#ifndef MAXLOCALS
33#define SMAXLOCALS "32"31#define MAXLOCALS 200 /* arbitrary limit (<256) */
32#endif
34 33
35 34
36/* maximum number of upvalues */35/* maximum number of upvalues */
37#define MAXUPVALUES 1636#ifndef MAXUPVALUES
38#define SMAXUPVALUES "16"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
39 51
40 52
41/*53/*
42** Variable descriptor:54** Variable descriptor:
43** must include a "exp" option because LL(1) cannot distinguish55** must include an "exp" option because LL(1) cannot distinguish
44** between variables, upvalues and function calls on first sight.56** 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)
49*/57*/
50typedef enum {VGLOBAL, VLOCAL, VDOT, VINDEXED, VEXP} varkind;58typedef enum {
51 59 VGLOBAL, /* info is constant index of global name */
52typedef struct {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
66typedef struct vardesc {
53 varkind k;67 varkind k;
54 int info;68 int info;
55} vardesc;69} vardesc;
@@ -61,7 +75,7 @@ typedef struct { · 5 unmodified lines
61** and, if last expression is open (a function call),75** and, if last expression is open (a function call),
62** where is its pc index of "nparam"76** where is its pc index of "nparam"
63*/77*/
64typedef struct {78typedef struct listdesc {
65 int n;79 int n;
66 int pc; /* 0 if last expression is closed */80 int pc; /* 0 if last expression is closed */
67} listdesc;81} listdesc;
@@ -73,7 +87,7 @@ typedef struct { · 5 unmodified lines
73** it is a list constructor (k = 0) or a record constructor (k = 1)87** it is a list constructor (k = 0) or a record constructor (k = 1)
74** or empty (k = ';' or '}')88** or empty (k = ';' or '}')
75*/89*/
76typedef struct {90typedef struct constdesc {
77 int n;91 int n;
78 int k;92 int k;
79} constdesc;93} constdesc;
@@ -88,16 +102,16 @@ typedef struct FuncState { · 8 unmodified lines
88 int maxstacksize; /* maximum number of values on activation register */102 int maxstacksize; /* maximum number of values on activation register */
89 int nlocalvar; /* number of active local variables */103 int nlocalvar; /* number of active local variables */
90 int nupvalues; /* number of upvalues */104 int nupvalues; /* number of upvalues */
91 int nvars; /* number of entries in f->locvars */105 int nvars; /* number of entries in f->locvars (-1 if no debug information) */
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 */
95 int lastsetline; /* line where last SETLINE was issued */106 int lastsetline; /* line where last SETLINE was issued */
96 vardesc upvalues[MAXUPVALUES]; /* upvalues */107 vardesc upvalues[MAXUPVALUES]; /* upvalues */
97 TaggedString *localvar[MAXLOCALS]; /* store local variable names */108 TaggedString *localvar[MAXLOCALS]; /* store local variable names */
98} FuncState;109} FuncState;
99 110
100 111
112/*
113** prototypes for non-terminal functions
114*/
101static int assignment (LexState *ls, vardesc *v, int nvars);115static int assignment (LexState *ls, vardesc *v, int nvars);
102static int cond (LexState *ls);116static int cond (LexState *ls);
103static int funcname (LexState *ls, vardesc *v);117static int funcname (LexState *ls, vardesc *v);
@@ -117,22 +131,28 @@ static void exp1 (LexState *ls); · 13 unmodified lines
117static void exp2 (LexState *ls, vardesc *v);131static void exp2 (LexState *ls, vardesc *v);
118static void explist (LexState *ls, listdesc *e);132static void explist (LexState *ls, listdesc *e);
119static void explist1 (LexState *ls, listdesc *e);133static void explist1 (LexState *ls, listdesc *e);
120static void ifpart (LexState *ls);134static void ifpart (LexState *ls, int line);
121static void parlist (LexState *ls);135static void parlist (LexState *ls);
122static void part (LexState *ls, constdesc *cd);136static void part (LexState *ls, constdesc *cd);
123static void recfield (LexState *ls);137static void recfield (LexState *ls);
124static void ret (LexState *ls);138static void ret (LexState *ls);
125static void simpleexp (LexState *ls, vardesc *v);
126static void statlist (LexState *ls);139static void statlist (LexState *ls);
127static void var_or_func (LexState *ls, vardesc *v);140static void var_or_func (LexState *ls, vardesc *v);
128static void var_or_func_tail (LexState *ls, vardesc *v);141static void var_or_func_tail (LexState *ls, vardesc *v);
129 142
130 143
131 144
145static 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
132static void check_pc (FuncState *fs, int n) {154static void check_pc (FuncState *fs, int n) {
133 if (fs->pc+n > fs->maxcode)155 luaM_growvector(fs->f->code, fs->pc, n, Byte, codeEM, MAX_INT);
134 fs->maxcode = luaM_growvector(&fs->f->code, fs->maxcode,
135 Byte, codeEM, MAX_INT);
136}156}
137 157
138 158
@@ -146,76 +166,79 @@ static void deltastack (LexState *ls, int delta) { · 7 unmodified lines
146 FuncState *fs = ls->fs;166 FuncState *fs = ls->fs;
147 fs->stacksize += delta;167 fs->stacksize += delta;
148 if (fs->stacksize > fs->maxstacksize) {168 if (fs->stacksize > fs->maxstacksize) {
149 if (fs->stacksize > 255)169 if (fs->stacksize > MAX_BYTE)
150 luaX_error(ls, "function/expression too complex");170 luaX_error(ls, "function/expression too complex");
151 fs->maxstacksize = fs->stacksize;171 fs->maxstacksize = fs->stacksize;
152 }172 }
153}173}
154 174
155 175
156static int code_oparg_at (LexState *ls, int pc, OpCode op, int builtin,176static void code_oparg_at (LexState *ls, int pc, OpCode op,
157 int arg, int delta) {177 int arg, int delta) {
158 Byte *code = ls->fs->f->code;178 Byte *code = ls->fs->f->code;
159 deltastack(ls, delta);179 deltastack(ls, delta);
160 if (arg < builtin) {180 if (arg <= MAX_BYTE) {
161 code[pc] = op+1+arg;181 code[pc] = (Byte)op;
162 return 1;182 code[pc+1] = (Byte)arg;
163 }183 }
164 else if (arg <= 255) {184 else if (arg > MAX_ARG)
165 code[pc] = op;185 luaX_error(ls, "code too long");
166 code[pc+1] = arg;186 else { /* MAX_BYTE < arg < MAX_ARG */
167 return 2;187 if (arg > MAX_WORD) {
168 }188 code[pc] = (Byte)LONGARG;
169 else if (arg <= MAX_WORD) {189 code[pc+1] = (Byte)(arg>>16);
170 code[pc] = op+1+builtin;190 pc += 2;
171 code[pc+1] = arg>>8;191 }
172 code[pc+2] = arg&0xFF;192 code[pc] = (Byte)(op-1); /* opcode for word argument */
173 return 3;193 code[pc+1] = (Byte)((arg&0xFFFF)>>8);
194 code[pc+2] = (Byte)(arg&0xFF);
174 }195 }
175 else luaX_error(ls, "code too long " MES_LIM("64K"));
176 return 0; /* to avoid warnings */
177}196}
178 197
179 198
180static int fix_opcode (LexState *ls, int pc, OpCode op, int builtin, int arg) {199static int codesize (int arg) {
181 FuncState *fs = ls->fs;200 if (arg <= MAX_BYTE) return 2; /* opcode + 1 byte */
182 TProtoFunc *f = fs->f;201 else if (arg <= MAX_WORD) return 3; /* opcode + 1 word (2 bytes) */
183 if (arg < builtin) { /* close space */202 else return 5; /* LONGARG + 1 byte + opcode + 1 word (2 bytes) */
184 luaO_memdown(f->code+pc+1, f->code+pc+2, fs->pc-(pc+2));203}
185 fs->pc--;204
186 }205
187 else if (arg > 255) { /* open space */206static int fix_opcode (LexState *ls, int pc, OpCode op, int arg) {
188 check_pc(fs, 1);207 int tomove = codesize(arg)-2;
189 luaO_memup(f->code+pc+1, f->code+pc, fs->pc-pc);208 if (tomove > 0) { /* need to open space? */
190 fs->pc++;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;
191 }214 }
192 return code_oparg_at(ls, pc, op, builtin, arg, 0) - 2;215 code_oparg_at(ls, pc, op, arg, 0);
216 return tomove;
193}217}
194 218
195static void code_oparg (LexState *ls, OpCode op, int builtin, int arg,219
196 int delta) {220static void code_oparg (LexState *ls, OpCode op, int arg, int delta) {
197 check_pc(ls->fs, 3); /* maximum code size */221 int size = codesize(arg);
198 ls->fs->pc += code_oparg_at(ls, ls->fs->pc, op, builtin, arg, delta);222 check_pc(ls->fs, size);
223 code_oparg_at(ls, ls->fs->pc, op, arg, delta);
224 ls->fs->pc += size;
199}225}
200 226
201 227
202static void code_opcode (LexState *ls, OpCode op, int delta) {228static void code_opcode (LexState *ls, OpCode op, int delta) {
203 deltastack(ls, delta);229 deltastack(ls, delta);
204 code_byte(ls->fs, op);230 code_byte(ls->fs, (Byte)op);
205}231}
206 232
207 233
208static void code_constant (LexState *ls, int c) {234static void code_constant (LexState *ls, int c) {
209 code_oparg(ls, PUSHCONSTANT, 8, c, 1);235 code_oparg(ls, PUSHCONSTANT, c, 1);
210}236}
211 237
212 238
213static int next_constant (FuncState *fs) {239static int next_constant (FuncState *fs) {
214 TProtoFunc *f = fs->f;240 TProtoFunc *f = fs->f;
215 if (f->nconsts >= fs->maxconsts) {241 luaM_growvector(f->consts, f->nconsts, 1, TObject, constantEM, MAX_ARG);
216 fs->maxconsts = luaM_growvector(&f->consts, fs->maxconsts, TObject,
217 constantEM, MAX_WORD);
218 }
219 return f->nconsts++;242 return f->nconsts++;
220}243}
221 244
@@ -249,9 +272,9 @@ static int real_constant (FuncState *fs, real r) { · 27 unmodified lines
249 if (ttype(&cnt[c]) == LUA_T_NUMBER && nvalue(&cnt[c]) == r)272 if (ttype(&cnt[c]) == LUA_T_NUMBER && nvalue(&cnt[c]) == r)
250 return c;273 return c;
251 }274 }
252 /* not found; create a luaM_new entry */275 /* not found; create a new entry */
253 c = next_constant(fs);276 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 */
255 ttype(&cnt[c]) = LUA_T_NUMBER;278 ttype(&cnt[c]) = LUA_T_NUMBER;
256 nvalue(&cnt[c]) = r;279 nvalue(&cnt[c]) = r;
257 return c;280 return c;
@@ -259,9 +282,11 @@ static int real_constant (FuncState *fs, real r) { · 1 unmodified line
259 282
260 283
261static void code_number (LexState *ls, real f) {284static void code_number (LexState *ls, real f) {
262 int i;285 real af = (f<0) ? -f : f;
263 if (f >= 0 && f <= (real)MAX_WORD && (real)(i=(int)f) == f)286 if (0 <= af && af <= (real)MAX_WORD && (int)af == af) {
264 code_oparg(ls, PUSHNUMBER, 3, i, 1); /* f has a short integer value */287 /* abs(f) has a short integer value */
288 code_oparg(ls, (f<0) ? PUSHNUMBERNEG : PUSHNUMBER, (int)af, 1);
289 }
265 else290 else
266 code_constant(ls, real_constant(ls->fs, f));291 code_constant(ls, real_constant(ls->fs, f));
267}292}
@@ -269,24 +294,23 @@ static void code_number (LexState *ls, real f) { · 1 unmodified line
269 294
270static void flush_record (LexState *ls, int n) {295static void flush_record (LexState *ls, int n) {
271 if (n > 0)296 if (n > 0)
272 code_oparg(ls, SETMAP, 1, n-1, -2*n);297 code_oparg(ls, SETMAP, n-1, -2*n);
273}298}
274 299
275 300
276static void flush_list (LexState *ls, int m, int n) {301static void flush_list (LexState *ls, int m, int n) {
277 if (n == 0) return;302 if (n > 0) {
278 code_oparg(ls, SETLIST, 1, m, -n);303 code_oparg(ls, SETLIST, m, -n);
279 code_byte(ls->fs, n);304 code_byte(ls->fs, (Byte)n);
305 }
280}306}
281 307
282 308
283static void luaI_registerlocalvar (FuncState *fs, TaggedString *varname,309static void luaI_registerlocalvar (FuncState *fs, TaggedString *varname,
284 int line) {310 int line) {
285 if (fs->maxvars != -1) { /* debug information? */311 if (fs->nvars != -1) { /* debug information? */
286 TProtoFunc *f = fs->f;312 TProtoFunc *f = fs->f;
287 if (fs->nvars >= fs->maxvars)313 luaM_growvector(f->locvars, fs->nvars, 1, LocVar, "", MAX_INT);
288 fs->maxvars = luaM_growvector(&f->locvars, fs->maxvars,
289 LocVar, "", MAX_WORD);
290 f->locvars[fs->nvars].varname = varname;314 f->locvars[fs->nvars].varname = varname;
291 f->locvars[fs->nvars].line = line;315 f->locvars[fs->nvars].line = line;
292 fs->nvars++;316 fs->nvars++;
@@ -301,10 +325,8 @@ static void luaI_unregisterlocalvar (FuncState *fs, int line) { · 8 unmodified lines
301 325
302static void store_localvar (LexState *ls, TaggedString *name, int n) {326static void store_localvar (LexState *ls, TaggedString *name, int n) {
303 FuncState *fs = ls->fs;327 FuncState *fs = ls->fs;
304 if (fs->nlocalvar+n < MAXLOCALS)328 checklimit(ls, fs->nlocalvar+n+1, MAXLOCALS, "local variables");
305 fs->localvar[fs->nlocalvar+n] = name;329 fs->localvar[fs->nlocalvar+n] = name;
306 else
307 luaX_error(ls, "too many local variables " MES_LIM(SMAXLOCALS));
308 luaI_registerlocalvar(fs, name, ls->linenumber);330 luaI_registerlocalvar(fs, name, ls->linenumber);
309}331}
310 332
@@ -315,6 +337,16 @@ static void add_localvar (LexState *ls, TaggedString *name) { · 4 unmodified lines
315}337}
316 338
317 339
340static 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
318static int aux_localname (FuncState *fs, TaggedString *n) {350static int aux_localname (FuncState *fs, TaggedString *n) {
319 int i;351 int i;
320 for (i=fs->nlocalvar-1; i >= 0; i--)352 for (i=fs->nlocalvar-1; i >= 0; i--)
@@ -326,13 +358,13 @@ static int aux_localname (FuncState *fs, TaggedString *n) { · 5 unmodified lines
326static void singlevar (LexState *ls, TaggedString *n, vardesc *var, int prev) {358static void singlevar (LexState *ls, TaggedString *n, vardesc *var, int prev) {
327 FuncState *fs = prev ? ls->fs->prev : ls->fs;359 FuncState *fs = prev ? ls->fs->prev : ls->fs;
328 int i = aux_localname(fs, n);360 int i = aux_localname(fs, n);
329 if (i >= 0) { /* local value */361 if (i >= 0) { /* local value? */
330 var->k = VLOCAL;362 var->k = VLOCAL;
331 var->info = i;363 var->info = i;
332 }364 }
333 else { /* check shadowing */365 else {
334 FuncState *level = fs;366 FuncState *level = fs;
335 while ((level = level->prev) != NULL)367 while ((level = level->prev) != NULL) /* check shadowing */
336 if (aux_localname(level, n) >= 0)368 if (aux_localname(level, n) >= 0)
337 luaX_syntaxerror(ls, "cannot access a variable in outer scope", n->str);369 luaX_syntaxerror(ls, "cannot access a variable in outer scope", n->str);
338 var->k = VGLOBAL;370 var->k = VGLOBAL;
@@ -351,29 +383,26 @@ static int indexupvalue (LexState *ls, TaggedString *n) { · 12 unmodified lines
351 return i;383 return i;
352 }384 }
353 /* new one */385 /* new one */
354 if (++(fs->nupvalues) > MAXUPVALUES)386 ++(fs->nupvalues);
355 luaX_error(ls, "too many upvalues in a single function "387 checklimit(ls, fs->nupvalues, MAXUPVALUES, "upvalues");
356 MES_LIM(SMAXUPVALUES));
357 fs->upvalues[i] = v; /* i = fs->nupvalues - 1 */388 fs->upvalues[i] = v; /* i = fs->nupvalues - 1 */
358 return i;389 return i;
359}390}
360 391
361 392
362static void pushupvalue (LexState *ls, TaggedString *n) {393static void pushupvalue (LexState *ls, TaggedString *n) {
363 int i;
364 if (ls->fs->prev == NULL)394 if (ls->fs->prev == NULL)
365 luaX_syntaxerror(ls, "cannot access upvalue in main", n->str);395 luaX_syntaxerror(ls, "cannot access upvalue in main", n->str);
366 if (aux_localname(ls->fs, n) >= 0)396 if (aux_localname(ls->fs, n) >= 0)
367 luaX_syntaxerror(ls, "cannot access an upvalue in current scope", n->str);397 luaX_syntaxerror(ls, "cannot access an upvalue in current scope", n->str);
368 i = indexupvalue(ls, n);398 code_oparg(ls, PUSHUPVALUE, indexupvalue(ls, n), 1);
369 code_oparg(ls, PUSHUPVALUE, 2, i, 1);
370}399}
371 400
372 401
373 402
374static void check_debugline (LexState *ls) {403static void check_debugline (LexState *ls) {
375 if (lua_debug && ls->linenumber != ls->fs->lastsetline) {404 if (L->debug && ls->linenumber != ls->fs->lastsetline) {
376 code_oparg(ls, SETLINE, 0, ls->linenumber, 0);405 code_oparg(ls, SETLINE, ls->linenumber, 0);
377 ls->fs->lastsetline = ls->linenumber;406 ls->fs->lastsetline = ls->linenumber;
378 }407 }
379}408}
@@ -381,22 +410,22 @@ static void check_debugline (LexState *ls) { · 1 unmodified line
381 410
382static void adjuststack (LexState *ls, int n) {411static void adjuststack (LexState *ls, int n) {
383 if (n > 0)412 if (n > 0)
384 code_oparg(ls, POP, 2, n-1, -n);413 code_oparg(ls, POP, n, -n);
385 else if (n < 0)414 else if (n < 0)
386 code_oparg(ls, PUSHNIL, 1, (-n)-1, -n);415 code_oparg(ls, PUSHNIL, (-n)-1, -n);
387}416}
388 417
389 418
390static void close_exp (LexState *ls, int pc, int nresults) {419static 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? */
392 Byte *code = ls->fs->f->code;421 Byte *code = ls->fs->f->code;
393 int nparams = code[pc]; /* save nparams */422 code[pc-1] = (Byte)nresults; /* set nresults */
394 pc += fix_opcode(ls, pc-2, CALLFUNC, 2, nresults);423 /* push results, pop params (at code[pc]) and function */
395 code[pc] = nparams; /* restore nparams */424 deltastack(ls, nresults-(code[pc]+1));
396 if (nresults != MULT_RET)
397 deltastack(ls, nresults); /* "push" results */
398 deltastack(ls, -(nparams+1)); /* "pop" params and function */
399 }425 }
426#ifdef DEBUG
427 code_oparg(ls, CHECKSTACK, ls->fs->stacksize, 0);
428#endif
400}429}
401 430
402 431
@@ -408,7 +437,7 @@ static void adjust_mult_assign (LexState *ls, int nvars, listdesc *d) { · 5 unmodified lines
408 }437 }
409 else { /* must correct function call */438 else { /* must correct function call */
410 diff--; /* do not count function call itself */439 diff--; /* do not count function call itself */
411 if (diff < 0) { /* more variables than values */440 if (diff <= 0) { /* more variables than values? */
412 /* function call must provide extra values */441 /* function call must provide extra values */
413 close_exp(ls, d->pc, -diff);442 close_exp(ls, d->pc, -diff);
414 }443 }
@@ -423,29 +452,39 @@ static void adjust_mult_assign (LexState *ls, int nvars, listdesc *d) { · 8 unmodified lines
423static void code_args (LexState *ls, int nparams, int dots) {452static void code_args (LexState *ls, int nparams, int dots) {
424 FuncState *fs = ls->fs;453 FuncState *fs = ls->fs;
425 fs->nlocalvar += nparams; /* "self" may already be there */454 fs->nlocalvar += nparams; /* "self" may already be there */
455 checklimit(ls, fs->nlocalvar, MAXPARAMS, "parameters");
426 nparams = fs->nlocalvar;456 nparams = fs->nlocalvar;
427 if (!dots) {457 if (!dots) {
428 fs->f->code[1] = nparams; /* fill-in arg information */458 fs->f->code[1] = (Byte)nparams; /* fill-in arg information */
429 deltastack(ls, nparams);459 deltastack(ls, nparams);
430 }460 }
431 else {461 else {
432 fs->f->code[1] = nparams+ZEROVARARG;462 fs->f->code[1] = (Byte)(nparams+ZEROVARARG);
433 deltastack(ls, nparams+1);463 deltastack(ls, nparams+1);
434 add_localvar(ls, luaS_new("arg"));464 add_localvar(ls, luaS_new("arg"));
435 }465 }
436}466}
437 467
438 468
469static 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
439static void lua_pushvar (LexState *ls, vardesc *var) {478static void lua_pushvar (LexState *ls, vardesc *var) {
440 switch (var->k) {479 switch (var->k) {
441 case VLOCAL:480 case VLOCAL:
442 code_oparg(ls, PUSHLOCAL, 8, var->info, 1);481 code_oparg(ls, PUSHLOCAL, var->info, 1);
443 break;482 break;
444 case VGLOBAL:483 case VGLOBAL:
445 code_oparg(ls, GETGLOBAL, 8, var->info, 1);484 code_oparg(ls, GETGLOBAL, var->info, 1);
446 break;485 break;
447 case VDOT:486 case VDOT:
448 code_oparg(ls, GETDOTTED, 8, var->info, 0);487 code_oparg(ls, GETDOTTED, var->info, 0);
449 break;488 break;
450 case VINDEXED:489 case VINDEXED:
451 code_opcode(ls, GETTABLE, -1);490 code_opcode(ls, GETTABLE, -1);
@@ -462,13 +501,13 @@ static void lua_pushvar (LexState *ls, vardesc *var) { · 10 unmodified lines
462static void storevar (LexState *ls, vardesc *var) {501static void storevar (LexState *ls, vardesc *var) {
463 switch (var->k) {502 switch (var->k) {
464 case VLOCAL:503 case VLOCAL:
465 code_oparg(ls, SETLOCAL, 8, var->info, -1);504 code_oparg(ls, SETLOCAL, var->info, -1);
466 break;505 break;
467 case VGLOBAL:506 case VGLOBAL:
468 code_oparg(ls, SETGLOBAL, 8, var->info, -1);507 code_oparg(ls, SETGLOBAL, var->info, -1);
469 break;508 break;
470 case VINDEXED:509 case VINDEXED:
471 code_opcode(ls, SETTABLE0, -3);510 code_opcode(ls, SETTABLEPOP, -3);
472 break;511 break;
473 default:512 default:
474 LUA_INTERNALERROR("invalid var kind to store");513 LUA_INTERNALERROR("invalid var kind to store");
@@ -478,21 +517,20 @@ static void storevar (LexState *ls, vardesc *var) { · 3 unmodified lines
478 517
479static int fix_jump (LexState *ls, int pc, OpCode op, int n) {518static int fix_jump (LexState *ls, int pc, OpCode op, int n) {
480 /* jump is relative to position following jump instruction */519 /* 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));
482}521}
483 522
484 523
485static void fix_upjmp (LexState *ls, OpCode op, int pos) {524static void fix_upjmp (LexState *ls, OpCode op, int pos) {
486 int delta = ls->fs->pc+JMPSIZE - pos; /* jump is relative */525 int delta = ls->fs->pc+JMPSIZE - pos; /* jump is relative */
487 if (delta > 255) delta++;526 code_oparg(ls, op, delta+(codesize(delta)-2), 0);
488 code_oparg(ls, op, 0, delta, 0);
489}527}
490 528
491 529
492static void codeIf (LexState *ls, int thenAdd, int elseAdd) {530static void codeIf (LexState *ls, int thenAdd, int elseAdd) {
493 FuncState *fs = ls->fs;531 FuncState *fs = ls->fs;
494 int elseinit = elseAdd+JMPSIZE;532 int elseinit = elseAdd+JMPSIZE;
495 if (fs->pc == elseinit) { /* no else part */533 if (fs->pc == elseinit) { /* no else part? */
496 fs->pc -= JMPSIZE;534 fs->pc -= JMPSIZE;
497 elseinit = fs->pc;535 elseinit = fs->pc;
498 }536 }
@@ -513,13 +551,14 @@ static void func_onstack (LexState *ls, FuncState *func) { · 14 unmodified lines
513 else {551 else {
514 for (i=0; i<func->nupvalues; i++)552 for (i=0; i<func->nupvalues; i++)
515 lua_pushvar(ls, &func->upvalues[i]);553 lua_pushvar(ls, &func->upvalues[i]);
516 code_oparg(ls, CLOSURE, 0, c, -func->nupvalues+1);554 deltastack(ls, 1); /* CLOSURE puts one extra element (before poping) */
517 code_byte(fs, func->nupvalues);555 code_oparg(ls, CLOSURE, c, -func->nupvalues);
556 code_byte(fs, (Byte)func->nupvalues);
518 }557 }
519}558}
520 559
521 560
522static void init_state (LexState *ls, FuncState *fs, TaggedString *filename) {561static void init_state (LexState *ls, FuncState *fs, TaggedString *source) {
523 TProtoFunc *f = luaF_newproto();562 TProtoFunc *f = luaF_newproto();
524 fs->prev = ls->fs; /* linked list of funcstates */563 fs->prev = ls->fs; /* linked list of funcstates */
525 ls->fs = fs;564 ls->fs = fs;
@@ -529,17 +568,15 @@ static void init_state (LexState *ls, FuncState *fs, TaggedString *filename) { · 3 unmodified lines
529 fs->nupvalues = 0;568 fs->nupvalues = 0;
530 fs->lastsetline = 0;569 fs->lastsetline = 0;
531 fs->f = f;570 fs->f = f;
532 f->fileName = filename;571 f->source = source;
533 fs->pc = 0;572 fs->pc = 0;
534 fs->maxcode = 0;
535 f->code = NULL;573 f->code = NULL;
536 fs->maxconsts = 0;574 fs->nvars = (L->debug) ? 0 : -1; /* flag no debug information? */
537 if (lua_debug)575 code_byte(fs, 0); /* to be filled with maxstacksize */
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 */
542 code_byte(fs, 0); /* to be filled with arg information */576 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;
543}580}
544 581
545 582
@@ -547,14 +584,15 @@ static void close_func (LexState *ls) { · 1 unmodified line
547 FuncState *fs = ls->fs;584 FuncState *fs = ls->fs;
548 TProtoFunc *f = fs->f;585 TProtoFunc *f = fs->f;
549 code_opcode(ls, ENDCODE, 0);586 code_opcode(ls, ENDCODE, 0);
550 f->code[0] = fs->maxstacksize;587 f->code[0] = (Byte)fs->maxstacksize;
551 f->code = luaM_reallocvector(f->code, fs->pc, Byte);588 luaM_reallocvector(f->code, fs->pc, Byte);
552 f->consts = luaM_reallocvector(f->consts, f->nconsts, TObject);589 luaM_reallocvector(f->consts, f->nconsts, TObject);
553 if (fs->maxvars != -1) { /* debug information? */590 if (fs->nvars != -1) { /* debug information? */
554 luaI_registerlocalvar(fs, NULL, -1); /* flag end of vector */591 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);
556 }593 }
557 ls->fs = fs->prev;594 ls->fs = fs->prev;
595 L->stack.top--; /* pop function */
558}596}
559 597
560 598
@@ -562,13 +600,11 @@ static void close_func (LexState *ls) { · 1 unmodified line
562static int expfollow [] = {ELSE, ELSEIF, THEN, IF, WHILE, REPEAT, DO, NAME,600static int expfollow [] = {ELSE, ELSEIF, THEN, IF, WHILE, REPEAT, DO, NAME,
563 LOCAL, FUNCTION, END, UNTIL, RETURN, ')', ']', '}', ';', EOS, ',', 0};601 LOCAL, FUNCTION, END, UNTIL, RETURN, ')', ']', '}', ';', EOS, ',', 0};
564 602
603
565static int is_in (int tok, int *toks) {604static int is_in (int tok, int *toks) {
566 int *t = toks;605 int *t;
567 while (*t) {606 for (t=toks; *t; t++)
568 if (*t == tok)607 if (*t == tok) return t-toks;
569 return t-toks;
570 t++;
571 }
572 return -1;608 return -1;
573}609}
574 610
@@ -580,19 +616,25 @@ static void next (LexState *ls) { · 5 unmodified lines
580 616
581static void error_expected (LexState *ls, int token) {617static void error_expected (LexState *ls, int token) {
582 char buff[100], t[TOKEN_LEN];618 char buff[100], t[TOKEN_LEN];
583 luaX_token2str(ls, token, t);619 luaX_token2str(token, t);
584 sprintf(buff, "`%s' expected", t);620 sprintf(buff, "`%s' expected", t);
585 luaX_error(ls, buff);621 luaX_error(ls, buff);
586}622}
587 623
624
625static void error_unexpected (LexState *ls) {
626 luaX_error(ls, "unexpected token");
627}
628
629
588static void error_unmatched (LexState *ls, int what, int who, int where) {630static void error_unmatched (LexState *ls, int what, int who, int where) {
589 if (where == ls->linenumber)631 if (where == ls->linenumber)
590 error_expected(ls, what);632 error_expected(ls, what);
591 else {633 else {
592 char buff[100];634 char buff[100];
593 char t_what[TOKEN_LEN], t_who[TOKEN_LEN];635 char t_what[TOKEN_LEN], t_who[TOKEN_LEN];
594 luaX_token2str(ls, what, t_what);636 luaX_token2str(what, t_what);
595 luaX_token2str(ls, who, t_who);637 luaX_token2str(who, t_who);
596 sprintf(buff, "`%s' expected (to close `%s' at line %d)",638 sprintf(buff, "`%s' expected (to close `%s' at line %d)",
597 t_what, t_who, where);639 t_what, t_who, where);
598 luaX_error(ls, buff);640 luaX_error(ls, buff);
@@ -612,13 +654,18 @@ static void check_match (LexState *ls, int what, int who, int where) { · 13 unmodified lines
612 next(ls);654 next(ls);
613}655}
614 656
615static TaggedString *checkname (LexState *ls) {657static int checkname (LexState *ls) {
616 TaggedString *ts;658 int sc;
617 if (ls->token != NAME)659 if (ls->token != NAME)
618 luaX_error(ls, "`NAME' expected");660 luaX_error(ls, "`NAME' expected");
619 ts = ls->seminfo.ts;661 sc = string_constant(ls->fs, ls->seminfo.ts);
620 next(ls);662 next(ls);
621 return ts;663 return sc;
664}
665
666
667static TaggedString *str_checkname (LexState *ls) {
668 return tsvalue(&ls->fs->f->consts[checkname(ls)]);
622}669}
623 670
624 671
@@ -669,12 +716,9 @@ static int stat (LexState *ls) { · 44 unmodified lines
669 int line = ls->linenumber; /* may be needed for error messages */716 int line = ls->linenumber; /* may be needed for error messages */
670 FuncState *fs = ls->fs;717 FuncState *fs = ls->fs;
671 switch (ls->token) {718 switch (ls->token) {
672 case IF: { /* stat -> IF ifpart END */719 case IF: /* stat -> IF ifpart END */
673 next(ls);720 ifpart(ls, line);
674 ifpart(ls);
675 check_match(ls, END, IF, line);
676 return 1;721 return 1;
677 }
678 722
679 case WHILE: { /* stat -> WHILE cond DO block END */723 case WHILE: { /* stat -> WHILE cond DO block END */
680 TProtoFunc *f = fs->f;724 TProtoFunc *f = fs->f;
@@ -732,7 +776,8 @@ static int stat (LexState *ls) { · 51 unmodified lines
732 next(ls);776 next(ls);
733 nvars = localnamelist(ls);777 nvars = localnamelist(ls);
734 decinit(ls, &d);778 decinit(ls, &d);
735 ls->fs->nlocalvar += nvars;779 fs->nlocalvar += nvars;
780 correctvarlines(ls, nvars); /* vars will be alive only after decinit */
736 adjust_mult_assign(ls, nvars, &d);781 adjust_mult_assign(ls, nvars, &d);
737 return 1;782 return 1;
738 }783 }
@@ -746,8 +791,8 @@ static int stat (LexState *ls) { · 7 unmodified lines
746 luaX_error(ls, "syntax error");791 luaX_error(ls, "syntax error");
747 close_exp(ls, v.info, 0);792 close_exp(ls, v.info, 0);
748 }793 }
749 else {794 else { /* stat -> ['%'] NAME assignment */
750 int left = assignment(ls, &v, 1); /* stat -> ['%'] NAME assignment */795 int left = assignment(ls, &v, 1);
751 adjuststack(ls, left); /* remove eventual 'garbage' left on stack */796 adjuststack(ls, left); /* remove eventual 'garbage' left on stack */
752 }797 }
753 return 1;798 return 1;
@@ -758,7 +803,7 @@ static int stat (LexState *ls) { · 4 unmodified lines
758 return 0;803 return 0;
759 804
760 default:805 default:
761 luaX_error(ls, "<statement> expected");806 error_unexpected(ls);
762 return 0; /* to avoid warnings */807 return 0; /* to avoid warnings */
763 }808 }
764}809}
@@ -788,18 +833,18 @@ static void block (LexState *ls) { · 23 unmodified lines
788 chunk(ls);833 chunk(ls);
789 adjuststack(ls, fs->nlocalvar - nlocalvar);834 adjuststack(ls, fs->nlocalvar - nlocalvar);
790 for (; fs->nlocalvar > nlocalvar; fs->nlocalvar--)835 for (; fs->nlocalvar > nlocalvar; fs->nlocalvar--)
791 luaI_unregisterlocalvar(fs, ls->linenumber);836 luaI_unregisterlocalvar(fs, fs->lastsetline);
792}837}
793 838
794static int funcname (LexState *ls, vardesc *v) {839static int funcname (LexState *ls, vardesc *v) {
795 /* funcname -> NAME [':' NAME | '.' NAME] */840 /* funcname -> NAME [':' NAME | '.' NAME] */
796 int needself = 0;841 int needself = 0;
797 singlevar(ls, checkname(ls), v, 0);842 singlevar(ls, str_checkname(ls), v, 0);
798 if (ls->token == ':' || ls->token == '.') {843 if (ls->token == ':' || ls->token == '.') {
799 needself = (ls->token == ':');844 needself = (ls->token == ':');
800 next(ls);845 next(ls);
801 lua_pushvar(ls, v);846 lua_pushvar(ls, v);
802 code_string(ls, checkname(ls));847 code_constant(ls, checkname(ls));
803 v->k = VINDEXED;848 v->k = VINDEXED;
804 }849 }
805 return needself;850 return needself;
@@ -808,7 +853,7 @@ static int funcname (LexState *ls, vardesc *v) { · 2 unmodified lines
808static void body (LexState *ls, int needself, int line) {853static void body (LexState *ls, int needself, int line) {
809 /* body -> '(' parlist ')' chunk END */854 /* body -> '(' parlist ')' chunk END */
810 FuncState newfs;855 FuncState newfs;
811 init_state(ls, &newfs, ls->fs->f->fileName);856 init_state(ls, &newfs, ls->fs->f->source);
812 newfs.f->lineDefined = line;857 newfs.f->lineDefined = line;
813 check(ls, '(');858 check(ls, '(');
814 if (needself)859 if (needself)
@@ -821,36 +866,40 @@ static void body (LexState *ls, int needself, int line) { · 6 unmodified lines
821 func_onstack(ls, &newfs);866 func_onstack(ls, &newfs);
822}867}
823 868
824static void ifpart (LexState *ls) {869
870static void ifpart (LexState *ls, int line) {
825 /* ifpart -> cond THEN block [ELSE block | ELSEIF ifpart] */871 /* ifpart -> cond THEN block [ELSE block | ELSEIF ifpart] */
826 int c = cond(ls);872 int c;
827 int e;873 int e;
874 next(ls); /* skip IF or ELSEIF */
875 c = cond(ls);
828 check(ls, THEN);876 check(ls, THEN);
829 block(ls);877 block(ls);
830 e = SaveWord(ls);878 e = SaveWord(ls);
831 switch (ls->token) {879 if (ls->token == ELSEIF)
832 case ELSE:880 ifpart(ls, line);
833 next(ls);881 else {
882 if (optional(ls, ELSE))
834 block(ls);883 block(ls);
835 break;884 check_match(ls, END, IF, line);
836
837 case ELSEIF:
838 next(ls);
839 ifpart(ls);
840 break;
841 }885 }
842 codeIf(ls, c, e);886 codeIf(ls, c, e);
843}887}
844 888
889
845static void ret (LexState *ls) {890static void ret (LexState *ls) {
846 /* ret -> [RETURN explist sc] */891 /* ret -> [RETURN explist sc] */
847 if (ls->token == RETURN) {892 if (optional(ls, RETURN)) {
848 listdesc e;893 listdesc e;
849 check_debugline(ls);894 check_debugline(ls);
850 next(ls);895 explist(ls, &e);
851 explist(ls, &e);896 if (e.pc > 0) { /* expression is an open function call? */
852 close_exp(ls, e.pc, MULT_RET);897 Byte *code = ls->fs->f->code;
853 code_oparg(ls, RETCODE, 0, ls->fs->nlocalvar, 0);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);
854 ls->fs->stacksize = ls->fs->nlocalvar; /* removes all temp values */903 ls->fs->stacksize = ls->fs->nlocalvar; /* removes all temp values */
855 optional(ls, ';');904 optional(ls, ';');
856 }905 }
@@ -863,6 +912,9 @@ static void ret (LexState *ls) { · 6 unmodified lines
863** (EQ=2, NE=3, ... '^'=13). The unary NOT is 0 and UNMINUS is 1.912** (EQ=2, NE=3, ... '^'=13). The unary NOT is 0 and UNMINUS is 1.
864*/913*/
865 914
915#define INDNOT 0
916#define INDMINUS 1
917
866/* code of first binary operator */918/* code of first binary operator */
867#define FIRSTBIN 2919#define FIRSTBIN 2
868 920
@@ -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
879static OpCode opcodes [POW+1] = {NOTOP, MINUSOP, EQOP, NEQOP, GTOP, LTOP,931static OpCode opcodes [POW+1] = {NOTOP, MINUSOP, EQOP, NEQOP, GTOP, LTOP,
880 LEOP, GEOP, CONCOP, ADDOP, SUBOP, MULTOP, DIVOP, POWOP};932 LEOP, GEOP, CONCOP, ADDOP, SUBOP, MULTOP, DIVOP, POWOP};
881 933
882#define MAXOPS 20934#define MAXOPS 20 /* op's stack size (arbitrary limit) */
883 935
884typedef struct {936typedef struct stack_op {
885 int ops[MAXOPS];937 int ops[MAXOPS];
886 int top;938 int top;
887} stack_op;939} stack_op;
@@ -892,39 +944,33 @@ static void exp1 (LexState *ls) { · 4 unmodified lines
892 exp0(ls, &v);944 exp0(ls, &v);
893 lua_pushvar(ls, &v);945 lua_pushvar(ls, &v);
894 if (is_in(ls->token, expfollow) < 0)946 if (is_in(ls->token, expfollow) < 0)
895 luaX_error(ls, "ill formed expression");947 luaX_error(ls, "ill-formed expression");
896}948}
897 949
898 950
899static void exp0 (LexState *ls, vardesc *v) {951static void exp0 (LexState *ls, vardesc *v) {
952 /* exp0 -> exp2 {(AND | OR) exp2} */
900 exp2(ls, v);953 exp2(ls, v);
901 while (ls->token == AND || ls->token == OR) {954 while (ls->token == AND || ls->token == OR) {
902 int is_and = (ls->token == AND);955 int op = (ls->token == AND) ? ONFJMP : ONTJMP;
903 int pc;956 int pc;
904 lua_pushvar(ls, v);957 lua_pushvar(ls, v);
905 next(ls);958 next(ls);
906 pc = SaveWordPop(ls);959 pc = SaveWordPop(ls);
907 exp2(ls, v);960 exp2(ls, v);
908 lua_pushvar(ls, v);961 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);
910 }963 }
911}964}
912 965
913 966
914static void push (LexState *ls, stack_op *s, int op) {967static void push (LexState *ls, stack_op *s, int op) {
915 if (s->top == MAXOPS)968 if (s->top >= MAXOPS)
916 luaX_error(ls, "expression too complex");969 luaX_error(ls, "expression too complex");
917 s->ops[s->top++] = op;970 s->ops[s->top++] = op;
918}971}
919 972
920 973
921static 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
928static void pop_to (LexState *ls, stack_op *s, int prio) {974static void pop_to (LexState *ls, stack_op *s, int prio) {
929 int op;975 int op;
930 while (s->top > 0 && priority[(op=s->ops[s->top-1])] >= prio) {976 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
933 }979 }
934}980}
935 981
936static void exp2 (LexState *ls, vardesc *v) {982static void simpleexp (LexState *ls, vardesc *v, stack_op *s) {
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
960static void simpleexp (LexState *ls, vardesc *v) {
961 check_debugline(ls);983 check_debugline(ls);
962 switch (ls->token) {984 switch (ls->token) {
963 case '(': /* simpleexp -> '(' exp0 ')' */985 case NUMBER: { /* simpleexp -> NUMBER */
964 next(ls);986 real r = ls->seminfo.r;
965 exp0(ls, v);
966 check(ls, ')');
967 break;
968
969 case NUMBER: /* simpleexp -> NUMBER */
970 code_number(ls, ls->seminfo.r);
971 next(ls);987 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);
973 break;995 break;
996 }
974 997
975 case STRING: /* simpleexp -> STRING */998 case STRING: /* simpleexp -> STRING */
976 code_string(ls, ls->seminfo.ts);999 code_string(ls, ls->seminfo.ts); /* must use 'seminfo' before "next" */
977 next(ls);1000 next(ls);
978 v->k = VEXP; v->info = 0;
979 break;1001 break;
980 1002
981 case NIL: /* simpleexp -> NIL */1003 case NIL: /* simpleexp -> NIL */
982 adjuststack(ls, -1);1004 adjuststack(ls, -1);
983 next(ls);1005 next(ls);
984 v->k = VEXP; v->info = 0;
985 break;1006 break;
986 1007
987 case '{': /* simpleexp -> constructor */1008 case '{': /* simpleexp -> constructor */
988 constructor(ls);1009 constructor(ls);
989 v->k = VEXP; v->info = 0;
990 break;1010 break;
991 1011
992 case FUNCTION: { /* simpleexp -> FUNCTION body */1012 case FUNCTION: /* simpleexp -> FUNCTION body */
993 int line = ls->linenumber;
994 next(ls);1013 next(ls);
995 body(ls, 0, line);1014 body(ls, 0, ls->linenumber);
996 v->k = VEXP; v->info = 0;
997 break;1015 break;
998 }1016
1017 case '(': /* simpleexp -> '(' exp0 ')' */
1018 next(ls);
1019 exp0(ls, v);
1020 check(ls, ')');
1021 return;
999 1022
1000 case NAME: case '%':1023 case NAME: case '%':
1001 var_or_func(ls, v);1024 var_or_func(ls, v);
1002 break;1025 return;
1003 1026
1004 default:1027 default:
1005 luaX_error(ls, "<expression> expected");1028 luaX_error(ls, "<expression> expected");
1006 break;1029 return;
1030 }
1031 v->k = VEXP; v->info = 0;
1032}
1033
1034
1035static 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
1045static 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);
1007 }1063 }
1008}1064}
1009 1065
1066
1010static void var_or_func (LexState *ls, vardesc *v) {1067static void var_or_func (LexState *ls, vardesc *v) {
1011 /* var_or_func -> ['%'] NAME var_or_func_tail */1068 /* var_or_func -> ['%'] NAME var_or_func_tail */
1012 if (optional(ls, '%')) { /* upvalue? */1069 if (optional(ls, '%')) { /* upvalue? */
1013 pushupvalue(ls, checkname(ls));1070 pushupvalue(ls, str_checkname(ls));
1014 v->k = VEXP;1071 v->k = VEXP;
1015 v->info = 0; /* closed expression */1072 v->info = 0; /* closed expression */
1016 }1073 }
1017 else /* variable name */1074 else /* variable name */
1018 singlevar(ls, checkname(ls), v, 0);1075 singlevar(ls, str_checkname(ls), v, 0);
1019 var_or_func_tail(ls, v);1076 var_or_func_tail(ls, v);
1020}1077}
1021 1078
1079
1022static void var_or_func_tail (LexState *ls, vardesc *v) {1080static void var_or_func_tail (LexState *ls, vardesc *v) {
1023 for (;;) {1081 for (;;) {
1024 switch (ls->token) {1082 switch (ls->token) {
@@ -1026,7 +1084,7 @@ static void var_or_func_tail (LexState *ls, vardesc *v) { · 1 unmodified line
1026 next(ls);1084 next(ls);
1027 lua_pushvar(ls, v); /* 'v' must be on stack */1085 lua_pushvar(ls, v); /* 'v' must be on stack */
1028 v->k = VDOT;1086 v->k = VDOT;
1029 v->info = string_constant(ls->fs, checkname(ls));1087 v->info = checkname(ls);
1030 break;1088 break;
1031 1089
1032 case '[': /* var_or_func_tail -> '[' exp1 ']' */1090 case '[': /* var_or_func_tail -> '[' exp1 ']' */
@@ -1040,7 +1098,7 @@ static void var_or_func_tail (LexState *ls, vardesc *v) { · 7 unmodified lines
1040 case ':': /* var_or_func_tail -> ':' NAME funcparams */1098 case ':': /* var_or_func_tail -> ':' NAME funcparams */
1041 next(ls);1099 next(ls);
1042 lua_pushvar(ls, v); /* 'v' must be on stack */1100 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);
1044 v->k = VEXP;1102 v->k = VEXP;
1045 v->info = funcparams(ls, 1);1103 v->info = funcparams(ls, 1);
1046 break;1104 break;
@@ -1058,13 +1116,14 @@ static void var_or_func_tail (LexState *ls, vardesc *v) { · 11 unmodified lines
1058 1116
1059static int funcparams (LexState *ls, int slf) {1117static int funcparams (LexState *ls, int slf) {
1060 FuncState *fs = ls->fs;1118 FuncState *fs = ls->fs;
1061 int nparams = 1; /* default value */1119 int nparams = 1; /* in cases STRING and constructor */
1062 switch (ls->token) {1120 switch (ls->token) {
1063 case '(': { /* funcparams -> '(' explist ')' */1121 case '(': { /* funcparams -> '(' explist ')' */
1122 int line = ls->linenumber;
1064 listdesc e;1123 listdesc e;
1065 next(ls);1124 next(ls);
1066 explist(ls, &e);1125 explist(ls, &e);
1067 check(ls, ')');1126 check_match(ls, ')', '(', line);
1068 close_exp(ls, e.pc, 1);1127 close_exp(ls, e.pc, 1);
1069 nparams = e.n;1128 nparams = e.n;
1070 break;1129 break;
@@ -1075,7 +1134,7 @@ static int funcparams (LexState *ls, int slf) { · 4 unmodified lines
1075 break;1134 break;
1076 1135
1077 case STRING: /* funcparams -> STRING */1136 case STRING: /* funcparams -> STRING */
1078 code_string(ls, ls->seminfo.ts);1137 code_string(ls, ls->seminfo.ts); /* must use 'seminfo' before "next" */
1079 next(ls);1138 next(ls);
1080 break;1139 break;
1081 1140
@@ -1083,9 +1142,9 @@ static int funcparams (LexState *ls, int slf) { · 1 unmodified line
1083 luaX_error(ls, "function arguments expected");1142 luaX_error(ls, "function arguments expected");
1084 break;1143 break;
1085 }1144 }
1086 code_byte(fs, 0); /* save space for opcode */1145 code_byte(fs, CALL);
1087 code_byte(fs, 0); /* and nresult */1146 code_byte(fs, 0); /* save space for nresult */
1088 code_byte(fs, nparams+slf);1147 code_byte(fs, (Byte)(nparams+slf));
1089 return fs->pc-1;1148 return fs->pc-1;
1090}1149}
1091 1150
@@ -1131,7 +1190,7 @@ static void parlist (LexState *ls) { · 39 unmodified lines
1131 1190
1132 case NAME: /* parlist, tailparlist -> NAME [',' tailparlist] */1191 case NAME: /* parlist, tailparlist -> NAME [',' tailparlist] */
1133 init:1192 init:
1134 store_localvar(ls, checkname(ls), nparams++);1193 store_localvar(ls, str_checkname(ls), nparams++);
1135 if (ls->token == ',') {1194 if (ls->token == ',') {
1136 next(ls);1195 next(ls);
1137 switch (ls->token) {1196 switch (ls->token) {
@@ -1158,10 +1217,10 @@ static void parlist (LexState *ls) { · 20 unmodified lines
1158static int localnamelist (LexState *ls) {1217static int localnamelist (LexState *ls) {
1159 /* localnamelist -> NAME {',' NAME} */1218 /* localnamelist -> NAME {',' NAME} */
1160 int i = 1;1219 int i = 1;
1161 store_localvar(ls, checkname(ls), 0);1220 store_localvar(ls, str_checkname(ls), 0);
1162 while (ls->token == ',') {1221 while (ls->token == ',') {
1163 next(ls);1222 next(ls);
1164 store_localvar(ls, checkname(ls), i++);1223 store_localvar(ls, str_checkname(ls), i++);
1165 }1224 }
1166 return i;1225 return i;
1167}1226}
@@ -1178,13 +1237,11 @@ static void decinit (LexState *ls, listdesc *d) { · 10 unmodified lines
1178 }1237 }
1179}1238}
1180 1239
1240
1181static int assignment (LexState *ls, vardesc *v, int nvars) {1241static int assignment (LexState *ls, vardesc *v, int nvars) {
1182 int left = 0;1242 int left = 0;
1183 /* dotted variables <a.x> must be stored like regular indexed vars <a["x"]> */1243 checklimit(ls, nvars, MAXVARSLH, "variables in a multiple assignment");
1184 if (v->k == VDOT) {1244 unloaddot(ls, v);
1185 code_constant(ls, v->info);
1186 v->k = VINDEXED;
1187 }
1188 if (ls->token == ',') { /* assignment -> ',' NAME assignment */1245 if (ls->token == ',') { /* assignment -> ',' NAME assignment */
1189 vardesc nv;1246 vardesc nv;
1190 next(ls);1247 next(ls);
@@ -1204,12 +1261,13 @@ static int assignment (LexState *ls, vardesc *v, int nvars) { · 13 unmodified lines
1204 storevar(ls, v);1261 storevar(ls, v);
1205 }1262 }
1206 else { /* indexed var with values in between*/1263 else { /* indexed var with values in between*/
1207 code_oparg(ls, SETTABLE, 0, left+(nvars-1), -1);1264 code_oparg(ls, SETTABLE, left+(nvars-1), -1);
1208 left += 2; /* table/index are not popped, because they aren't on top */1265 left += 2; /* table&index are not popped, because they aren't on top */
1209 }1266 }
1210 return left;1267 return left;
1211}1268}
1212 1269
1270
1213static void constructor (LexState *ls) {1271static void constructor (LexState *ls) {
1214 /* constructor -> '{' part [';' part] '}' */1272 /* constructor -> '{' part [';' part] '}' */
1215 int line = ls->linenumber;1273 int line = ls->linenumber;
@@ -1229,7 +1287,7 @@ static void constructor (LexState *ls) { · 13 unmodified lines
1229 nelems += other_cd.n;1287 nelems += other_cd.n;
1230 }1288 }
1231 check_match(ls, '}', '{', line);1289 check_match(ls, '}', '{', line);
1232 fix_opcode(ls, pc, CREATEARRAY, 2, nelems);1290 fix_opcode(ls, pc, CREATEARRAY, nelems);
1233}1291}
1234 1292
1235static void part (LexState *ls, constdesc *cd) {1293static void part (LexState *ls, constdesc *cd) {
@@ -1251,7 +1309,7 @@ static void part (LexState *ls, constdesc *cd) { · 15 unmodified lines
1251 code_string(ls, ls->fs->localvar[v.info]);1309 code_string(ls, ls->fs->localvar[v.info]);
1252 break;1310 break;
1253 default:1311 default:
1254 luaX_error(ls, "`=' unexpected");1312 error_unexpected(ls);
1255 }1313 }
1256 next(ls);1314 next(ls);
1257 exp1(ls);1315 exp1(ls);
@@ -1316,7 +1374,7 @@ static void recfield (LexState *ls) { · 58 unmodified lines
1316 /* recfield -> (NAME | '['exp1']') = exp1 */1374 /* recfield -> (NAME | '['exp1']') = exp1 */
1317 switch (ls->token) {1375 switch (ls->token) {
1318 case NAME:1376 case NAME:
1319 code_string(ls, checkname(ls));1377 code_constant(ls, checkname(ls));
1320 break;1378 break;
1321 1379
1322 case '[':1380 case '[':
src/lparser.h+2−2
@@ -1,6 +1,6 @@
1/*1/*
2** $Id: lparser.h,v 1.2 1997/12/22 20:57:18 roberto Exp $2** $Id: lparser.h,v 1.3 1999/02/25 19:13:56 roberto Exp $
3** Syntax analizer and code generator3** LL(1) Parser and code generator for Lua
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
6 6
src/lstate.c+12−12
@@ -1,5 +1,5 @@
1/*1/*
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 $
3** Global State3** Global State
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -24,11 +24,19 @@ void lua_open (void) · 18 unmodified lines
24{24{
25 if (lua_state) return;25 if (lua_state) return;
26 lua_state = luaM_new(lua_State);26 lua_state = luaM_new(lua_State);
27 L->numCblocks = 0;
28 L->Cstack.base = 0;27 L->Cstack.base = 0;
29 L->Cstack.lua2C = 0;28 L->Cstack.lua2C = 0;
30 L->Cstack.num = 0;29 L->Cstack.num = 0;
31 L->errorJmp = NULL;30 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;
32 L->rootproto.next = NULL;40 L->rootproto.next = NULL;
33 L->rootproto.marked = 0;41 L->rootproto.marked = 0;
34 L->rootcl.next = NULL;42 L->rootcl.next = NULL;
@@ -37,12 +45,9 @@ void lua_open (void) · 2 unmodified lines
37 L->rootglobal.marked = 0;45 L->rootglobal.marked = 0;
38 L->roottable.next = NULL;46 L->roottable.next = NULL;
39 L->roottable.marked = 0;47 L->roottable.marked = 0;
48 L->IMtable = NULL;
40 L->refArray = NULL;49 L->refArray = NULL;
41 L->refSize = 0;50 L->refSize = 0;
42 L->Mbuffsize = 0;
43 L->Mbuffnext = 0;
44 L->Mbuffbase = NULL;
45 L->Mbuffer = NULL;
46 L->GCthreshold = GARBAGE_BLOCK;51 L->GCthreshold = GARBAGE_BLOCK;
47 L->nblocks = 0;52 L->nblocks = 0;
48 luaD_init();53 luaD_init();
@@ -69,6 +74,7 @@ void lua_close (void) · 20 unmodified lines
69 luaM_free(L->IMtable);74 luaM_free(L->IMtable);
70 luaM_free(L->refArray);75 luaM_free(L->refArray);
71 luaM_free(L->Mbuffer);76 luaM_free(L->Mbuffer);
77 luaM_free(L->Cblocks);
72 luaM_free(L);78 luaM_free(L);
73 L = NULL;79 L = NULL;
74#ifdef DEBUG80#ifdef DEBUG
@@ -78,9 +84,3 @@ void lua_close (void) · 3 unmodified lines
78}84}
79 85
80 86
81lua_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 @@
1/*1/*
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 $
3** Global State3** Global State
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -11,15 +11,24 @@ · 5 unmodified lines
11 11
12#include "lobject.h"12#include "lobject.h"
13#include "lua.h"13#include "lua.h"
14#include "luadebug.h"
14 15
15 16
16#define MAX_C_BLOCKS 10
17
18#define GARBAGE_BLOCK 15017#define GARBAGE_BLOCK 150
19 18
20 19
21typedef int StkId; /* index to stack elements */20typedef int StkId; /* index to stack elements */
22 21
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*/
27struct lua_longjmp {
28 jmp_buf b;
29};
30
31
23struct Stack {32struct Stack {
24 TObject *top;33 TObject *top;
25 TObject *stack;34 TObject *stack;
@@ -34,7 +43,7 @@ struct C_Lua_Stack { · 8 unmodified lines
34};43};
35 44
36 45
37typedef struct {46typedef struct stringtable {
38 int size;47 int size;
39 int nuse; /* number of elements (including EMPTYs) */48 int nuse; /* number of elements (including EMPTYs) */
40 TaggedString **hash;49 TaggedString **hash;
@@ -53,22 +62,23 @@ struct lua_State { · 12 unmodified lines
53 /* thread-specific state */62 /* thread-specific state */
54 struct Stack stack; /* Lua stack */63 struct Stack stack; /* Lua stack */
55 struct C_Lua_Stack Cstack; /* C2lua struct */64 struct C_Lua_Stack Cstack; /* C2lua struct */
56 jmp_buf *errorJmp; /* current error recover point */65 struct lua_longjmp *errorJmp; /* current error recover point */
57 char *Mbuffer; /* global buffer */66 char *Mbuffer; /* global buffer */
58 char *Mbuffbase; /* current first position of Mbuffer */67 int Mbuffbase; /* current first position of Mbuffer */
59 int Mbuffsize; /* size of Mbuffer */68 int Mbuffsize; /* size of Mbuffer */
60 int Mbuffnext; /* next position to fill in Mbuffer */69 int Mbuffnext; /* next position to fill in Mbuffer */
61 struct C_Lua_Stack Cblocks[MAX_C_BLOCKS];70 struct C_Lua_Stack *Cblocks;
62 int numCblocks; /* number of nested Cblocks */71 int numCblocks; /* number of nested Cblocks */
72 int debug;
73 lua_CHFunction callhook;
74 lua_LHFunction linehook;
63 /* global state */75 /* global state */
64 TObject errorim; /* error tag method */
65 GCnode rootproto; /* list of all prototypes */76 GCnode rootproto; /* list of all prototypes */
66 GCnode rootcl; /* list of all closures */77 GCnode rootcl; /* list of all closures */
67 GCnode roottable; /* list of all tables */78 GCnode roottable; /* list of all tables */
68 GCnode rootglobal; /* list of strings with global values */79 GCnode rootglobal; /* list of strings with global values */
69 stringtable *string_root; /* array of hash tables for strings and udata */80 stringtable *string_root; /* array of hash tables for strings and udata */
70 struct IM *IMtable; /* table for tag methods */81 struct IM *IMtable; /* table for tag methods */
71 int IMtable_size; /* size of IMtable */
72 int last_tag; /* last used tag in IMtable */82 int last_tag; /* last used tag in IMtable */
73 struct ref *refArray; /* locked objects */83 struct ref *refArray; /* locked objects */
74 int refSize; /* size of refArray */84 int refSize; /* size of refArray */
@@ -77,10 +87,8 @@ struct lua_State { · 2 unmodified lines
77};87};
78 88
79 89
80extern lua_State *lua_state;
81
82
83#define L lua_state90#define L lua_state
84 91
85 92
86#endif93#endif
94
src/lstring.c+62−77
@@ -1,5 +1,5 @@
1/*1/*
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 $
3** String table (keeps all strings handled by Lua)3** String table (keeps all strings handled by Lua)
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -14,7 +14,9 @@ · 8 unmodified lines
14#include "lua.h"14#include "lua.h"
15 15
16 16
17#define NUM_HASHS 6117#define NUM_HASHSTR 31
18#define NUM_HASHUDATA 31
19#define NUM_HASHS (NUM_HASHSTR+NUM_HASHUDATA)
18 20
19 21
20#define gcsizestring(l) (1+(l/64)) /* "weight" for a string with length 'l' */22#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
25 {{{LUA_T_NIL, {NULL}}, 0L}}, {0}};27 {{{LUA_T_NIL, {NULL}}, 0L}}, {0}};
26 28
27 29
28void luaS_init (void)30void luaS_init (void) {
29{
30 int i;31 int i;
31 L->string_root = luaM_newvector(NUM_HASHS, stringtable);32 L->string_root = luaM_newvector(NUM_HASHS, stringtable);
32 for (i=0; i<NUM_HASHS; i++) {33 for (i=0; i<NUM_HASHS; i++) {
@@ -37,16 +38,14 @@ void luaS_init (void) · 4 unmodified lines
37}38}
38 39
39 40
40static unsigned long hash_s (char *s, long l)41static unsigned long hash_s (char *s, long l) {
41{42 unsigned long h = 0; /* seed */
42 unsigned long h = 0;
43 while (l--)43 while (l--)
44 h = ((h<<5)-h)^(unsigned char)*(s++);44 h = h ^ ((h<<5)+(h>>2)+(unsigned char)*(s++));
45 return h;45 return h;
46}46}
47 47
48static int newsize (stringtable *tb)48static int newsize (stringtable *tb) {
49{
50 int size = tb->size;49 int size = tb->size;
51 int realuse = 0;50 int realuse = 0;
52 int i;51 int i;
@@ -54,16 +53,11 @@ static int newsize (stringtable *tb) · 1 unmodified line
54 for (i=0; i<size; i++)53 for (i=0; i<size; i++)
55 if (tb->hash[i] != NULL && tb->hash[i] != &EMPTY)54 if (tb->hash[i] != NULL && tb->hash[i] != &EMPTY)
56 realuse++;55 realuse++;
57 if (2*(realuse+1) <= size) /* +1 is the new element */56 return luaO_redimension((realuse+1)*2); /* +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);
61}57}
62 58
63 59
64static void grow (stringtable *tb)60static void grow (stringtable *tb) {
65{
66
67 int ns = newsize(tb);61 int ns = newsize(tb);
68 TaggedString **newhash = luaM_newvector(ns, TaggedString *);62 TaggedString **newhash = luaM_newvector(ns, TaggedString *);
69 int i;63 int i;
@@ -73,10 +67,13 @@ static void grow (stringtable *tb) · 3 unmodified lines
73 tb->nuse = 0;67 tb->nuse = 0;
74 for (i=0; i<tb->size; i++) {68 for (i=0; i<tb->size; i++) {
75 if (tb->hash[i] != NULL && tb->hash[i] != &EMPTY) {69 if (tb->hash[i] != NULL && tb->hash[i] != &EMPTY) {
76 int h = tb->hash[i]->hash%ns;70 unsigned long h = tb->hash[i]->hash;
77 while (newhash[h])71 int h1 = h%ns;
78 h = (h+1)%ns;72 while (newhash[h1]) {
79 newhash[h] = tb->hash[i];73 h1 += (h&(ns-2)) + 1; /* double hashing */
74 if (h1 >= ns) h1 -= ns;
75 }
76 newhash[h1] = tb->hash[i];
80 tb->nuse++;77 tb->nuse++;
81 }78 }
82 }79 }
@@ -86,8 +83,7 @@ static void grow (stringtable *tb) · 3 unmodified lines
86}83}
87 84
88 85
89static TaggedString *newone_s (char *str, long l, unsigned long h)86static TaggedString *newone_s (char *str, long l, unsigned long h) {
90{
91 TaggedString *ts = (TaggedString *)luaM_malloc(sizeof(TaggedString)+l);87 TaggedString *ts = (TaggedString *)luaM_malloc(sizeof(TaggedString)+l);
92 memcpy(ts->str, str, l);88 memcpy(ts->str, str, l);
93 ts->str[l] = 0; /* ending 0 */89 ts->str[l] = 0; /* ending 0 */
@@ -101,8 +97,7 @@ static TaggedString *newone_s (char *str, long l, unsigned long h) · 7 unmodified lines
101 return ts;97 return ts;
102}98}
103 99
104static TaggedString *newone_u (char *buff, int tag, unsigned long h)100static TaggedString *newone_u (char *buff, int tag, unsigned long h) {
105{
106 TaggedString *ts = luaM_new(TaggedString);101 TaggedString *ts = luaM_new(TaggedString);
107 ts->u.d.v = buff;102 ts->u.d.v = buff;
108 ts->u.d.tag = (tag == LUA_ANYTAG) ? 0 : tag;103 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
114 return ts;109 return ts;
115}110}
116 111
117static TaggedString *insert_s (char *str, long l, stringtable *tb)112static TaggedString *insert_s (char *str, long l, stringtable *tb) {
118{
119 TaggedString *ts;113 TaggedString *ts;
120 unsigned long h = hash_s(str, l);114 unsigned long h = hash_s(str, l);
121 int size = tb->size;115 int size = tb->size;
122 int i;
123 int j = -1;116 int j = -1;
117 int h1;
124 if ((long)tb->nuse*3 >= (long)size*2) {118 if ((long)tb->nuse*3 >= (long)size*2) {
125 grow(tb);119 grow(tb);
126 size = tb->size;120 size = tb->size;
127 }121 }
128 for (i = h%size; (ts = tb->hash[i]) != NULL; ) {122 h1 = h%size;
123 while ((ts = tb->hash[h1]) != NULL) {
129 if (ts == &EMPTY)124 if (ts == &EMPTY)
130 j = i;125 j = h1;
131 else if (ts->constindex >= 0 &&126 else if (ts->u.s.len == l && (memcmp(str, ts->str, l) == 0))
132 ts->u.s.len == l &&
133 (memcmp(str, ts->str, l) == 0))
134 return ts;127 return ts;
135 if (++i == size) i=0;128 h1 += (h&(size-2)) + 1; /* double hashing */
129 if (h1 >= size) h1 -= size;
136 }130 }
137 /* not found */131 /* not found */
138 if (j != -1) /* is there an EMPTY space? */132 if (j != -1) /* is there an EMPTY space? */
139 i = j;133 h1 = j;
140 else134 else
141 tb->nuse++;135 tb->nuse++;
142 ts = tb->hash[i] = newone_s(str, l, h);136 ts = tb->hash[h1] = newone_s(str, l, h);
143 return ts;137 return ts;
144}138}
145 139
146static TaggedString *insert_u (void *buff, int tag, stringtable *tb)140
147{141static TaggedString *insert_u (void *buff, int tag, stringtable *tb) {
148 TaggedString *ts;142 TaggedString *ts;
149 unsigned long h = (unsigned long)buff;143 unsigned long h = (unsigned long)buff;
150 int size = tb->size;144 int size = tb->size;
151 int i;
152 int j = -1;145 int j = -1;
146 int h1;
153 if ((long)tb->nuse*3 >= (long)size*2) {147 if ((long)tb->nuse*3 >= (long)size*2) {
154 grow(tb);148 grow(tb);
155 size = tb->size;149 size = tb->size;
156 }150 }
157 for (i = h%size; (ts = tb->hash[i]) != NULL; ) {151 h1 = h%size;
152 while ((ts = tb->hash[h1]) != NULL) {
158 if (ts == &EMPTY)153 if (ts == &EMPTY)
159 j = i;154 j = h1;
160 else if (ts->constindex < 0 && /* is a udata? */155 else if ((tag == ts->u.d.tag || tag == LUA_ANYTAG) && buff == ts->u.d.v)
161 (tag == ts->u.d.tag || tag == LUA_ANYTAG) &&
162 buff == ts->u.d.v)
163 return ts;156 return ts;
164 if (++i == size) i=0;157 h1 += (h&(size-2)) + 1; /* double hashing */
158 if (h1 >= size) h1 -= size;
165 }159 }
166 /* not found */160 /* not found */
167 if (j != -1) /* is there an EMPTY space? */161 if (j != -1) /* is there an EMPTY space? */
168 i = j;162 h1 = j;
169 else163 else
170 tb->nuse++;164 tb->nuse++;
171 ts = tb->hash[i] = newone_u(buff, tag, h);165 ts = tb->hash[h1] = newone_u(buff, tag, h);
172 return ts;166 return ts;
173}167}
174 168
175TaggedString *luaS_createudata (void *udata, int tag)169
176{170TaggedString *luaS_createudata (void *udata, int tag) {
177 return insert_u(udata, tag, &L->string_root[(unsigned)udata%NUM_HASHS]);171 int t = ((unsigned)udata%NUM_HASHUDATA)+NUM_HASHSTR;
172 return insert_u(udata, tag, &L->string_root[t]);
178}173}
179 174
180TaggedString *luaS_newlstr (char *str, long l)175TaggedString *luaS_newlstr (char *str, long l) {
181{176 int t = (l==0) ? 0 : ((int)((unsigned char)str[0]*l))%NUM_HASHSTR;
182 int i = (l==0)?0:(unsigned char)str[0];177 return insert_s(str, l, &L->string_root[t]);
183 return insert_s(str, l, &L->string_root[i%NUM_HASHS]);
184}178}
185 179
186TaggedString *luaS_new (char *str)180TaggedString *luaS_new (char *str) {
187{
188 return luaS_newlstr(str, strlen(str));181 return luaS_newlstr(str, strlen(str));
189}182}
190 183
191TaggedString *luaS_newfixedstring (char *str)184TaggedString *luaS_newfixedstring (char *str) {
192{
193 TaggedString *ts = luaS_new(str);185 TaggedString *ts = luaS_new(str);
194 if (ts->head.marked == 0)186 if (ts->head.marked == 0)
195 ts->head.marked = 2; /* avoid GC */187 ts->head.marked = 2; /* avoid GC */
@@ -197,8 +189,7 @@ TaggedString *luaS_newfixedstring (char *str) · 1 unmodified line
197}189}
198 190
199 191
200void luaS_free (TaggedString *l)192void luaS_free (TaggedString *l) {
201{
202 while (l) {193 while (l) {
203 TaggedString *next = (TaggedString *)l->head.next;194 TaggedString *next = (TaggedString *)l->head.next;
204 L->nblocks -= (l->constindex == -1) ? 1 : gcsizestring(l->u.s.len);195 L->nblocks -= (l->constindex == -1) ? 1 : gcsizestring(l->u.s.len);
@@ -212,8 +203,7 @@ void luaS_free (TaggedString *l) · 7 unmodified lines
212** Garbage collection functions.203** Garbage collection functions.
213*/204*/
214 205
215static void remove_from_list (GCnode *l)206static void remove_from_list (GCnode *l) {
216{
217 while (l) {207 while (l) {
218 GCnode *next = l->next;208 GCnode *next = l->next;
219 while (next && !next->marked)209 while (next && !next->marked)
@@ -223,8 +213,7 @@ static void remove_from_list (GCnode *l) · 3 unmodified lines
223}213}
224 214
225 215
226TaggedString *luaS_collector (void)216TaggedString *luaS_collector (void) {
227{
228 TaggedString *frees = NULL;217 TaggedString *frees = NULL;
229 int i;218 int i;
230 remove_from_list(&(L->rootglobal));219 remove_from_list(&(L->rootglobal));
@@ -247,18 +236,18 @@ TaggedString *luaS_collector (void) · 16 unmodified lines
247}236}
248 237
249 238
250TaggedString *luaS_collectudata (void)239TaggedString *luaS_collectudata (void) {
251{
252 TaggedString *frees = NULL;240 TaggedString *frees = NULL;
253 int i;241 int i;
254 L->rootglobal.next = NULL; /* empty list of globals */242 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++) {
256 stringtable *tb = &L->string_root[i];244 stringtable *tb = &L->string_root[i];
257 int j;245 int j;
258 for (j=0; j<tb->size; j++) {246 for (j=0; j<tb->size; j++) {
259 TaggedString *t = tb->hash[j];247 TaggedString *t = tb->hash[j];
260 if (t == NULL || t == &EMPTY || t->constindex != -1)248 if (t == NULL || t == &EMPTY)
261 continue; /* get only user data */249 continue;
250 LUA_ASSERT(t->constindex == -1, "must be userdata");
262 t->head.next = (GCnode *)frees;251 t->head.next = (GCnode *)frees;
263 frees = t;252 frees = t;
264 tb->hash[j] = &EMPTY;253 tb->hash[j] = &EMPTY;
@@ -268,8 +257,7 @@ TaggedString *luaS_collectudata (void) · 3 unmodified lines
268}257}
269 258
270 259
271void luaS_freeall (void)260void luaS_freeall (void) {
272{
273 int i;261 int i;
274 for (i=0; i<NUM_HASHS; i++) {262 for (i=0; i<NUM_HASHS; i++) {
275 stringtable *tb = &L->string_root[i];263 stringtable *tb = &L->string_root[i];
@@ -285,8 +273,7 @@ void luaS_freeall (void) · 9 unmodified lines
285}273}
286 274
287 275
288void luaS_rawsetglobal (TaggedString *ts, TObject *newval)276void luaS_rawsetglobal (TaggedString *ts, TObject *newval) {
289{
290 ts->u.s.globalval = *newval;277 ts->u.s.globalval = *newval;
291 if (ts->head.next == (GCnode *)ts) { /* is not in list? */278 if (ts->head.next == (GCnode *)ts) { /* is not in list? */
292 ts->head.next = L->rootglobal.next;279 ts->head.next = L->rootglobal.next;
@@ -295,8 +282,7 @@ void luaS_rawsetglobal (TaggedString *ts, TObject *newval) · 2 unmodified lines
295}282}
296 283
297 284
298char *luaS_travsymbol (int (*fn)(TObject *))285char *luaS_travsymbol (int (*fn)(TObject *)) {
299{
300 TaggedString *g;286 TaggedString *g;
301 for (g=(TaggedString *)L->rootglobal.next; g; g=(TaggedString *)g->head.next)287 for (g=(TaggedString *)L->rootglobal.next; g; g=(TaggedString *)g->head.next)
302 if (fn(&g->u.s.globalval))288 if (fn(&g->u.s.globalval))
@@ -305,8 +291,7 @@ char *luaS_travsymbol (int (*fn)(TObject *)) · 2 unmodified lines
305}291}
306 292
307 293
308int luaS_globaldefined (char *name)294int luaS_globaldefined (char *name) {
309{
310 TaggedString *ts = luaS_new(name);295 TaggedString *ts = luaS_new(name);
311 return ts->u.s.globalval.ttype != LUA_T_NIL;296 return ts->u.s.globalval.ttype != LUA_T_NIL;
312}297}
src/ltable.c+65−104
@@ -1,5 +1,5 @@
1/*1/*
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 $
3** Lua tables (hash)3** Lua tables (hash)
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -20,14 +20,11 @@ · 14 unmodified lines
20#define nodevector(t) ((t)->node)20#define nodevector(t) ((t)->node)
21 21
22 22
23#define REHASH_LIMIT 0.70 /* avoid more than this % full */
24
25#define TagDefault LUA_T_ARRAY;23#define TagDefault LUA_T_ARRAY;
26 24
27 25
28 26
29static long int hashindex (TObject *ref)27static long int hashindex (TObject *ref) {
30{
31 long int h;28 long int h;
32 switch (ttype(ref)) {29 switch (ttype(ref)) {
33 case LUA_T_NUMBER:30 case LUA_T_NUMBER:
@@ -56,61 +53,45 @@ static long int hashindex (TObject *ref) · 22 unmodified lines
56}53}
57 54
58 55
59static int present (Hash *t, TObject *key)56Node *luaH_present (Hash *t, TObject *key) {
60{
61 int tsize = nhash(t);57 int tsize = nhash(t);
62 long int h = hashindex(key);58 long int h = hashindex(key);
63 int h1 = h%tsize;59 int h1 = h%tsize;
64 TObject *rf = ref(node(t, h1));60 Node *n = node(t, h1);
65 if (ttype(rf) != LUA_T_NIL && !luaO_equalObj(key, rf)) {61 /* keep looking until an entry with "ref" equal to key or nil */
66 int h2 = h%(tsize-2) + 1;62 while ((ttype(ref(n)) == ttype(key)) ? !luaO_equalval(key, ref(n))
67 do {63 : ttype(ref(n)) != LUA_T_NIL) {
68 h1 += h2;64 h1 += (h&(tsize-2)) + 1; /* double hashing */
69 if (h1 >= tsize) h1 -= tsize;65 if (h1 >= tsize) h1 -= tsize;
70 rf = ref(node(t, h1));66 n = node(t, h1);
71 } while (ttype(rf) != LUA_T_NIL && !luaO_equalObj(key, rf));
72 }67 }
73 return h1;68 return n;
74}69}
75 70
76 71
77/*72void luaH_free (Hash *frees) {
78** Alloc a vector node
79*/
80static 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*/
92static void hashdelete (Hash *t)
93{
94 luaM_free(nodevector(t));
95 luaM_free(t);
96}
97
98
99void luaH_free (Hash *frees)
100{
101 while (frees) {73 while (frees) {
102 Hash *next = (Hash *)frees->head.next;74 Hash *next = (Hash *)frees->head.next;
103 L->nblocks -= gcsize(frees->nhash);75 L->nblocks -= gcsize(frees->nhash);
104 hashdelete(frees);76 luaM_free(nodevector(frees));
77 luaM_free(frees);
105 frees = next;78 frees = next;
106 }79 }
107}80}
108 81
109 82
110Hash *luaH_new (int nhash)83static Node *hashnodecreate (int nhash) {
111{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
92Hash *luaH_new (int nhash) {
112 Hash *t = luaM_new(Hash);93 Hash *t = luaM_new(Hash);
113 nhash = luaO_redimension((int)((float)nhash/REHASH_LIMIT));94 nhash = luaO_redimension(nhash*3/2);
114 nodevector(t) = hashnodecreate(nhash);95 nodevector(t) = hashnodecreate(nhash);
115 nhash(t) = nhash;96 nhash(t) = nhash;
116 nuse(t) = 0;97 nuse(t) = 0;
@@ -121,96 +102,76 @@ Hash *luaH_new (int nhash) · 4 unmodified lines
121}102}
122 103
123 104
124static int newsize (Hash *t)105static int newsize (Hash *t) {
125{
126 Node *v = t->node;106 Node *v = t->node;
127 int size = nhash(t);107 int size = nhash(t);
128 int realuse = 0;108 int realuse = 0;
129 int i;109 int i;
130 for (i=0; i<size; i++) {110 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)
132 realuse++;112 realuse++;
133 }113 }
134 if (2*(realuse+1) <= size) /* +1 is the new element */114 return luaO_redimension((realuse+1)*2); /* +1 is the new element */
135 return size; /* don't need to grow, just rehash */
136 else
137 return luaO_redimension(size);
138}115}
139 116
140static void rehash (Hash *t)117
141{118static void rehash (Hash *t) {
142 int nold = nhash(t);119 int nold = nhash(t);
143 Node *vold = nodevector(t);120 Node *vold = nodevector(t);
144 int nnew = newsize(t);121 int nnew = newsize(t);
145 int i;122 int i;
146 nodevector(t) = hashnodecreate(nnew);123 nodevector(t) = hashnodecreate(nnew);
147 nhash(t) = nnew;124 nhash(t) = nnew;
125 nuse(t) = 0;
148 for (i=0; i<nold; i++) {126 for (i=0; i<nold; i++) {
149 Node *n = vold+i;127 Node *n = vold+i;
150 if (ttype(ref(n)) != LUA_T_NIL && ttype(val(n)) != LUA_T_NIL)128 if (ttype(val(n)) != LUA_T_NIL) {
151 *node(t, present(t, ref(n))) = *n; /* copy old node to luaM_new hash */129 *luaH_present(t, ref(n)) = *n; /* copy old node to new hash */
130 nuse(t)++;
131 }
152 }132 }
153 L->nblocks += gcsize(nnew)-gcsize(nold);133 L->nblocks += gcsize(nnew)-gcsize(nold);
154 luaM_free(vold);134 luaM_free(vold);
155}135}
156 136
157/*
158** If the hash node is present, return its pointer, otherwise return
159** null.
160*/
161TObject *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}
167 137
168 138void luaH_set (Hash *t, TObject *ref, TObject *val) {
169/*139 Node *n = luaH_present(t, ref);
170** If the hash node is present, return its pointer, otherwise create a luaM_new140 if (ttype(ref(n)) != LUA_T_NIL)
171** node for the given reference and also return its pointer.141 *val(n) = *val;
172*/142 else {
173TObject *luaH_set (Hash *t, TObject *ref)143 TObject buff;
174{144 buff = *val; /* rehash may invalidate this address */
175 Node *n = node(t, present(t, ref));145 if ((long)nuse(t)*3L > (long)nhash(t)*2L) {
176 if (ttype(ref(n)) == LUA_T_NIL) {
177 nuse(t)++;
178 if ((float)nuse(t) > (float)nhash(t)*REHASH_LIMIT) {
179 rehash(t);146 rehash(t);
180 n = node(t, present(t, ref));147 n = luaH_present(t, ref);
181 }148 }
149 nuse(t)++;
182 *ref(n) = *ref;150 *ref(n) = *ref;
183 ttype(val(n)) = LUA_T_NIL;151 *val(n) = buff;
184 }152 }
185 return (val(n));
186}153}
187 154
188 155
189static Node *hashnext (Hash *t, int i)156int luaH_pos (Hash *t, TObject *r) {
190{157 Node *n = luaH_present(t, r);
191 Node *n;158 luaL_arg_check(ttype(val(n)) != LUA_T_NIL, 2, "key not found");
192 int tsize = nhash(t);159 return n-(t->node);
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);
202}160}
203 161
204Node *luaH_next (TObject *o, TObject *r)162
205{163void luaH_setint (Hash *t, int ref, TObject *val) {
206 Hash *t = avalue(o);164 TObject index;
207 if (ttype(r) == LUA_T_NIL)165 ttype(&index) = LUA_T_NUMBER;
208 return hashnext(t, 0);166 nvalue(&index) = ref;
209 else {167 luaH_set(t, &index, val);
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 }
216}168}
169
170
171TObject *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 @@
1/*1/*
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 $
3** Lua tables (hash)3** Lua tables (hash)
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -15,10 +15,16 @@ · 9 unmodified lines
15#define val(n) (&(n)->val)15#define val(n) (&(n)->val)
16#define nhash(t) ((t)->nhash)16#define nhash(t) ((t)->nhash)
17 17
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
18Hash *luaH_new (int nhash);21Hash *luaH_new (int nhash);
19void luaH_free (Hash *frees);22void luaH_free (Hash *frees);
20TObject *luaH_get (Hash *t, TObject *ref);23Node *luaH_present (Hash *t, TObject *key);
21TObject *luaH_set (Hash *t, TObject *ref);24void luaH_set (Hash *t, TObject *ref, TObject *val);
22Node *luaH_next (TObject *o, TObject *r);25int luaH_pos (Hash *t, TObject *r);
26void luaH_setint (Hash *t, int ref, TObject *val);
27TObject *luaH_getint (Hash *t, int ref);
28
23 29
24#endif30#endif
src/ltm.c+38−53
@@ -1,5 +1,5 @@
1/*1/*
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 $
3** Tag methods3** Tag methods
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -22,8 +22,7 @@ char *luaT_eventname[] = { /* ORDER IM */ · 16 unmodified lines
22};22};
23 23
24 24
25static int luaI_checkevent (char *name, char *list[])25static int luaI_checkevent (char *name, char *list[]) {
26{
27 int e = luaL_findstring(name, list);26 int e = luaL_findstring(name, list);
28 if (e < 0)27 if (e < 0)
29 luaL_verror("`%.50s' is not a valid event name", name);28 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
35/* events in LUA_T_NIL are all allowed, since this is used as a34/* events in LUA_T_NIL are all allowed, since this is used as a
36* 'placeholder' for "default" fallbacks35* 'placeholder' for "default" fallbacks
37*/36*/
38static char validevents[NUM_TAGS][IM_N] = { /* ORDER LUA_T, ORDER IM */37static char luaT_validevents[NUM_TAGS][IM_N] = { /* ORDER LUA_T, ORDER IM */
39{1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1}, /* LUA_T_USERDATA */38{1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1}, /* LUA_T_USERDATA */
40{1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1}, /* LUA_T_NUMBER */39{1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1}, /* LUA_T_NUMBER */
41{1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, /* LUA_T_STRING */40{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
45{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1} /* LUA_T_NIL */44{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1} /* LUA_T_NIL */
46};45};
47 46
48 47static int luaT_validevent (int t, int e) { /* ORDER LUA_T */
49static int validevent (int t, int e)48 return (t < LUA_T_NIL) ? 1 : luaT_validevents[-t][e];
50{ /* ORDER LUA_T */
51 return (t < LUA_T_NIL) ? 1 : validevents[-t][e];
52}49}
53 50
54 51
55static void init_entry (int tag)52static void init_entry (int tag) {
56{
57 int i;53 int i;
58 for (i=0; i<IM_N; i++)54 for (i=0; i<IM_N; i++)
59 ttype(luaT_getim(tag, i)) = LUA_T_NIL;55 ttype(luaT_getim(tag, i)) = LUA_T_NIL;
60}56}
61 57
62 58
63void luaT_init (void)59void luaT_init (void) {
64{
65 int t;60 int t;
66 L->IMtable_size = NUM_TAGS*2;
67 L->last_tag = -(NUM_TAGS-1);61 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);
69 for (t=L->last_tag; t<=0; t++)63 for (t=L->last_tag; t<=0; t++)
70 init_entry(t);64 init_entry(t);
71}65}
72 66
73 67
74int lua_newtag (void)68int lua_newtag (void) {
75{
76 --L->last_tag;69 --L->last_tag;
77 if ((-L->last_tag) >= L->IMtable_size)70 luaM_growvector(L->IMtable, -(L->last_tag), 1, struct IM, arrEM, MAX_INT);
78 L->IMtable_size = luaM_growvector(&L->IMtable, L->IMtable_size,
79 struct IM, memEM, MAX_INT);
80 init_entry(L->last_tag);71 init_entry(L->last_tag);
81 return L->last_tag;72 return L->last_tag;
82}73}
83 74
84 75
85static void checktag (int tag)76static void checktag (int tag) {
86{
87 if (!(L->last_tag <= tag && tag <= 0))77 if (!(L->last_tag <= tag && tag <= 0))
88 luaL_verror("%d is not a valid tag", tag);78 luaL_verror("%d is not a valid tag", tag);
89}79}
90 80
91void luaT_realtag (int tag)81void luaT_realtag (int tag) {
92{
93 if (!(L->last_tag <= tag && tag < LUA_T_NIL))82 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);
95}84}
96 85
97 86
98int lua_copytagmethods (int tagto, int tagfrom)87int lua_copytagmethods (int tagto, int tagfrom) {
99{
100 int e;88 int e;
101 checktag(tagto);89 checktag(tagto);
102 checktag(tagfrom);90 checktag(tagfrom);
103 for (e=0; e<IM_N; e++) {91 for (e=0; e<IM_N; e++) {
104 if (validevent(tagto, e))92 if (luaT_validevent(tagto, e))
105 *luaT_getim(tagto, e) = *luaT_getim(tagfrom, e);93 *luaT_getim(tagto, e) = *luaT_getim(tagfrom, e);
106 }94 }
107 return tagto;95 return tagto;
108}96}
109 97
110 98
111int luaT_efectivetag (TObject *o)99int luaT_effectivetag (TObject *o) {
112{
113 int t;100 int t;
114 switch (t = ttype(o)) {101 switch (t = ttype(o)) {
115 case LUA_T_ARRAY:102 case LUA_T_ARRAY:
@@ -131,36 +118,34 @@ int luaT_efectivetag (TObject *o) · 15 unmodified lines
131}118}
132 119
133 120
134TObject *luaT_gettagmethod (int t, char *event)121TObject *luaT_gettagmethod (int t, char *event) {
135{
136 int e = luaI_checkevent(event, luaT_eventname);122 int e = luaI_checkevent(event, luaT_eventname);
137 checktag(t);123 checktag(t);
138 if (validevent(t, e))124 if (luaT_validevent(t, e))
139 return luaT_getim(t,e);125 return luaT_getim(t,e);
140 else126 else
141 return &luaO_nilobject;127 return &luaO_nilobject;
142}128}
143 129
144 130
145void luaT_settagmethod (int t, char *event, TObject *func)131void luaT_settagmethod (int t, char *event, TObject *func) {
146{132 TObject temp;
147 TObject temp = *func;
148 int e = luaI_checkevent(event, luaT_eventname);133 int e = luaI_checkevent(event, luaT_eventname);
149 checktag(t);134 checktag(t);
150 if (!validevent(t, e))135 if (!luaT_validevent(t, e))
151 luaL_verror("settagmethod: cannot change tag method `%.20s' for tag %d",136 luaL_verror("cannot change tag method `%.20s' for type `%.20s'%.20s",
152 luaT_eventname[e], t);137 luaT_eventname[e], luaO_typenames[-t],
138 (t == LUA_T_ARRAY || t == LUA_T_USERDATA) ? " with default tag"
139 : "");
140 temp = *func;
153 *func = *luaT_getim(t,e);141 *func = *luaT_getim(t,e);
154 *luaT_getim(t, e) = temp;142 *luaT_getim(t, e) = temp;
155}143}
156 144
157 145
158char *luaT_travtagmethods (int (*fn)(TObject *))146char *luaT_travtagmethods (int (*fn)(TObject *)) { /* ORDER IM */
159{
160 int e;147 int e;
161 if (fn(&L->errorim))148 for (e=IM_GETTABLE; e<=IM_FUNCTION; e++) {
162 return "error";
163 for (e=IM_GETTABLE; e<=IM_FUNCTION; e++) { /* ORDER IM */
164 int t;149 int t;
165 for (t=0; t>=L->last_tag; t--)150 for (t=0; t>=L->last_tag; t--)
166 if (fn(luaT_getim(t,e)))151 if (fn(luaT_getim(t,e)))
@@ -177,6 +162,7 @@ char *luaT_travtagmethods (int (*fn)(TObject *)) · 10 unmodified lines
177#ifdef LUA_COMPAT2_5162#ifdef LUA_COMPAT2_5
178 163
179#include "lapi.h"164#include "lapi.h"
165#include "lstring.h"
180 166
181static void errorFB (void)167static void errorFB (void)
182{168{
@@ -191,23 +177,20 @@ static void errorFB (void) · 8 unmodified lines
191static void nilFB (void) { }177static void nilFB (void) { }
192 178
193 179
194static void typeFB (void)180static void typeFB (void) {
195{
196 lua_error("unexpected type");181 lua_error("unexpected type");
197}182}
198 183
199 184
200static void fillvalids (IMS e, TObject *func)185static void fillvalids (IMS e, TObject *func) {
201{
202 int t;186 int t;
203 for (t=LUA_T_NIL; t<=LUA_T_USERDATA; t++)187 for (t=LUA_T_NIL; t<=LUA_T_USERDATA; t++)
204 if (validevent(t, e))188 if (luaT_validevent(t, e))
205 *luaT_getim(t, e) = *func;189 *luaT_getim(t, e) = *func;
206}190}
207 191
208 192
209void luaT_setfallback (void)193void luaT_setfallback (void) {
210{
211 static char *oldnames [] = {"error", "getglobal", "arith", "order", NULL};194 static char *oldnames [] = {"error", "getglobal", "arith", "order", NULL};
212 TObject oldfunc;195 TObject oldfunc;
213 lua_CFunction replace;196 lua_CFunction replace;
@@ -215,11 +198,13 @@ void luaT_setfallback (void) · 1 unmodified line
215 lua_Object func = lua_getparam(2);198 lua_Object func = lua_getparam(2);
216 luaL_arg_check(lua_isfunction(func), 2, "function expected");199 luaL_arg_check(lua_isfunction(func), 2, "function expected");
217 switch (luaL_findstring(name, oldnames)) {200 switch (luaL_findstring(name, oldnames)) {
218 case 0: /* old error fallback */201 case 0: { /* old error fallback */
219 oldfunc = L->errorim;202 TObject *em = &(luaS_new("_ERRORMESSAGE")->u.s.globalval);
220 L->errorim = *luaA_Address(func);203 oldfunc = *em;
204 *em = *luaA_Address(func);
221 replace = errorFB;205 replace = errorFB;
222 break;206 break;
207 }
223 case 1: /* old getglobal fallback */208 case 1: /* old getglobal fallback */
224 oldfunc = *luaT_getim(LUA_T_NIL, IM_GETGLOBAL);209 oldfunc = *luaT_getim(LUA_T_NIL, IM_GETGLOBAL);
225 *luaT_getim(LUA_T_NIL, IM_GETGLOBAL) = *luaA_Address(func);210 *luaT_getim(LUA_T_NIL, IM_GETGLOBAL) = *luaA_Address(func);
src/ltm.h+3−3
@@ -1,5 +1,5 @@
1/*1/*
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 $
3** Tag methods3** Tag methods
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -45,14 +45,14 @@ struct IM { · 39 unmodified lines
45 45
46 46
47#define luaT_getim(tag,event) (&L->IMtable[-(tag)].int_method[event])47#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)))
49 49
50extern char *luaT_eventname[];50extern char *luaT_eventname[];
51 51
52 52
53void luaT_init (void);53void luaT_init (void);
54void luaT_realtag (int tag);54void luaT_realtag (int tag);
55int luaT_efectivetag (TObject *o);55int luaT_effectivetag (TObject *o);
56void luaT_settagmethod (int t, char *event, TObject *func);56void luaT_settagmethod (int t, char *event, TObject *func);
57TObject *luaT_gettagmethod (int t, char *event);57TObject *luaT_gettagmethod (int t, char *event);
58char *luaT_travtagmethods (int (*fn)(TObject *));58char *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
17 $(CC) -o $@ $(OBJS) -L$(LIB) -llua -llualib -lm17 $(CC) -o $@ $(OBJS) -L$(LIB) -llua -llualib -lm
18 18
19$(LIB)/liblua.a:19$(LIB)/liblua.a:
20 cd ..; make20 cd ..; $(MAKE)
21 21
22$(LIB)/liblualib.a:22$(LIB)/liblualib.a:
23 cd ../lib; make23 cd ../lib; $(MAKE)
24 24
25clean:25clean:
26 rm -f $(OBJS) $T26 rm -f $(OBJS) $T
src/lua/README+21−3
@@ -1,5 +1,6 @@
1This client is a sample lua interpreter.1This client is a sample lua interpreter.
2It can be used as a batch interpreter and interactively.2It can be used as a batch interpreter and also interactively.
3
3Here are the options it understands:4Here are the options it understands:
4 5
5 -v print version information6 -v print version information
@@ -11,10 +12,27 @@ Here are the options it understands: · 5 unmodified lines
11 a=b sets global `a' with string `b' (no need to quote b)12 a=b sets global `a' with string `b' (no need to quote b)
12 name dofile `name'13 name dofile `name'
13 14
14If no options are given, then it reads and executes lines from stdin.15If no options are given, then it reads lines from stdin and executes them
15In this case, each line must contain a complete statement.16as they are read. So, each line must contain a complete statement.
16To span a statement across several lines, end each line with a backslash '\'.17To span a statement across several lines, end each line with a backslash '\'.
18
17To change the prompt, set the global variable _PROMPT to whatever you want.19To change the prompt, set the global variable _PROMPT to whatever you want.
20You can do after calling the interpreter or on the command line with
21 _PROMPT="lua: "
22for example.
23
24You must be careful when using quotes on the command line because they are
25usually handled by the shell.
18 26
19This interpreter is good for using Lua as a standalone language.27This interpreter is good for using Lua as a standalone language.
20For a minimal interpreter, see etc/min.c.28For a minimal interpreter, see etc/min.c.
29
30If your application simply exports new functions to Lua (which is common),
31then you can use this interpreter unmodified: just define a function
32
33 void lua_userinit (void)
34
35in your code. In this function, you should do whatever initializations are
36need, typically exporting your functions to Lua.
37If you use this scheme, you must explicily open any standard libraries you need.
38See ../lib/linit.c
src/lua/lua.c+29−35
@@ -1,5 +1,5 @@
1/*1/*
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 $
3** Lua stand-alone interpreter3** Lua stand-alone interpreter
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -15,12 +15,6 @@ · 9 unmodified lines
15#include "lualib.h"15#include "lualib.h"
16 16
17 17
18#ifndef OLD_ANSI
19#include <locale.h>
20#else
21#define setlocale(a,b) 0
22#endif
23
24#ifdef _POSIX_SOURCE18#ifdef _POSIX_SOURCE
25#include <unistd.h>19#include <unistd.h>
26#else20#else
@@ -32,27 +26,33 @@ typedef void (*handler)(int); /* type for signal actions */ · 5 unmodified lines
32 26
33static void laction (int i);27static void laction (int i);
34 28
35static handler lreset (void)29
36{30static lua_LHFunction old_linehook = NULL;
37 lua_linehook = NULL;31static lua_CHFunction old_callhook = NULL;
38 lua_callhook = NULL;32
33
34static handler lreset (void) {
39 return signal(SIGINT, laction);35 return signal(SIGINT, laction);
40}36}
41 37
42static void lstop (void)38
43{39static void lstop (void) {
40 lua_setlinehook(old_linehook);
41 lua_setcallhook(old_callhook);
44 lreset();42 lreset();
45 lua_error("interrupted!");43 lua_error("interrupted!");
46}44}
47 45
48static void laction (int i)46
49{47static void laction (int i) {
50 lua_linehook = (lua_LHFunction)lstop;48 signal(SIGINT, SIG_DFL); /* if another SIGINT happens before lstop,
51 lua_callhook = (lua_CHFunction)lstop;49 terminate process (default action) */
50 old_linehook = lua_setlinehook((lua_LHFunction)lstop);
51 old_callhook = lua_setcallhook((lua_CHFunction)lstop);
52}52}
53 53
54static int ldo (int (*f)(char *), char *name)54
55{55static int ldo (int (*f)(char *), char *name) {
56 int res;56 int res;
57 handler h = lreset();57 handler h = lreset();
58 res = f(name); /* dostring | dofile */58 res = f(name); /* dostring | dofile */
@@ -61,8 +61,7 @@ static int ldo (int (*f)(char *), char *name) · 2 unmodified lines
61}61}
62 62
63 63
64static void print_message (void)64static void print_message (void) {
65{
66 fprintf(stderr,65 fprintf(stderr,
67"Lua: command line options:\n"66"Lua: command line options:\n"
68" -v print version information\n"67" -v print version information\n"
@@ -76,8 +75,7 @@ static void print_message (void) · 7 unmodified lines
76}75}
77 76
78 77
79static void assign (char *arg)78static void assign (char *arg) {
80{
81 if (strlen(arg) >= 500)79 if (strlen(arg) >= 500)
82 fprintf(stderr, "lua: shell argument too long");80 fprintf(stderr, "lua: shell argument too long");
83 else {81 else {
@@ -90,13 +88,11 @@ static void assign (char *arg) · 6 unmodified lines
90 }88 }
91}89}
92 90
93#define BUF_SIZE 512
94 91
95static void manual_input (int prompt)92static void manual_input (int prompt) {
96{
97 int cont = 1;93 int cont = 1;
98 while (cont) {94 while (cont) {
99 char buffer[BUF_SIZE];95 char buffer[BUFSIZ];
100 int i = 0;96 int i = 0;
101 lua_beginblock();97 lua_beginblock();
102 if (prompt)98 if (prompt)
@@ -112,13 +108,13 @@ static void manual_input (int prompt) · 9 unmodified lines
112 buffer[i-1] = '\n';108 buffer[i-1] = '\n';
113 else break;109 else break;
114 }110 }
115 else if (i >= BUF_SIZE-1) {111 else if (i >= BUFSIZ-1) {
116 fprintf(stderr, "lua: argument line too long\n");112 fprintf(stderr, "lua: argument line too long\n");
117 break;113 break;
118 }114 }
119 else buffer[i++] = c;115 else buffer[i++] = (char)c;
120 }116 }
121 buffer[i] = 0;117 buffer[i] = '\0';
122 ldo(lua_dostring, buffer);118 ldo(lua_dostring, buffer);
123 lua_endblock();119 lua_endblock();
124 }120 }
@@ -129,11 +125,9 @@ static void manual_input (int prompt) · 4 unmodified lines
129int main (int argc, char *argv[])125int main (int argc, char *argv[])
130{126{
131 int i;127 int i;
132 setlocale(LC_ALL, "");128 lua_open();
133 lua_iolibopen();
134 lua_strlibopen();
135 lua_mathlibopen();
136 lua_pushstring("> "); lua_setglobal("_PROMPT");129 lua_pushstring("> "); lua_setglobal("_PROMPT");
130 lua_userinit();
137 if (argc < 2) { /* no arguments? */131 if (argc < 2) { /* no arguments? */
138 if (isatty(0)) {132 if (isatty(0)) {
139 printf("%s %s\n", LUA_VERSION, LUA_COPYRIGHT);133 printf("%s %s\n", LUA_VERSION, LUA_COPYRIGHT);
@@ -155,7 +149,7 @@ int main (int argc, char *argv[]) · 15 unmodified lines
155 manual_input(0);149 manual_input(0);
156 break;150 break;
157 case 'd':151 case 'd':
158 lua_debug = 1;152 lua_setdebug(1);
159 break;153 break;
160 case 'v':154 case 'v':
161 printf("%s %s\n(written by %s)\n\n",155 printf("%s %s\n(written by %s)\n\n",
src/luac/Makefile+3−3
@@ -5,8 +5,8 @@ LUA= ../.. · 4 unmodified lines
5include $(LUA)/config5include $(LUA)/config
6 6
7INCS= -I$(INC) $(EXTRA_INCS) -I..7INCS= -I$(INC) $(EXTRA_INCS) -I..
8OBJS= dump.o luac.o opcode.o opt.o print.o stubs.o8OBJS= dump.o luac.o opcode.o opt.o print.o stubs.o test.o
9SRCS= dump.c luac.c opcode.c opt.c print.c stubs.c luac.h opcode.h9SRCS= dump.c luac.c opcode.c opt.c print.c stubs.c test.c luac.h opcode.h
10 10
11T= $(BIN)/luac11T= $(BIN)/luac
12 12
@@ -16,7 +16,7 @@ $T: $(OBJS) $(LIB)/liblua.a · 3 unmodified lines
16 $(CC) -o $@ $(OBJS) -L$(LIB) -llua16 $(CC) -o $@ $(OBJS) -L$(LIB) -llua
17 17
18$(LIB)/liblua.a:18$(LIB)/liblua.a:
19 cd ..; make19 cd ..; $(MAKE)
20 20
21clean:21clean:
22 rm -f $(OBJS) $T22 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
2with lua_dofile in C or with dofile in Lua.2with lua_dofile in C or with dofile in Lua.
3The main advantages of pre-compiling chunks are: faster loading,3The main advantages of pre-compiling chunks are: faster loading,
4protecting source code from user changes, off-line syntax error detection.4protecting source code from user changes, off-line syntax error detection.
5
6luac can also be used to learn about the Lua virtual machine.5luac can also be used to learn about the Lua virtual machine.
7 6
8Here are the options it understands:7Here are the options that luac understands:
9 8
10 -c compile (default)9 -c compile (default)
11 -u undump10 -d generate debugging information
12 -d generate debugging information11 -D name predefine 'name' for conditional compilation
13 -D predefine symbol for conditional compilation12 -l list (default for -u)
14 -l list (default for -u)13 -n save numbers in native format (file may not be portable)
15 -o output file for -c (default is "luac.out")14 -o file output file for -c (default is "luac.out")
16 -O optimize15 -O optimize
17 -p parse only16 -p parse only
18 -q quiet (default for -c)17 -q quiet (default for -c)
19 -v show version information18 -t test code integrity
20 -V verbose19 -u undump
21 - compile "stdin"20 -U name undefine 'name' for conditional compilation
21 -v show version information
22 -V verbose
23 - compile "stdin"
22 24
23Finally, luac is an example of how to use the internals of Lua (politely).25Finally, luac is an example of how to use the internals of Lua (politely).
24Also, luac does not need the runtime code and stubs.c makes sure it is not26Also, luac does not need the runtime code and stubs.c makes sure it is not
25linked into luac. This file also shows how to avoid linking the parser.27linked into luac. This file also shows how to avoid linking the parser.
28
src/luac/dump.c+61−65
@@ -1,16 +1,20 @@
1/*1/*
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 $
3** save bytecodes to file3** save bytecodes to file
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
6 6
7#include <errno.h>
7#include <stdio.h>8#include <stdio.h>
8#include <stdlib.h>9#include <stdlib.h>
9#include "luac.h"10#include "luac.h"
10 11
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
12#define DumpBlock(b,size,D) fwrite(b,size,1,D)16#define DumpBlock(b,size,D) fwrite(b,size,1,D)
13#define DumpNative(t,D) DumpBlock(&t,sizeof(t),D)17#define DumpInt DumpLong
14 18
15static void DumpWord(int i, FILE* D)19static void DumpWord(int i, FILE* D)
16{20{
@@ -28,43 +32,24 @@ static void DumpLong(long i, FILE* D) · 11 unmodified lines
28 DumpWord(lo,D);32 DumpWord(lo,D);
29}33}
30 34
31#if ID_NUMBER==ID_REAL435static void DumpNumber(real x, FILE* D, int native, TProtoFunc* tf)
32/* LUA_NUMBER */
33/* assumes sizeof(long)==4 and sizeof(float)==4 (IEEE) */
34static void DumpFloat(float f, FILE* D)
35{36{
36 long l=*(long*)&f;37 if (native)
37 DumpLong(l,D);38 DumpBlock(&x,sizeof(x),D);
38}39 else
39#endif
40
41#if ID_NUMBER==ID_REAL8
42/* LUA_NUMBER */
43/* assumes sizeof(long)==4 and sizeof(double)==8 (IEEE) */
44static 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 */
54 {40 {
55 DumpLong(l[0],D);41 char b[256];
56 DumpLong(l[1],D);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);
57 }47 }
58}48}
59#endif
60 49
61static void DumpCode(TProtoFunc* tf, FILE* D)50static void DumpCode(TProtoFunc* tf, FILE* D)
62{51{
63 int size=CodeSize(tf);52 int size=luaU_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);
68 DumpLong(size,D);53 DumpLong(size,D);
69 DumpBlock(tf->code,size,D);54 DumpBlock(tf->code,size,D);
70}55}
@@ -72,87 +57,98 @@ static void DumpCode(TProtoFunc* tf, FILE* D) · 1 unmodified line
72static void DumpString(char* s, int size, FILE* D)57static void DumpString(char* s, int size, FILE* D)
73{58{
74 if (s==NULL)59 if (s==NULL)
75 DumpWord(0,D);60 DumpLong(0,D);
76 else61 else
77 {62 {
78 if (NotWord(size))63 DumpLong(size,D);
79 luaL_verror("string too long (%d bytes): \"%.32s...\"",size,s);
80 DumpWord(size,D);
81 DumpBlock(s,size,D);64 DumpBlock(s,size,D);
82 }65 }
83}66}
84 67
85static void DumpTString(TaggedString* s, FILE* D)68static void DumpTString(TaggedString* s, FILE* D)
86{69{
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);
88}74}
89 75
90static void DumpLocals(TProtoFunc* tf, FILE* D)76static void DumpLocals(TProtoFunc* tf, FILE* D)
91{77{
92 int n;78 if (tf->locvars==NULL)
93 LocVar* lv;79 DumpInt(0,D);
94 for (n=0,lv=tf->locvars; lv && lv->line>=0; lv++) ++n;80 else
95 DumpWord(n,D);
96 for (lv=tf->locvars; lv && lv->line>=0; lv++)
97 {81 {
98 DumpWord(lv->line,D);82 LocVar* v;
99 DumpTString(lv->varname,D);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 }
100 }92 }
101}93}
102 94
103static void DumpFunction(TProtoFunc* tf, FILE* D);95static void DumpFunction(TProtoFunc* tf, FILE* D, int native);
104 96
105static void DumpConstants(TProtoFunc* tf, FILE* D)97static void DumpConstants(TProtoFunc* tf, FILE* D, int native)
106{98{
107 int i,n=tf->nconsts;99 int i,n=tf->nconsts;
108 DumpWord(n,D);100 DumpInt(n,D);
109 for (i=0; i<n; i++)101 for (i=0; i<n; i++)
110 {102 {
111 TObject* o=tf->consts+i;103 TObject* o=tf->consts+i;
112 fputc(-ttype(o),D);104 fputc(-ttype(o),D); /* ttype(o) is negative - ORDER LUA_T */
113 switch (ttype(o))105 switch (ttype(o))
114 {106 {
115 case LUA_T_NUMBER:107 case LUA_T_NUMBER:
116 DumpNumber(nvalue(o),D);108 DumpNumber(nvalue(o),D,native,tf);
117 break;109 break;
118 case LUA_T_STRING:110 case LUA_T_STRING:
119 DumpTString(tsvalue(o),D);111 DumpTString(tsvalue(o),D);
120 break;112 break;
121 case LUA_T_PROTO:113 case LUA_T_PROTO:
122 DumpFunction(tfvalue(o),D);114 DumpFunction(tfvalue(o),D,native);
123 break;115 break;
124 case LUA_T_NIL:116 case LUA_T_NIL:
125 break;117 break;
126 default: /* cannot happen */118 default: /* cannot happen */
127 luaL_verror("cannot dump constant #%d: type=%d [%s]",119 luaU_badconstant("dump",i,o,tf);
128 i,ttype(o),luaO_typename(o));
129 break;120 break;
130 }121 }
131 }122 }
132}123}
133 124
134static void DumpFunction(TProtoFunc* tf, FILE* D)125static void DumpFunction(TProtoFunc* tf, FILE* D, int native)
135{126{
136 DumpWord(tf->lineDefined,D);127 DumpInt(tf->lineDefined,D);
137 DumpTString(tf->fileName,D);128 DumpTString(tf->source,D);
138 DumpCode(tf,D);129 DumpCode(tf,D);
139 DumpLocals(tf,D);130 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);
141}134}
142 135
143static void DumpHeader(TProtoFunc* Main, FILE* D)136static void DumpHeader(TProtoFunc* Main, FILE* D, int native)
144{137{
145 real t=TEST_NUMBER;
146 fputc(ID_CHUNK,D);138 fputc(ID_CHUNK,D);
147 fputs(SIGNATURE,D);139 fputs(SIGNATURE,D);
148 fputc(VERSION,D);140 fputc(VERSION,D);
149 fputc(ID_NUMBER,D);141 if (native)
150 fputc(sizeof(t),D);142 {
151 DumpNumber(t,D);143 fputc(sizeof(real),D);
144 DumpNumber(TEST_NUMBER,D,native,Main);
145 }
146 else
147 fputc(0,D);
152}148}
153 149
154void DumpChunk(TProtoFunc* Main, FILE* D)150void luaU_dumpchunk(TProtoFunc* Main, FILE* D, int native)
155{151{
156 DumpHeader(Main,D);152 DumpHeader(Main,D,native);
157 DumpFunction(Main,D);153 DumpFunction(Main,D,native);
158}154}
src/luac/luac.c+51−48
@@ -1,5 +1,5 @@
1/*1/*
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 $
3** lua compiler (saves bytecodes to files; also list binary files)3** lua compiler (saves bytecodes to files; also list binary files)
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -9,43 +9,45 @@ · 3 unmodified lines
9#include <string.h>9#include <string.h>
10#include "luac.h"10#include "luac.h"
11#include "lparser.h"11#include "lparser.h"
12#include "lstate.h"
12#include "lzio.h"13#include "lzio.h"
13#include "luadebug.h"
14 14
15#define OUTPUT "luac.out" /* default output file */15#define OUTPUT "luac.out" /* default output file */
16 16
17extern void DumpChunk(TProtoFunc* Main, FILE* D);
18extern void PrintChunk(TProtoFunc* Main);
19extern void OptChunk(TProtoFunc* Main);
20
21static FILE* efopen(char* name, char* mode);17static FILE* efopen(char* name, char* mode);
22static void doit(int undump, char* filename);18static void doit(int undump, char* filename);
23 19
24static int listing=0; /* list bytecodes? */20static int listing=0; /* list bytecodes? */
25static int debugging=0; /* debug? */21static int debugging=0; /* emit debug information? */
26static int dumping=1; /* dump bytecodes? */22static int dumping=1; /* dump bytecodes? */
27static int undumping=0; /* undump bytecodes? */23static int undumping=0; /* undump bytecodes? */
28static int optimizing=0; /* optimize? */24static int optimizing=0; /* optimize? */
29static int parsing=0; /* parse only? */25static int parsing=0; /* parse only? */
26static int testing=0; /* test integrity? */
30static int verbose=0; /* tell user what is done */27static int verbose=0; /* tell user what is done */
28static int native=0; /* save numbers in native format? */
31static FILE* D; /* output file */29static FILE* D; /* output file */
32 30
33static void usage(void)31static void usage(char* op)
34{32{
35 fprintf(stderr,"usage: "33 if (op) fprintf(stderr,"luac: unrecognized option '%s'\n",op);
36 "luac [-c | -u] [-D name] [-d] [-l] [-o output] [-O] [-p] [-q] [-v] [-V] [files]\n"34 fprintf(stderr,
37 " -c\tcompile (default)\n"35 "usage: luac [options] [filenames]. Available options are:\n"
38 " -u\tundump\n"36 " -c\t\tcompile (default)\n"
39 " -d\tgenerate debugging information\n"37 " -d\t\tgenerate debugging information\n"
40 " -D\tpredefine symbol for conditional compilation\n"38 " -D name\tpredefine 'name' for conditional compilation\n"
41 " -l\tlist (default for -u)\n"39 " -l\t\tlist (default for -u)\n"
42 " -o\toutput file for -c (default is \"" OUTPUT "\")\n"40 " -n\t\tsave numbers in native format (file may not be portable)\n"
43 " -O\toptimize\n"41 " -o file\toutput file for -c (default is \"" OUTPUT "\")\n"
44 " -p\tparse only\n"42 " -O\t\toptimize\n"
45 " -q\tquiet (default for -c)\n"43 " -p\t\tparse only\n"
46 " -v\tshow version information\n"44 " -q\t\tquiet (default for -c)\n"
47 " -V\tverbose\n"45 " -t\t\ttest code integrity\n"
48 " -\tcompile \"stdin\"\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"
49 );51 );
50 exit(1);52 exit(1);
51}53}
@@ -61,7 +63,7 @@ int main(int argc, char* argv[]) · 9 unmodified lines
61 {63 {
62 if (argv[i][0]!='-') /* end of options */64 if (argv[i][0]!='-') /* end of options */
63 break;65 break;
64 else if (IS("-")) /* use stdin */66 else if (IS("-")) /* end of options; use stdin */
65 break;67 break;
66 else if (IS("-c")) /* compile (and dump) */68 else if (IS("-c")) /* compile (and dump) */
67 {69 {
@@ -78,6 +80,8 @@ int main(int argc, char* argv[]) · 10 unmodified lines
78 debugging=1;80 debugging=1;
79 else if (IS("-l")) /* list */81 else if (IS("-l")) /* list */
80 listing=1;82 listing=1;
83 else if (IS("-n")) /* native */
84 native=1;
81 else if (IS("-o")) /* output file */85 else if (IS("-o")) /* output file */
82 d=argv[++i];86 d=argv[++i];
83 else if (IS("-O")) /* optimize */87 else if (IS("-O")) /* optimize */
@@ -89,34 +93,37 @@ int main(int argc, char* argv[]) · 5 unmodified lines
89 }93 }
90 else if (IS("-q")) /* quiet */94 else if (IS("-q")) /* quiet */
91 listing=0;95 listing=0;
96 else if (IS("-t")) /* test */
97 testing=1;
92 else if (IS("-u")) /* undump */98 else if (IS("-u")) /* undump */
93 {99 {
94 dumping=0;100 dumping=0;
95 undumping=1;101 undumping=1;
96 listing=1;102 listing=1;
97 }103 }
104 else if (IS("-U")) /* undefine */
105 {
106 TaggedString* s=luaS_new(argv[++i]);
107 s->u.s.globalval.ttype=LUA_T_NIL;
108 }
98 else if (IS("-v")) /* show version */109 else if (IS("-v")) /* show version */
99 printf("%s %s\n(written by %s)\n\n",LUA_VERSION,LUA_COPYRIGHT,LUA_AUTHORS);110 printf("%s %s\n(written by %s)\n\n",LUA_VERSION,LUA_COPYRIGHT,LUA_AUTHORS);
100 else if (IS("-V")) /* verbose */111 else if (IS("-V")) /* verbose */
101 verbose=1;112 verbose=1;
102 else /* unknown option */113 else /* unknown option */
103 usage();114 usage(argv[i]);
104 }115 }
105 --i; /* fake new argv[0] */116 --i; /* fake new argv[0] */
106 argc-=i;117 argc-=i;
107 argv+=i;118 argv+=i;
108 if (dumping || parsing)119 if (dumping || parsing)
109 {120 {
110 if (argc<2) usage();121 if (argc<2) usage(NULL);
111 if (dumping)122 if (dumping)
112 {123 {
113 for (i=1; i<argc; i++) /* play safe with output file */124 for (i=1; i<argc; i++) /* play safe with output file */
114 if (IS(d)) luaL_verror("will not overwrite input file \"%s\"",d);125 if (IS(d)) luaL_verror("will not overwrite input file \"%s\"",d);
115 D=efopen(d,"wb"); /* must open in binary mode */126 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
120 }127 }
121 for (i=1; i<argc; i++) doit(0,IS("-")? NULL : argv[i]);128 for (i=1; i<argc; i++) doit(0,IS("-")? NULL : argv[i]);
122 if (dumping) fclose(D);129 if (dumping) fclose(D);
@@ -134,39 +141,35 @@ int main(int argc, char* argv[]) · 11 unmodified lines
134static void do_compile(ZIO* z)141static void do_compile(ZIO* z)
135{142{
136 TProtoFunc* Main;143 TProtoFunc* Main;
137 if (optimizing) lua_debug=0; /* set debugging before parsing */144 if (optimizing) L->debug=0;
138 if (debugging) lua_debug=1;145 if (debugging) L->debug=1;
139 Main=luaY_parser(z);146 Main=luaY_parser(z);
140 if (optimizing) OptChunk(Main);147 if (optimizing) luaU_optchunk(Main);
141 if (listing) PrintChunk(Main);148 if (listing) luaU_printchunk(Main);
142 if (dumping) DumpChunk(Main,D);149 if (testing) luaU_testchunk(Main);
150 if (dumping) luaU_dumpchunk(Main,D,native);
143}151}
144 152
145static void do_undump(ZIO* z)153static void do_undump(ZIO* z)
146{154{
147 while (1)155 for (;;)
148 {156 {
149 TProtoFunc* Main=luaU_undump1(z);157 TProtoFunc* Main=luaU_undump1(z);
150 if (Main==NULL) break;158 if (Main==NULL) break;
151 if (optimizing) OptChunk(Main);159 if (optimizing) luaU_optchunk(Main);
152 if (listing) PrintChunk(Main);160 if (listing) luaU_printchunk(Main);
161 if (testing) luaU_testchunk(Main);
153 }162 }
154}163}
155 164
156static void doit(int undump, char* filename)165static void doit(int undump, char* filename)
157{166{
158 FILE* f;167 FILE* f= (filename==NULL) ? stdin : efopen(filename, undump ? "rb" : "r");
159 ZIO z;168 ZIO z;
160 if (filename==NULL)169 char source[255+2]; /* +2 for '@' and '\0' */
161 {170 luaL_filesource(source,filename,sizeof(source));
162 f=stdin; filename="(stdin)";171 zFopen(&z,f,source);
163 }172 if (verbose) fprintf(stderr,"%s\n",source+1);
164 else
165 {
166 f=efopen(filename, undump ? "rb" : "r");
167 }
168 zFopen(&z,f,filename);
169 if (verbose) fprintf(stderr,"%s\n",filename);
170 if (undump) do_undump(&z); else do_compile(&z);173 if (undump) do_undump(&z); else do_compile(&z);
171 if (f!=stdin) fclose(f);174 if (f!=stdin) fclose(f);
172}175}
src/luac/luac.h+29−14
@@ -1,11 +1,12 @@
1/*1/*
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 $
3** definitions for luac3** definitions for luac
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
6 6
7#include "lauxlib.h"7#include "lauxlib.h"
8#include "lfunc.h"8#include "lfunc.h"
9#include "lmem.h"
9#include "lobject.h"10#include "lobject.h"
10#include "lopcodes.h"11#include "lopcodes.h"
11#include "lstring.h"12#include "lstring.h"
@@ -13,21 +14,35 @@ · 1 unmodified line
13 14
14typedef struct15typedef struct
15{16{
16 char* name;17 char* name; /* name of opcode */
17 int size;18 int op; /* value of opcode */
18 int op;19 int class; /* class of opcode (byte variant) */
19 int class;20 int args; /* types of arguments (operands) */
20 int arg;21 int arg; /* arg #1 */
21 int arg2;22 int arg2; /* arg #2 */
22} Opcode;23} Opcode;
23 24
24int OpcodeInfo(TProtoFunc* tf, Byte* p, Opcode* I, char* xFILE, int xLINE);25/* from dump.c */
25int CodeSize(TProtoFunc* tf);26void luaU_dumpchunk(TProtoFunc* Main, FILE* D, int native);
26 27
27#define INFO(tf,p,I) OpcodeInfo(tf,p,I,__FILE__,__LINE__)28/* from opcode.c */
28#define fileName(tf) ( (tf->fileName)==NULL ? NULL : tf->fileName->str )29int luaU_opcodeinfo(TProtoFunc* tf, Byte* p, Opcode* I, char* xFILE, int xLINE);
30int luaU_codesize(TProtoFunc* tf);
29 31
32/* from opt.c */
33void luaU_optchunk(TProtoFunc* Main);
34
35/* from print.c */
36void luaU_printchunk(TProtoFunc* Main);
37
38/* from test.c */
39void luaU_testchunk(TProtoFunc* Main);
40TObject* 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 */
30#define NOP 25545#define NOP 255
31#define STACK -146#define STACK (-1)
32#define ARGS -247#define ARGS (-2)
33#define VARARGS -348#define VARARGS (-3)
src/luac/opcode.c+50−35
@@ -1,83 +1,98 @@
1/*1/*
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 $
3** opcode information3** opcode information
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
6 6
7#include "luac.h"7#include "luac.h"
8 8
9enum { /* for Opcode.args */
10 ARGS_NONE,
11 ARGS_B,
12 ARGS_W,
13 ARGS_BB,
14 ARGS_WB
15};
16
9static Opcode Info[]= /* ORDER lopcodes.h */17static Opcode Info[]= /* ORDER lopcodes.h */
10{18{
11#include "opcode.h"19#include "opcode.h"
12};20};
13 21
22static 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
14#define NOPCODES (sizeof(Info)/sizeof(Info[0]))30#define NOPCODES (sizeof(Info)/sizeof(Info[0]))
15 31
16int OpcodeInfo(TProtoFunc* tf, Byte* p, Opcode* I, char* xFILE, int xLINE)32int luaU_opcodeinfo(TProtoFunc* tf, Byte* p, Opcode* I, char* xFILE, int xLINE)
17{33{
18 Opcode OP;34 Opcode OP;
19 Byte* code=tf->code;35 Byte* code=tf->code;
20 int op=*p;36 int op=*p;
21 if (p==code)37 int size=1;
38 if (p==code) /* first byte is STACK */
22 {39 {
23 OP.name="STACK";40 OP=Fake[-STACK];
24 OP.size=1;
25 OP.op=STACK;
26 OP.class=STACK;
27 OP.arg=op;41 OP.arg=op;
28 }42 }
29 else if (p==code+1)43 else if (p==code+1) /* second byte is ARGS or VARARGS */
30 {44 {
31 OP.size=1;45 if (op<ZEROVARARG)
32 if (op>=ZEROVARARG)
33 {46 {
34 OP.name="VARARGS";47 OP=Fake[-ARGS];
35 OP.op=VARARGS;48 OP.arg=op;
36 OP.class=VARARGS;
37 OP.arg=op-ZEROVARARG;
38 }49 }
39 else50 else
40 {51 {
41 OP.name="ARGS";52 OP=Fake[-VARARGS];
42 OP.op=ARGS;53 OP.arg=op-ZEROVARARG;
43 OP.class=ARGS;
44 OP.arg=op;
45 }54 }
46 }55 }
47 else if (op==NOP)56 else if (op==NOP) /* NOP is fake */
48 {57 {
49 OP.name="NOP";58 OP=Fake[0];
50 OP.size=1;
51 OP.op=NOP;
52 OP.class=NOP;
53 }59 }
54 else if (op>=NOPCODES) /* cannot happen */60 else if (op>=NOPCODES) /* cannot happen */
55 {61 {
56 luaL_verror("internal error at %s:%d: bad opcode %d at %d in tf=%p",62 luaL_verror("[%s:%d] bad opcode %d at pc=%d" IN,
57 xFILE, xLINE,op,(int)(p-code),tf);63 xFILE,xLINE,op,(int)(p-code),INLOC);
58 return 0;64 return 0;
59 }65 }
60 else66 else /* ordinary opcode */
61 {67 {
62 OP=Info[op];68 OP=Info[op];
63 if (op==SETLIST || op==CLOSURE || op==CALLFUNC)69 switch (OP.args)
64 {70 {
65 OP.arg=p[1];71 case ARGS_NONE: size=1;
66 OP.arg2=p[2];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;
67 }85 }
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];
71 }86 }
72 *I=OP;87 *I=OP;
73 return OP.size;88 return size;
74}89}
75 90
76int CodeSize(TProtoFunc* tf)91int luaU_codesize(TProtoFunc* tf)
77{92{
78 Byte* code=tf->code;93 Byte* code=tf->code;
79 Byte* p=code;94 Byte* p=code;
80 while (1)95 for (;;)
81 {96 {
82 Opcode OP;97 Opcode OP;
83 p+=INFO(tf,p,&OP);98 p+=INFO(tf,p,&OP);
src/luac/opcode.h+66−130
@@ -1,134 +1,70 @@
1/*1/*
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 $
3** opcode info to be #included into opcode.c3** opcode info to be #included into opcode.c
4** extracted automatically from lopcodes.h by mkopcodeh4** extracted automatically from lopcodes.h by mkopcodeh -- DO NOT EDIT
5** See Copyright Notice in lua.h5** See Copyright Notice in lua.h
6*/6*/
7{ "ENDCODE", 1, ENDCODE, ENDCODE, ENDCODE-ENDCODE-1, 0 },7{ "ENDCODE", ENDCODE, ENDCODE, ARGS_NONE, -1, -1 },
8{ "PUSHNIL", 2, PUSHNIL, PUSHNIL, PUSHNIL-PUSHNIL-1, 0 },8{ "RETCODE", RETCODE, RETCODE, ARGS_B, -1, -1 },
9{ "PUSHNIL0", 1, PUSHNIL0, PUSHNIL, PUSHNIL0-PUSHNIL-1, 0 },9{ "CALL", CALL, CALL, ARGS_BB, -1, -1 },
10{ "PUSHNUMBER", 2, PUSHNUMBER, PUSHNUMBER, PUSHNUMBER-PUSHNUMBER-1, 0 },10{ "TAILCALL", TAILCALL, TAILCALL, ARGS_BB, -1, -1 },
11{ "PUSHNUMBER0", 1, PUSHNUMBER0, PUSHNUMBER, PUSHNUMBER0-PUSHNUMBER-1, 0 },11{ "PUSHNIL", PUSHNIL, PUSHNIL, ARGS_B, -1, -1 },
12{ "PUSHNUMBER1", 1, PUSHNUMBER1, PUSHNUMBER, PUSHNUMBER1-PUSHNUMBER-1, 0 },12{ "POP", POP, POP, ARGS_B, -1, -1 },
13{ "PUSHNUMBER2", 1, PUSHNUMBER2, PUSHNUMBER, PUSHNUMBER2-PUSHNUMBER-1, 0 },13{ "PUSHNUMBERW", PUSHNUMBERW, PUSHNUMBER, ARGS_W, -1, -1 },
14{ "PUSHNUMBERW", 3, PUSHNUMBERW, PUSHNUMBER, PUSHNUMBERW-PUSHNUMBER-1, 0 },14{ "PUSHNUMBER", PUSHNUMBER, PUSHNUMBER, ARGS_B, -1, -1 },
15{ "PUSHCONSTANT", 2, PUSHCONSTANT, PUSHCONSTANT, PUSHCONSTANT-PUSHCONSTANT-1, 0 },15{ "PUSHNUMBERNEGW", PUSHNUMBERNEGW, PUSHNUMBERNEG, ARGS_W, -1, -1 },
16{ "PUSHCONSTANT0", 1, PUSHCONSTANT0, PUSHCONSTANT, PUSHCONSTANT0-PUSHCONSTANT-1, 0 },16{ "PUSHNUMBERNEG", PUSHNUMBERNEG, PUSHNUMBERNEG, ARGS_B, -1, -1 },
17{ "PUSHCONSTANT1", 1, PUSHCONSTANT1, PUSHCONSTANT, PUSHCONSTANT1-PUSHCONSTANT-1, 0 },17{ "PUSHCONSTANTW", PUSHCONSTANTW, PUSHCONSTANT, ARGS_W, -1, -1 },
18{ "PUSHCONSTANT2", 1, PUSHCONSTANT2, PUSHCONSTANT, PUSHCONSTANT2-PUSHCONSTANT-1, 0 },18{ "PUSHCONSTANT", PUSHCONSTANT, PUSHCONSTANT, ARGS_B, -1, -1 },
19{ "PUSHCONSTANT3", 1, PUSHCONSTANT3, PUSHCONSTANT, PUSHCONSTANT3-PUSHCONSTANT-1, 0 },19{ "PUSHUPVALUE", PUSHUPVALUE, PUSHUPVALUE, ARGS_B, -1, -1 },
20{ "PUSHCONSTANT4", 1, PUSHCONSTANT4, PUSHCONSTANT, PUSHCONSTANT4-PUSHCONSTANT-1, 0 },20{ "PUSHLOCAL", PUSHLOCAL, PUSHLOCAL, ARGS_B, -1, -1 },
21{ "PUSHCONSTANT5", 1, PUSHCONSTANT5, PUSHCONSTANT, PUSHCONSTANT5-PUSHCONSTANT-1, 0 },21{ "GETGLOBALW", GETGLOBALW, GETGLOBAL, ARGS_W, -1, -1 },
22{ "PUSHCONSTANT6", 1, PUSHCONSTANT6, PUSHCONSTANT, PUSHCONSTANT6-PUSHCONSTANT-1, 0 },22{ "GETGLOBAL", GETGLOBAL, GETGLOBAL, ARGS_B, -1, -1 },
23{ "PUSHCONSTANT7", 1, PUSHCONSTANT7, PUSHCONSTANT, PUSHCONSTANT7-PUSHCONSTANT-1, 0 },23{ "GETTABLE", GETTABLE, GETTABLE, ARGS_NONE, -1, -1 },
24{ "PUSHCONSTANTW", 3, PUSHCONSTANTW, PUSHCONSTANT, PUSHCONSTANTW-PUSHCONSTANT-1, 0 },24{ "GETDOTTEDW", GETDOTTEDW, GETDOTTED, ARGS_W, -1, -1 },
25{ "PUSHUPVALUE", 2, PUSHUPVALUE, PUSHUPVALUE, PUSHUPVALUE-PUSHUPVALUE-1, 0 },25{ "GETDOTTED", GETDOTTED, GETDOTTED, ARGS_B, -1, -1 },
26{ "PUSHUPVALUE0", 1, PUSHUPVALUE0, PUSHUPVALUE, PUSHUPVALUE0-PUSHUPVALUE-1, 0 },26{ "PUSHSELFW", PUSHSELFW, PUSHSELF, ARGS_W, -1, -1 },
27{ "PUSHUPVALUE1", 1, PUSHUPVALUE1, PUSHUPVALUE, PUSHUPVALUE1-PUSHUPVALUE-1, 0 },27{ "PUSHSELF", PUSHSELF, PUSHSELF, ARGS_B, -1, -1 },
28{ "PUSHLOCAL", 2, PUSHLOCAL, PUSHLOCAL, PUSHLOCAL-PUSHLOCAL-1, 0 },28{ "CREATEARRAYW", CREATEARRAYW, CREATEARRAY, ARGS_W, -1, -1 },
29{ "PUSHLOCAL0", 1, PUSHLOCAL0, PUSHLOCAL, PUSHLOCAL0-PUSHLOCAL-1, 0 },29{ "CREATEARRAY", CREATEARRAY, CREATEARRAY, ARGS_B, -1, -1 },
30{ "PUSHLOCAL1", 1, PUSHLOCAL1, PUSHLOCAL, PUSHLOCAL1-PUSHLOCAL-1, 0 },30{ "SETLOCAL", SETLOCAL, SETLOCAL, ARGS_B, -1, -1 },
31{ "PUSHLOCAL2", 1, PUSHLOCAL2, PUSHLOCAL, PUSHLOCAL2-PUSHLOCAL-1, 0 },31{ "SETGLOBALW", SETGLOBALW, SETGLOBAL, ARGS_W, -1, -1 },
32{ "PUSHLOCAL3", 1, PUSHLOCAL3, PUSHLOCAL, PUSHLOCAL3-PUSHLOCAL-1, 0 },32{ "SETGLOBAL", SETGLOBAL, SETGLOBAL, ARGS_B, -1, -1 },
33{ "PUSHLOCAL4", 1, PUSHLOCAL4, PUSHLOCAL, PUSHLOCAL4-PUSHLOCAL-1, 0 },33{ "SETTABLEPOP", SETTABLEPOP, SETTABLEPOP, ARGS_NONE, -1, -1 },
34{ "PUSHLOCAL5", 1, PUSHLOCAL5, PUSHLOCAL, PUSHLOCAL5-PUSHLOCAL-1, 0 },34{ "SETTABLE", SETTABLE, SETTABLE, ARGS_B, -1, -1 },
35{ "PUSHLOCAL6", 1, PUSHLOCAL6, PUSHLOCAL, PUSHLOCAL6-PUSHLOCAL-1, 0 },35{ "SETLISTW", SETLISTW, SETLIST, ARGS_WB, -1, -1 },
36{ "PUSHLOCAL7", 1, PUSHLOCAL7, PUSHLOCAL, PUSHLOCAL7-PUSHLOCAL-1, 0 },36{ "SETLIST", SETLIST, SETLIST, ARGS_BB, -1, -1 },
37{ "GETGLOBAL", 2, GETGLOBAL, GETGLOBAL, GETGLOBAL-GETGLOBAL-1, 0 },37{ "SETMAP", SETMAP, SETMAP, ARGS_B, -1, -1 },
38{ "GETGLOBAL0", 1, GETGLOBAL0, GETGLOBAL, GETGLOBAL0-GETGLOBAL-1, 0 },38{ "NEQOP", NEQOP, NEQOP, ARGS_NONE, -1, -1 },
39{ "GETGLOBAL1", 1, GETGLOBAL1, GETGLOBAL, GETGLOBAL1-GETGLOBAL-1, 0 },39{ "EQOP", EQOP, EQOP, ARGS_NONE, -1, -1 },
40{ "GETGLOBAL2", 1, GETGLOBAL2, GETGLOBAL, GETGLOBAL2-GETGLOBAL-1, 0 },40{ "LTOP", LTOP, LTOP, ARGS_NONE, -1, -1 },
41{ "GETGLOBAL3", 1, GETGLOBAL3, GETGLOBAL, GETGLOBAL3-GETGLOBAL-1, 0 },41{ "LEOP", LEOP, LEOP, ARGS_NONE, -1, -1 },
42{ "GETGLOBAL4", 1, GETGLOBAL4, GETGLOBAL, GETGLOBAL4-GETGLOBAL-1, 0 },42{ "GTOP", GTOP, GTOP, ARGS_NONE, -1, -1 },
43{ "GETGLOBAL5", 1, GETGLOBAL5, GETGLOBAL, GETGLOBAL5-GETGLOBAL-1, 0 },43{ "GEOP", GEOP, GEOP, ARGS_NONE, -1, -1 },
44{ "GETGLOBAL6", 1, GETGLOBAL6, GETGLOBAL, GETGLOBAL6-GETGLOBAL-1, 0 },44{ "ADDOP", ADDOP, ADDOP, ARGS_NONE, -1, -1 },
45{ "GETGLOBAL7", 1, GETGLOBAL7, GETGLOBAL, GETGLOBAL7-GETGLOBAL-1, 0 },45{ "SUBOP", SUBOP, SUBOP, ARGS_NONE, -1, -1 },
46{ "GETGLOBALW", 3, GETGLOBALW, GETGLOBAL, GETGLOBALW-GETGLOBAL-1, 0 },46{ "MULTOP", MULTOP, MULTOP, ARGS_NONE, -1, -1 },
47{ "GETTABLE", 1, GETTABLE, GETTABLE, GETTABLE-GETTABLE-1, 0 },47{ "DIVOP", DIVOP, DIVOP, ARGS_NONE, -1, -1 },
48{ "GETDOTTED", 2, GETDOTTED, GETDOTTED, GETDOTTED-GETDOTTED-1, 0 },48{ "POWOP", POWOP, POWOP, ARGS_NONE, -1, -1 },
49{ "GETDOTTED0", 1, GETDOTTED0, GETDOTTED, GETDOTTED0-GETDOTTED-1, 0 },49{ "CONCOP", CONCOP, CONCOP, ARGS_NONE, -1, -1 },
50{ "GETDOTTED1", 1, GETDOTTED1, GETDOTTED, GETDOTTED1-GETDOTTED-1, 0 },50{ "MINUSOP", MINUSOP, MINUSOP, ARGS_NONE, -1, -1 },
51{ "GETDOTTED2", 1, GETDOTTED2, GETDOTTED, GETDOTTED2-GETDOTTED-1, 0 },51{ "NOTOP", NOTOP, NOTOP, ARGS_NONE, -1, -1 },
52{ "GETDOTTED3", 1, GETDOTTED3, GETDOTTED, GETDOTTED3-GETDOTTED-1, 0 },52{ "ONTJMPW", ONTJMPW, ONTJMP, ARGS_W, -1, -1 },
53{ "GETDOTTED4", 1, GETDOTTED4, GETDOTTED, GETDOTTED4-GETDOTTED-1, 0 },53{ "ONTJMP", ONTJMP, ONTJMP, ARGS_B, -1, -1 },
54{ "GETDOTTED5", 1, GETDOTTED5, GETDOTTED, GETDOTTED5-GETDOTTED-1, 0 },54{ "ONFJMPW", ONFJMPW, ONFJMP, ARGS_W, -1, -1 },
55{ "GETDOTTED6", 1, GETDOTTED6, GETDOTTED, GETDOTTED6-GETDOTTED-1, 0 },55{ "ONFJMP", ONFJMP, ONFJMP, ARGS_B, -1, -1 },
56{ "GETDOTTED7", 1, GETDOTTED7, GETDOTTED, GETDOTTED7-GETDOTTED-1, 0 },56{ "JMPW", JMPW, JMP, ARGS_W, -1, -1 },
57{ "GETDOTTEDW", 3, GETDOTTEDW, GETDOTTED, GETDOTTEDW-GETDOTTED-1, 0 },57{ "JMP", JMP, JMP, ARGS_B, -1, -1 },
58{ "PUSHSELF", 2, PUSHSELF, PUSHSELF, PUSHSELF-PUSHSELF-1, 0 },58{ "IFFJMPW", IFFJMPW, IFFJMP, ARGS_W, -1, -1 },
59{ "PUSHSELF0", 1, PUSHSELF0, PUSHSELF, PUSHSELF0-PUSHSELF-1, 0 },59{ "IFFJMP", IFFJMP, IFFJMP, ARGS_B, -1, -1 },
60{ "PUSHSELF1", 1, PUSHSELF1, PUSHSELF, PUSHSELF1-PUSHSELF-1, 0 },60{ "IFTUPJMPW", IFTUPJMPW, IFTUPJMP, ARGS_W, -1, -1 },
61{ "PUSHSELF2", 1, PUSHSELF2, PUSHSELF, PUSHSELF2-PUSHSELF-1, 0 },61{ "IFTUPJMP", IFTUPJMP, IFTUPJMP, ARGS_B, -1, -1 },
62{ "PUSHSELF3", 1, PUSHSELF3, PUSHSELF, PUSHSELF3-PUSHSELF-1, 0 },62{ "IFFUPJMPW", IFFUPJMPW, IFFUPJMP, ARGS_W, -1, -1 },
63{ "PUSHSELF4", 1, PUSHSELF4, PUSHSELF, PUSHSELF4-PUSHSELF-1, 0 },63{ "IFFUPJMP", IFFUPJMP, IFFUPJMP, ARGS_B, -1, -1 },
64{ "PUSHSELF5", 1, PUSHSELF5, PUSHSELF, PUSHSELF5-PUSHSELF-1, 0 },64{ "CLOSUREW", CLOSUREW, CLOSURE, ARGS_WB, -1, -1 },
65{ "PUSHSELF6", 1, PUSHSELF6, PUSHSELF, PUSHSELF6-PUSHSELF-1, 0 },65{ "CLOSURE", CLOSURE, CLOSURE, ARGS_BB, -1, -1 },
66{ "PUSHSELF7", 1, PUSHSELF7, PUSHSELF, PUSHSELF7-PUSHSELF-1, 0 },66{ "SETLINEW", SETLINEW, SETLINE, ARGS_W, -1, -1 },
67{ "PUSHSELFW", 3, PUSHSELFW, PUSHSELF, PUSHSELFW-PUSHSELF-1, 0 },67{ "SETLINE", SETLINE, SETLINE, ARGS_B, -1, -1 },
68{ "CREATEARRAY", 2, CREATEARRAY, CREATEARRAY, CREATEARRAY-CREATEARRAY-1, 0 },68{ "LONGARGW", LONGARGW, LONGARG, ARGS_W, -1, -1 },
69{ "CREATEARRAY0", 1, CREATEARRAY0, CREATEARRAY, CREATEARRAY0-CREATEARRAY-1, 0 },69{ "LONGARG", LONGARG, LONGARG, ARGS_B, -1, -1 },
70{ "CREATEARRAY1", 1, CREATEARRAY1, CREATEARRAY, CREATEARRAY1-CREATEARRAY-1, 0 },70{ "CHECKSTACK", CHECKSTACK, CHECKSTACK, ARGS_B, -1, -1 },
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 },
src/luac/opt.c+147−94
@@ -1,70 +1,126 @@
1/*1/*
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 $
3** optimize bytecodes3** optimize bytecodes
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
6 6
7#include <stdio.h>7#include <stdio.h>
8#include <stdlib.h>8#include <stdlib.h>
9#include <string.h>
9#include "luac.h"10#include "luac.h"
10#include "lmem.h"11
12static 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}
11 39
12static void FixConstants(TProtoFunc* tf, int* C)40static void FixConstants(TProtoFunc* tf, int* C)
13{41{
14 Byte* code=tf->code;42 Byte* code=tf->code;
15 Byte* p=code;43 Byte* p=code;
16 while (1)44 int longarg=0;
45 for (;;)
17 {46 {
18 Opcode OP;47 Opcode OP;
19 int n=INFO(tf,p,&OP);48 int n=INFO(tf,p,&OP);
20 int op=OP.class;49 int op=OP.class;
21 int i=OP.arg;50 int i=OP.arg+longarg;
22 if (op==ENDCODE) break;51 longarg=0;
23 if ( op==PUSHCONSTANT || op==GETDOTTED || op==PUSHSELF ||52 if (op==PUSHCONSTANT || op==GETGLOBAL || op==GETDOTTED ||
24 op==GETGLOBAL || op==SETGLOBAL)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
64static 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)
25 {79 {
26 int j=C[i];80 TObject* o=tf->consts+i;
27 if (j==i)81 if (ttype(o)<=0) ttype(o)+=BIAS; /* mark as used */
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 }
51 }82 }
83 else if (op==LONGARG) longarg=i<<16;
84 else if (op==ENDCODE) break;
52 p+=n;85 p+=n;
53 }86 }
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 }
54}95}
55 96
56static TProtoFunc* TF;97#define CMP(oa,ob,f) memcmp(&f(oa),&f(ob),sizeof(f(oa)))
57 98
58static int compare(const void* a, const void *b)99static 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
116static TProtoFunc* TF; /* for sort */
117
118static int compare1(const void* a, const void* b)
59{119{
60 int ia=*(int*)a;120 int ia=*(int*)a;
61 int ib=*(int*)b;121 int ib=*(int*)b;
62 int t;122 int t=compare(TF,ia,ib);
63 TObject* oa=TF->consts+ia;123 return (t) ? t : ia-ib;
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;
68}124}
69 125
70static void OptConstants(TProtoFunc* tf)126static void OptConstants(TProtoFunc* tf)
@@ -74,43 +130,60 @@ static void OptConstants(TProtoFunc* tf) · 3 unmodified lines
74 int i,k;130 int i,k;
75 int n=tf->nconsts;131 int n=tf->nconsts;
76 if (n==0) return;132 if (n==0) return;
77 C=luaM_reallocvector(C,n,int);133 luaM_reallocvector(C,n,int);
78 D=luaM_reallocvector(D,n,int);134 luaM_reallocvector(D,n,int);
135 NoUnrefs(tf);
79 for (i=0; i<n; i++) C[i]=D[i]=i; /* group duplicates */136 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);
81 k=C[0]; /* build duplicate table */138 k=C[0]; /* build duplicate table */
82 for (i=1; i<n; i++)139 for (i=1; i<n; i++)
83 {140 {
84 int j=C[i];141 int j=C[i];
85 TObject* oa=tf->consts+k;142 if (compare(tf,k,j)==0) D[j]=k; else k=j;
86 TObject* ob=tf->consts+j;
87 if (ttype(oa)==ttype(ob) && oa->value.i==ob->value.i) D[j]=k; else k=j;
88 }143 }
89 k=0; /* build rename map & pack constants */144 k=0; /* build rename map & pack constants */
90 for (i=0; i<n; i++)145 for (i=0; i<n; i++)
91 {146 {
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 {
160printf("\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;
93 }164 }
94 if (k>=n) return;
95printf("\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);
99}165}
100 166
101static int NoDebug(TProtoFunc* tf)167static int NoDebug(TProtoFunc* tf)
102{168{
103 Byte* code=tf->code;169 Byte* code=tf->code;
104 Byte* p=code;170 Byte* p=code;
171 int lop=NOP; /* last opcode */
105 int nop=0;172 int nop=0;
106 while (1) /* change SETLINE to NOP */173 for (;;) /* change SETLINE to NOP */
107 {174 {
108 Opcode OP;175 Opcode OP;
109 int n=INFO(tf,p,&OP);176 int n=INFO(tf,p,&OP);
110 int op=OP.class;177 int op=OP.class;
111 if (op==ENDCODE) break;
112 if (op==NOP) ++nop;178 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;
114 p+=n;187 p+=n;
115 }188 }
116 return nop;189 return nop;
@@ -125,8 +198,8 @@ static int FixJump(TProtoFunc* tf, Byte* a, Byte* b) · 8 unmodified lines
125 Opcode OP;198 Opcode OP;
126 int n=INFO(tf,p,&OP);199 int n=INFO(tf,p,&OP);
127 int op=OP.class;200 int op=OP.class;
128 if (op==ENDCODE) break;
129 if (op==NOP) ++nop;201 if (op==NOP) ++nop;
202 else if (op==ENDCODE) break;
130 p+=n;203 p+=n;
131 }204 }
132 return nop;205 return nop;
@@ -136,42 +209,22 @@ static void FixJumps(TProtoFunc* tf) · 3 unmodified lines
136{209{
137 Byte* code=tf->code;210 Byte* code=tf->code;
138 Byte* p=code;211 Byte* p=code;
139 while (1)212 int longarg=0;
213 for (;;)
140 {214 {
141 Opcode OP;215 Opcode OP;
142 int n=INFO(tf,p,&OP);216 int n=INFO(tf,p,&OP);
143 int op=OP.class;217 int op=OP.class;
144 int i=OP.arg;218 int i=OP.arg+longarg;
145 int nop;219 int nop=0;
220 longarg=0;
146 if (op==ENDCODE) break;221 if (op==ENDCODE) break;
147 nop=0;222 else if (op==IFTUPJMP || op==IFFUPJMP)
148 if (op==IFTUPJMP || op==IFFUPJMP) nop=FixJump(tf,p-i+n,p); else223 nop=FixJump(tf,p-i+n,p);
149 if (op==ONTJMP || op==ONFJMP || op==JMP || op==IFFJMP) nop=FixJump(tf,p,p+i+n);224 else if (op==ONTJMP || op==ONFJMP || op==JMP || op==IFFJMP)
150 if (nop>0)225 nop=FixJump(tf,p,p+i+n);
151 {226 else if (op==LONGARG) longarg=i<<16;
152 int j=i-nop;227 if (nop>0) FixArg(p,i,i-nop,0);
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 }
175 p+=n;228 p+=n;
176 }229 }
177}230}
@@ -181,7 +234,7 @@ static void PackCode(TProtoFunc* tf) · 3 unmodified lines
181 Byte* code=tf->code;234 Byte* code=tf->code;
182 Byte* p=code;235 Byte* p=code;
183 Byte* q=code;236 Byte* q=code;
184 while (1)237 for (;;)
185 {238 {
186 Opcode OP;239 Opcode OP;
187 int n=INFO(tf,p,&OP);240 int n=INFO(tf,p,&OP);
@@ -190,14 +243,13 @@ static void PackCode(TProtoFunc* tf) · 2 unmodified lines
190 p+=n;243 p+=n;
191 if (op==ENDCODE) break;244 if (op==ENDCODE) break;
192 }245 }
193printf("\t\"%s\":%d reduced code from %d to %d\n",246printf("\t" SOURCE " reduced code from %d to %d\n",
194 tf->fileName->str,tf->lineDefined,(int)(p-code),(int)(q-code));247 tf->source->str,tf->lineDefined,(int)(p-code),(int)(q-code));
195}248}
196 249
197static void OptCode(TProtoFunc* tf)250static void OptCode(TProtoFunc* tf)
198{251{
199 int nop=NoDebug(tf);252 if (NoDebug(tf)==0) return; /* cannot improve code */
200 if (nop==0) return; /* cannot improve code */
201 FixJumps(tf);253 FixJumps(tf);
202 PackCode(tf);254 PackCode(tf);
203}255}
@@ -216,13 +268,14 @@ static void OptFunctions(TProtoFunc* tf) · 12 unmodified lines
216 268
217static void OptFunction(TProtoFunc* tf)269static void OptFunction(TProtoFunc* tf)
218{270{
219 tf->locvars=NULL; /* remove local variables table */
220 OptConstants(tf);271 OptConstants(tf);
221 OptCode(tf);272 OptCode(tf);
222 OptFunctions(tf);273 OptFunctions(tf);
274 tf->source=luaS_new("");
275 tf->locvars=NULL;
223}276}
224 277
225void OptChunk(TProtoFunc* Main)278void luaU_optchunk(TProtoFunc* Main)
226{279{
227 OptFunction(Main);280 OptFunction(Main);
228}281}
src/luac/print.c+86−96
@@ -1,5 +1,5 @@
1/*1/*
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 $
3** print bytecodes3** print bytecodes
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -9,88 +9,81 @@ · 3 unmodified lines
9#include "luac.h"9#include "luac.h"
10 10
11#ifdef DEBUG11#ifdef DEBUG
12void 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
36static void PrintConstants(TProtoFunc* tf)12static void PrintConstants(TProtoFunc* tf)
37{13{
38 int i,n=tf->nconsts;14 int i,n=tf->nconsts;
39 printf("constants (%d):\n",n);15 printf("constants (%d) for %p:\n",n,tf);
40 for (i=0; i<n; i++) PrintConstant1(tf,i);16 for (i=0; i<n; i++)
41}
42#endif
43
44static 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
49 {17 {
50 TObject* o=tf->consts+i;18 TObject* o=tf->consts+i;
19 printf("%6d ",i);
51 switch (ttype(o))20 switch (ttype(o))
52 {21 {
53 case LUA_T_NUMBER:22 case LUA_T_NUMBER:
54 printf(NUMBER_FMT,nvalue(o)); /* LUA_NUMBER */23 printf("N " NUMBER_FMT "\n",(double)nvalue(o));
55 break;24 break;
56 case LUA_T_STRING:25 case LUA_T_STRING:
57 printf("\"%s\"",svalue(o));26 printf("S %p\t\"%s\"\n",tsvalue(o),svalue(o));
58 break;27 break;
59 case LUA_T_PROTO:28 case LUA_T_PROTO:
60 printf("function at %p",(void*)tfvalue(o));29 printf("F %p\n",tfvalue(o));
61 break;30 break;
62 case LUA_T_NIL:31 case LUA_T_NIL:
63 printf("(nil)");32 printf("nil\n");
64 break;33 break;
65 default: /* cannot happen */34 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));
67 break;36 break;
68 }37 }
69 }38 }
70}39}
40#endif
71 41
72#define VarStr(i) svalue(tf->consts+i)42static 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}
73 64
74static void PrintCode(TProtoFunc* tf)65static void PrintCode(TProtoFunc* tf)
75{66{
76 Byte* code=tf->code;67 Byte* code=tf->code;
77 Byte* p=code;68 Byte* p=code;
78 int line=0;69 int line=0;
79 while (1)70 int longarg=0;
71 for (;;)
80 {72 {
81 Opcode OP;73 Opcode OP;
82 int n=INFO(tf,p,&OP);74 int n=INFO(tf,p,&OP);
83 int op=OP.op;75 int i=OP.arg+longarg;
84 int i=OP.arg;76 int at=p-code;
85 printf("%6d ",(int)(p-code));77 longarg=0;
78 printf("%6d ",at);
86 {79 {
87 Byte* q=p;80 Byte* q=p;
88 int j=n;81 int j=n;
89 while (j--) printf("%02X",*q++);82 while (j--) printf("%02X",*q++);
90 }83 }
91 printf("%*s%-13s",2*(5-n),"",OP.name);84 printf("%*s%-14s ",2*(5-n),"",OP.name);
92 85 if (OP.arg >=0) printf("%d",i);
93 if (n!=1 || op<0) printf("\t%d",i); else if (i>=0) printf("\t");86 if (OP.arg2>=0) printf(" %d",OP.arg2);
94 87
95 switch (OP.class)88 switch (OP.class)
96 {89 {
@@ -99,13 +92,14 @@ static void PrintCode(TProtoFunc* tf) · 2 unmodified lines
99 printf("\n");92 printf("\n");
100 return;93 return;
101 94
102 case CLOSURE:
103 printf(" %d",OP.arg2);
104 case PUSHCONSTANT:95 case PUSHCONSTANT:
96 case GETGLOBAL:
97 case SETGLOBAL:
105 case GETDOTTED:98 case GETDOTTED:
106 case PUSHSELF:99 case PUSHSELF:
100 case CLOSURE:
107 printf("\t; ");101 printf("\t; ");
108 PrintConstant(tf,i);102 PrintConstant(tf,i,at);
109 break;103 break;
110 104
111 case PUSHLOCAL:105 case PUSHLOCAL:
@@ -116,29 +110,24 @@ static void PrintCode(TProtoFunc* tf) · 4 unmodified lines
116 break;110 break;
117 }111 }
118 112
119 case GETGLOBAL:113 case SETLINE:
120 case SETGLOBAL:114 printf("\t; " SOURCE,tf->source->str,line=i);
121 printf("\t; %s",VarStr(i));
122 break;
123
124 case SETLIST:
125 case CALLFUNC:
126 if (n>=3) printf(" %d",OP.arg2);
127 break;115 break;
128 116
129 case SETLINE:117 case LONGARG:
130 printf("\t; \"%s\":%d",fileName(tf),line=i);118 longarg=i<<16;
131 break;119 break;
132 120
133/* suggested by Norman Ramsey <nr@cs.virginia.edu> */121/* suggested by Norman Ramsey <nr@cs.virginia.edu> */
134 case IFTUPJMP:
135 case IFFUPJMP:
136 i=-i;
137 case ONTJMP:122 case ONTJMP:
138 case ONFJMP:123 case ONFJMP:
139 case JMP:124 case JMP:
140 case IFFJMP:125 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);
142 break;131 break;
143 132
144 }133 }
@@ -150,47 +139,44 @@ static void PrintCode(TProtoFunc* tf) · 5 unmodified lines
150static void PrintLocals(TProtoFunc* tf)139static void PrintLocals(TProtoFunc* tf)
151{140{
152 LocVar* v=tf->locvars;141 LocVar* v=tf->locvars;
153 int n,i=0;142 int n,i;
154 if (v==NULL || v->varname==NULL) return;143 if (v==NULL || v->line<0) return;
155 n=tf->code[1]; if (n>=ZEROVARARG) n-=ZEROVARARG;144 n=tf->code[1]; if (n>=ZEROVARARG) n-=ZEROVARARG;
156
157 printf("locals:");145 printf("locals:");
158 if (n>0)146 for (i=0; i<n; v++,i++) /* arguments */
159 {147 printf(" %s",v->varname->str);
160 for (i=0; i<n; v++,i++) printf(" %s",v->varname->str);148 for (; v->line>=0; v++)
161 }
162 if (v->varname!=NULL)
163 {149 {
164 for (; v->line>=0; v++)150 if (v->varname==NULL)
165 {151 {
166 if (v->varname==NULL)152 --i; if (i<0) luaL_verror("bad locvars[%d]",v-tf->locvars); else printf(")");
167 {153 }
168 printf(")"); --i;154 else
169 }155 {
170 else156 ++i; printf(" (%s",v->varname->str);
171 {
172 printf(" (%s",v->varname->str); i++;
173 }
174 }157 }
175 i-=n;
176 while (i--) printf(")");
177 }158 }
159 i-=n;
160 while (i--) printf(")");
178 printf("\n");161 printf("\n");
179}162}
180 163
164#define IsMain(tf) (tf->lineDefined==0)
165
181static void PrintHeader(TProtoFunc* tf, TProtoFunc* Main, int at)166static void PrintHeader(TProtoFunc* tf, TProtoFunc* Main, int at)
182{167{
183 int size=CodeSize(tf);168 int size=luaU_codesize(tf);
184 if (IsMain(tf))169 if (IsMain(tf))
185 printf("\nmain of \"%s\" (%d bytes at %p)\n",fileName(tf),size,(void*)tf);170 printf("\nmain " SOURCE " (%d bytes at %p)\n",
186 else if (Main)171 tf->source->str,tf->lineDefined,size,tf);
172 else
187 {173 {
188 printf("\nfunction defined at \"%s\":%d (%d bytes at %p); used at ",174 printf("\nfunction " SOURCE " (%d bytes at %p); used at ",
189 fileName(tf),tf->lineDefined,size,(void*)tf);175 tf->source->str,tf->lineDefined,size,tf);
190 if (IsMain(Main))176 if (Main && IsMain(Main))
191 printf("main");177 printf("main");
192 else178 else
193 printf("%p",(void*)Main);179 printf("%p",Main);
194 printf("+%d\n",at);180 printf("+%d\n",at);
195 }181 }
196}182}
@@ -201,17 +187,21 @@ static void PrintFunctions(TProtoFunc* Main) · 4 unmodified lines
201{187{
202 Byte* code=Main->code;188 Byte* code=Main->code;
203 Byte* p=code;189 Byte* p=code;
204 while (1)190 int longarg=0;
191 for (;;)
205 {192 {
206 Opcode OP;193 Opcode OP;
207 int n=INFO(Main,p,&OP);194 int n=INFO(Main,p,&OP);
208 if (OP.class==ENDCODE) break;195 int op=OP.class;
209 if (OP.class==PUSHCONSTANT || OP.class==CLOSURE)196 int i=OP.arg+longarg;
197 longarg=0;
198 if (op==PUSHCONSTANT || op==CLOSURE)
210 {199 {
211 int i=OP.arg;
212 TObject* o=Main->consts+i;200 TObject* o=Main->consts+i;
213 if (ttype(o)==LUA_T_PROTO) PrintFunction(tfvalue(o),Main,(int)(p-code));201 if (ttype(o)==LUA_T_PROTO) PrintFunction(tfvalue(o),Main,(int)(p-code));
214 }202 }
203 else if (op==LONGARG) longarg=i<<16;
204 else if (op==ENDCODE) break;
215 p+=n;205 p+=n;
216 }206 }
217}207}
@@ -227,7 +217,7 @@ static void PrintFunction(TProtoFunc* tf, TProtoFunc* Main, int at) · 9 unmodified lines
227 PrintFunctions(tf);217 PrintFunctions(tf);
228}218}
229 219
230void PrintChunk(TProtoFunc* Main)220void luaU_printchunk(TProtoFunc* Main)
231{221{
232 PrintFunction(Main,0,0);222 PrintFunction(Main,0,0);
233}223}
src/luac/stubs.c+72−19
@@ -1,9 +1,17 @@
1/*1/*
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 $
3** avoid runtime modules in luac3** avoid runtime modules in luac
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
6 6
7#ifdef NOSTUBS
8
9/* according to gcc, ANSI C forbids an empty source file */
10void luaU_dummy(void);
11void luaU_dummy(void){}
12
13#else
14
7#include <stdarg.h>15#include <stdarg.h>
8#include <stdio.h>16#include <stdio.h>
9#include <stdlib.h>17#include <stdlib.h>
@@ -22,32 +30,34 @@ void lua_error(char* s) · 12 unmodified lines
22}30}
23 31
24/* copied from lauxlib.c */32/* copied from lauxlib.c */
25void luaL_verror(char* fmt, ...)33void luaL_verror (char *fmt, ...)
26{34{
27 char buff[500];35 char buff[500];
28 va_list argp;36 va_list argp;
29 va_start(argp,fmt);37 va_start(argp, fmt);
30 vsprintf(buff,fmt,argp);38 vsprintf(buff, fmt, argp);
31 va_end(argp);39 va_end(argp);
32 lua_error(buff);40 lua_error(buff);
33}41}
34 42
35/* copied from lauxlib.c */43/* copied from lauxlib.c */
36int luaL_findstring (char* name, char* list[])44void luaL_filesource (char *out, char *filename, int len) {
37{45 if (filename == NULL) filename = "(stdin)";
38 int i;46 sprintf(out, "@%.*s", len-2, filename); /* -2 for '@' and '\0' */
39 for (i=0; list[i]; i++)
40 if (strcmp(list[i], name) == 0)
41 return i;
42 return -1;
43}47}
44 48
45/* avoid runtime modules in lstate.c */49/* 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
46void luaB_predefine(void){}57void luaB_predefine(void){}
47void luaC_hashcallIM(Hash *l){}58void luaC_hashcallIM(Hash *l){}
48void luaC_strcallIM(TaggedString *l){}59void luaC_strcallIM(TaggedString *l){}
49void luaD_gcIM(TObject *o){}60void luaD_gcIM(TObject *o){}
50void luaD_init(void){}
51void luaH_free(Hash *frees){}61void luaH_free(Hash *frees){}
52void luaT_init(void){}62void luaT_init(void){}
53 63
@@ -59,10 +69,53 @@ void luaT_init(void){} · 5 unmodified lines
59 69
60#ifdef NOPARSER70#ifdef NOPARSER
61 71
62int lua_debug=0;72#include "llex.h"
73#include "lparser.h"
63 74
64void luaX_init(void){}75void luaX_init(void){}
65void luaY_init(void){}76void luaD_init(void){}
66void luaY_parser(void) { lua_error("parser not loaded"); }77
78TProtoFunc* luaY_parser(ZIO *z) {
79 lua_error("parser not loaded");
80 return NULL;
81}
82
83#else
67 84
85/* copied from lauxlib.c */
86int 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 */
95void 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
109void luaD_checkstack(int n){}
110
111#define STACK_UNIT 128
112
113/* copied from ldo.c */
114void 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
68#endif121#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
17TObject* 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
23static 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
35static 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
43static 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
158static 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
183static 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]"
196static 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
217static void TestFunction(TProtoFunc* tf);
218
219static 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
243static void TestFunction(TProtoFunc* tf)
244{
245 TestCode(tf);
246 TestLocals(tf);
247 TestConstants(tf);
248}
249
250void luaU_testchunk(TProtoFunc* Main)
251{
252 TestFunction(Main);
253}
src/lundump.c+91−80
@@ -1,5 +1,5 @@
1/*1/*
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 $
3** load bytecodes from files3** load bytecodes from files
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -9,99 +9,96 @@ · 3 unmodified lines
9#include "lauxlib.h"9#include "lauxlib.h"
10#include "lfunc.h"10#include "lfunc.h"
11#include "lmem.h"11#include "lmem.h"
12#include "lopcodes.h"
12#include "lstring.h"13#include "lstring.h"
13#include "lundump.h"14#include "lundump.h"
14 15
15#define LoadBlock(b,size,Z) ezread(Z,b,size)16#define LoadBlock(b,size,Z) ezread(Z,b,size)
16#define LoadNative(t,Z) LoadBlock(&t,sizeof(t),Z)
17 17
18#if ID_NUMBER==ID_NATIVE18static void unexpectedEOZ (ZIO* Z)
19 #define doLoadNumber(f,Z) LoadNative(f,Z)
20#else
21 #define doLoadNumber(f,Z) f=LoadNumber(Z)
22#endif
23
24static void unexpectedEOZ(ZIO* Z)
25{19{
26 luaL_verror("unexpected end of file in %s",zname(Z));20 luaL_verror("unexpected end of file in %s",zname(Z));
27}21}
28 22
29static int ezgetc(ZIO* Z)23static int ezgetc (ZIO* Z)
30{24{
31 int c=zgetc(Z);25 int c=zgetc(Z);
32 if (c==EOZ) unexpectedEOZ(Z);26 if (c==EOZ) unexpectedEOZ(Z);
33 return c;27 return c;
34}28}
35 29
36static void ezread(ZIO* Z, void* b, int n)30static void ezread (ZIO* Z, void* b, int n)
37{31{
38 int r=zread(Z,b,n);32 int r=zread(Z,b,n);
39 if (r!=0) unexpectedEOZ(Z);33 if (r!=0) unexpectedEOZ(Z);
40}34}
41 35
42static unsigned int LoadWord(ZIO* Z)36static unsigned int LoadWord (ZIO* Z)
43{37{
44 unsigned int hi=ezgetc(Z);38 unsigned int hi=ezgetc(Z);
45 unsigned int lo=ezgetc(Z);39 unsigned int lo=ezgetc(Z);
46 return (hi<<8)|lo;40 return (hi<<8)|lo;
47}41}
48 42
49static unsigned long LoadLong(ZIO* Z)43static unsigned long LoadLong (ZIO* Z)
50{44{
51 unsigned long hi=LoadWord(Z);45 unsigned long hi=LoadWord(Z);
52 unsigned long lo=LoadWord(Z);46 unsigned long lo=LoadWord(Z);
53 return (hi<<16)|lo;47 return (hi<<16)|lo;
54}48}
55 49
56#if ID_NUMBER==ID_REAL450/*
57/* LUA_NUMBER */51* convert number from text
58/* assumes sizeof(long)==4 and sizeof(float)==4 (IEEE) */52*/
59static float LoadFloat(ZIO* Z)53double luaU_str2d (char* b, char* where)
60{54{
61 unsigned long l=LoadLong(Z);55 int negative=(b[0]=='-');
62 float f;56 double x=luaO_str2d(b+negative);
63 memcpy(&f,&l,sizeof(f));57 if (x<0) luaL_verror("cannot convert number '%s' in %s",b,where);
64 return f;58 return negative ? -x : x;
65}59}
66#endif
67 60
68#if ID_NUMBER==ID_REAL861static real LoadNumber (ZIO* Z, int native)
69/* LUA_NUMBER */
70/* assumes sizeof(long)==4 and sizeof(double)==8 (IEEE) */
71static double LoadDouble(ZIO* Z)
72{62{
73 unsigned long l[2];63 real x;
74 double f;64 if (native)
75 int x=1;
76 if (*(char*)&x==1) /* little-endian */
77 {65 {
78 l[1]=LoadLong(Z);66 LoadBlock(&x,sizeof(x),Z);
79 l[0]=LoadLong(Z);67 return x;
80 }68 }
81 else /* big-endian */69 else
82 {70 {
83 l[0]=LoadLong(Z);71 char b[256];
84 l[1]=LoadLong(Z);72 int size=ezgetc(Z);
73 LoadBlock(b,size,Z);
74 b[size]=0;
75 return luaU_str2d(b,zname(Z));
85 }76 }
86 memcpy(&f,l,sizeof(f));
87 return f;
88}77}
89#endif
90 78
91static Byte* LoadCode(ZIO* Z)79static int LoadInt (ZIO* Z, char* message)
92{80{
93 unsigned long size=LoadLong(Z);81 unsigned long l=LoadLong(Z);
94 unsigned int s=size;82 unsigned int i=l;
95 void* b;83 if (i!=l) luaL_verror(message,l,zname(Z));
96 if (s!=size) luaL_verror("code too long (%ld bytes) in %s",size,zname(Z));84 return i;
97 b=luaM_malloc(size);85}
86
87#define PAD 5 /* two word operands plus opcode */
88
89static Byte* LoadCode (ZIO* Z)
90{
91 int size=LoadInt(Z,"code too long (%ld bytes) in %s");
92 Byte* b=luaM_malloc(size+PAD);
98 LoadBlock(b,size,Z);93 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 */
99 return b;96 return b;
100}97}
101 98
102static TaggedString* LoadTString(ZIO* Z)99static TaggedString* LoadTString (ZIO* Z)
103{100{
104 int size=LoadWord(Z);101 long size=LoadLong(Z);
105 if (size==0)102 if (size==0)
106 return NULL;103 return NULL;
107 else104 else
@@ -112,65 +109,65 @@ static TaggedString* LoadTString(ZIO* Z) · 4 unmodified lines
112 }109 }
113}110}
114 111
115static void LoadLocals(TProtoFunc* tf, ZIO* Z)112static void LoadLocals (TProtoFunc* tf, ZIO* Z)
116{113{
117 int i,n=LoadWord(Z);114 int i,n=LoadInt(Z,"too many locals (%ld) in %s");
118 if (n==0) return;115 if (n==0) return;
119 tf->locvars=luaM_newvector(n+1,LocVar);116 tf->locvars=luaM_newvector(n+1,LocVar);
120 for (i=0; i<n; i++)117 for (i=0; i<n; i++)
121 {118 {
122 tf->locvars[i].line=LoadWord(Z);119 tf->locvars[i].line=LoadInt(Z,"too many lines (%ld) in %s");
123 tf->locvars[i].varname=LoadTString(Z);120 tf->locvars[i].varname=LoadTString(Z);
124 }121 }
125 tf->locvars[i].line=-1; /* flag end of vector */122 tf->locvars[i].line=-1; /* flag end of vector */
126 tf->locvars[i].varname=NULL;123 tf->locvars[i].varname=NULL;
127}124}
128 125
129static TProtoFunc* LoadFunction(ZIO* Z);126static TProtoFunc* LoadFunction (ZIO* Z, int native);
130 127
131static void LoadConstants(TProtoFunc* tf, ZIO* Z)128static void LoadConstants (TProtoFunc* tf, ZIO* Z, int native)
132{129{
133 int i,n=LoadWord(Z);130 int i,n=LoadInt(Z,"too many constants (%ld) in %s");
134 tf->nconsts=n;131 tf->nconsts=n;
135 if (n==0) return;132 if (n==0) return;
136 tf->consts=luaM_newvector(n,TObject);133 tf->consts=luaM_newvector(n,TObject);
137 for (i=0; i<n; i++)134 for (i=0; i<n; i++)
138 {135 {
139 TObject* o=tf->consts+i;136 TObject* o=tf->consts+i;
140 ttype(o)=-ezgetc(Z);137 ttype(o)=-ezgetc(Z); /* ttype(o) is negative - ORDER LUA_T */
141 switch (ttype(o))138 switch (ttype(o))
142 {139 {
143 case LUA_T_NUMBER:140 case LUA_T_NUMBER:
144 doLoadNumber(nvalue(o),Z);141 nvalue(o)=LoadNumber(Z,native);
145 break;142 break;
146 case LUA_T_STRING:143 case LUA_T_STRING:
147 tsvalue(o)=LoadTString(Z);144 tsvalue(o)=LoadTString(Z);
148 break;145 break;
149 case LUA_T_PROTO:146 case LUA_T_PROTO:
150 tfvalue(o)=LoadFunction(Z);147 tfvalue(o)=LoadFunction(Z,native);
151 break;148 break;
152 case LUA_T_NIL:149 case LUA_T_NIL:
153 break;150 break;
154 default:151 default: /* cannot happen */
155 luaL_verror("bad constant #%d in %s: type=%d [%s]",152 luaU_badconstant("load",i,o,tf);
156 i,zname(Z),ttype(o),luaO_typename(o));
157 break;153 break;
158 }154 }
159 }155 }
160}156}
161 157
162static TProtoFunc* LoadFunction(ZIO* Z)158static TProtoFunc* LoadFunction (ZIO* Z, int native)
163{159{
164 TProtoFunc* tf=luaF_newproto();160 TProtoFunc* tf=luaF_newproto();
165 tf->lineDefined=LoadWord(Z);161 tf->lineDefined=LoadInt(Z,"lineDefined too large (%ld) in %s");
166 tf->fileName=LoadTString(Z);162 tf->source=LoadTString(Z);
163 if (tf->source==NULL) tf->source=luaS_new(zname(Z));
167 tf->code=LoadCode(Z);164 tf->code=LoadCode(Z);
168 LoadLocals(tf,Z);165 LoadLocals(tf,Z);
169 LoadConstants(tf,Z);166 LoadConstants(tf,Z,native);
170 return tf;167 return tf;
171}168}
172 169
173static void LoadSignature(ZIO* Z)170static void LoadSignature (ZIO* Z)
174{171{
175 char* s=SIGNATURE;172 char* s=SIGNATURE;
176 while (*s!=0 && ezgetc(Z)==*s)173 while (*s!=0 && ezgetc(Z)==*s)
@@ -178,10 +175,10 @@ static void LoadSignature(ZIO* Z) · 1 unmodified line
178 if (*s!=0) luaL_verror("bad signature in %s",zname(Z));175 if (*s!=0) luaL_verror("bad signature in %s",zname(Z));
179}176}
180 177
181static void LoadHeader(ZIO* Z)178static int LoadHeader (ZIO* Z)
182{179{
183 int version,id,sizeofR;180 int version,sizeofR;
184 real f=-TEST_NUMBER,tf=TEST_NUMBER;181 int native;
185 LoadSignature(Z);182 LoadSignature(Z);
186 version=ezgetc(Z);183 version=ezgetc(Z);
187 if (version>VERSION)184 if (version>VERSION)
@@ -192,32 +189,36 @@ static void LoadHeader(ZIO* Z) · 4 unmodified lines
192 luaL_verror(189 luaL_verror(
193 "%s too old: version=0x%02x; expected at least 0x%02x",190 "%s too old: version=0x%02x; expected at least 0x%02x",
194 zname(Z),version,VERSION0);191 zname(Z),version,VERSION0);
195 id=ezgetc(Z); /* test number representation */
196 sizeofR=ezgetc(Z);192 sizeofR=ezgetc(Z);
197 if (id!=ID_NUMBER || sizeofR!=sizeof(real))193 native=(sizeofR!=0);
194 if (native) /* test number representation */
198 {195 {
199 luaL_verror("unknown number signature in %s: "196 if (sizeofR!=sizeof(real))
200 "read 0x%02x%02x; expected 0x%02x%02x",197 luaL_verror("unknown number size in %s: read %d; expected %d",
201 zname(Z),id,sizeofR,ID_NUMBER,sizeof(real));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 }
202 }208 }
203 doLoadNumber(f,Z);209 return native;
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);
208}210}
209 211
210static TProtoFunc* LoadChunk(ZIO* Z)212static TProtoFunc* LoadChunk (ZIO* Z)
211{213{
212 LoadHeader(Z);214 return LoadFunction(Z,LoadHeader(Z));
213 return LoadFunction(Z);
214}215}
215 216
216/*217/*
217** load one chunk from a file or buffer218** load one chunk from a file or buffer
218** return main if ok and NULL at EOF219** return main if ok and NULL at EOF
219*/220*/
220TProtoFunc* luaU_undump1(ZIO* Z)221TProtoFunc* luaU_undump1 (ZIO* Z)
221{222{
222 int c=zgetc(Z);223 int c=zgetc(Z);
223 if (c==ID_CHUNK)224 if (c==ID_CHUNK)
@@ -226,3 +227,13 @@ TProtoFunc* luaU_undump1(ZIO* Z) · 2 unmodified lines
226 luaL_verror("%s is not a Lua binary file",zname(Z));227 luaL_verror("%s is not a Lua binary file",zname(Z));
227 return NULL;228 return NULL;
228}229}
230
231/*
232* handle constants that cannot happen
233*/
234void 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 @@
1/*1/*
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 $
3** load pre-compiled Lua chunks3** load pre-compiled Lua chunks
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -10,69 +10,30 @@ · 4 unmodified lines
10#include "lobject.h"10#include "lobject.h"
11#include "lzio.h"11#include "lzio.h"
12 12
13TProtoFunc* luaU_undump1(ZIO* Z); /* load one chunk */13TProtoFunc* luaU_undump1 (ZIO* Z); /* load one chunk */
14 14void luaU_badconstant (char* s, int i, TObject* o, TProtoFunc* tf);
15#define SIGNATURE "Lua"15 /* handle cases that cannot happen */
16#define VERSION 0x31 /* last format change was in 3.1 */16double luaU_str2d (char* b, char* where);
17#define VERSION0 0x31 /* last major change was in 3.1 */17 /* convert number from text */
18#define ID_CHUNK 27 /* ESC */18
19 19/* definitions for headers of binary files */
20#define IsMain(f) (f->lineDefined==0)20#define VERSION 0x32 /* last format change was in 3.2 */
21#define luaO_typename(o) luaO_typenames[-ttype(o)]21#define VERSION0 0x32 /* last major change was in 3.2 */
22 22#define ID_CHUNK 27 /* binary files start with ESC... */
23/* number representation */23#define SIGNATURE "Lua" /* ...followed by this signature */
24#define ID_INT4 'l' /* 4-byte integers */24
25#define ID_REAL4 'f' /* 4-byte reals */25/* formats for error messages */
26#define ID_REAL8 'd' /* 8-byte reals */26#define SOURCE "<%s:%d>"
27#define ID_NATIVE '?' /* whatever your machine uses */27#define IN " in %p " SOURCE
28 28#define INLOC tf,tf->source->str,tf->lineDefined
29/*29
30* use a multiple of PI for testing number representation.30/* format for numbers in listings and error messages */
31* multiplying by 1E8 gives notrivial integer values.31#ifndef NUMBER_FMT
32*/32#define NUMBER_FMT "%.16g" /* LUA_NUMBER */
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
49#endif33#endif
50 34
51#if 035/* a multiple of PI for testing native format */
52#define ID_NUMBER ID_INT436/* multiplying by 1E8 gives non-trivial integer values */
53#define ID_NUMBER ID_REAL437#define TEST_NUMBER 3.14159265358979323846E8
54#define ID_NUMBER ID_REAL8
55#define ID_NUMBER ID_NATIVE
56#endif
57
58#endif
59 38
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
78#endif39#endif
src/lvm.c+234−336
@@ -1,11 +1,14 @@
1/*1/*
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 $
3** Lua virtual machine3** Lua virtual machine
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
6 6
7 7
8#include <ctype.h>
9#include <limits.h>
8#include <stdio.h>10#include <stdio.h>
11#include <stdlib.h>
9#include <string.h>12#include <string.h>
10 13
11#include "lauxlib.h"14#include "lauxlib.h"
@@ -13,6 +16,7 @@ · 1 unmodified line
13#include "lfunc.h"16#include "lfunc.h"
14#include "lgc.h"17#include "lgc.h"
15#include "lmem.h"18#include "lmem.h"
19#include "lobject.h"
16#include "lopcodes.h"20#include "lopcodes.h"
17#include "lstate.h"21#include "lstate.h"
18#include "lstring.h"22#include "lstring.h"
@@ -27,9 +31,7 @@ · 8 unmodified lines
27#endif31#endif
28 32
29 33
30#define skip_word(pc) (pc+=2)34#define highbyte(x) ((x)<<8)
31#define get_word(pc) ((*(pc)<<8)+(*((pc)+1)))
32#define next_word(pc) (pc+=2, get_word(pc-2))
33 35
34 36
35/* Extra stack size to run a function: LUA_T_LINE(1), TM calls(2), ... */37/* Extra stack size to run a function: LUA_T_LINE(1), TM calls(2), ... */
@@ -37,45 +39,47 @@ · 1 unmodified line
37 39
38 40
39 41
40static TaggedString *strconc (TaggedString *l, TaggedString *r)42static TaggedString *strconc (TaggedString *l, TaggedString *r) {
41{43 long nl = l->u.s.len;
42 size_t nl = l->u.s.len;44 long nr = r->u.s.len;
43 size_t nr = r->u.s.len;45 char *buffer = luaL_openspace(nl+nr);
44 char *buffer = luaL_openspace(nl+nr+1);
45 memcpy(buffer, l->str, nl);46 memcpy(buffer, l->str, nl);
46 memcpy(buffer+nl, r->str, nr);47 memcpy(buffer+nl, r->str, nr);
47 return luaS_newlstr(buffer, nl+nr);48 return luaS_newlstr(buffer, nl+nr);
48}49}
49 50
50 51
51int luaV_tonumber (TObject *obj)52int luaV_tonumber (TObject *obj) { /* LUA_NUMBER */
52{ /* LUA_NUMBER */
53 double t;
54 char c;
55 if (ttype(obj) != LUA_T_STRING)53 if (ttype(obj) != LUA_T_STRING)
56 return 1;54 return 1;
57 else if (sscanf(svalue(obj), "%lf %c",&t, &c) == 1) {55 else {
58 nvalue(obj) = (real)t;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;
59 ttype(obj) = LUA_T_NUMBER;71 ttype(obj) = LUA_T_NUMBER;
60 return 0;72 return 0;
61 }73 }
62 else
63 return 2;
64}74}
65 75
66 76
67int luaV_tostring (TObject *obj)77int luaV_tostring (TObject *obj) { /* LUA_NUMBER */
68{ /* LUA_NUMBER */
69 if (ttype(obj) != LUA_T_NUMBER)78 if (ttype(obj) != LUA_T_NUMBER)
70 return 1;79 return 1;
71 else {80 else {
72 char s[60];81 char s[32]; /* 16 digits, signal, point and \0 (+ some extra...) */
73 real f = nvalue(obj);82 sprintf(s, "%.16g", (double)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));
79 tsvalue(obj) = luaS_new(s);83 tsvalue(obj) = luaS_new(s);
80 ttype(obj) = LUA_T_STRING;84 ttype(obj) = LUA_T_STRING;
81 return 0;85 return 0;
@@ -83,8 +87,15 @@ int luaV_tostring (TObject *obj) · 1 unmodified line
83}87}
84 88
85 89
86void luaV_closure (int nelems)90void luaV_setn (Hash *t, int val) {
87{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
98void luaV_closure (int nelems) {
88 if (nelems > 0) {99 if (nelems > 0) {
89 struct Stack *S = &L->stack;100 struct Stack *S = &L->stack;
90 Closure *c = luaF_newclosure(nelems);101 Closure *c = luaF_newclosure(nelems);
@@ -101,99 +112,110 @@ void luaV_closure (int nelems) · 10 unmodified lines
101** Function to index a table.112** Function to index a table.
102** Receives the table at top-2 and the index at top-1.113** Receives the table at top-2 and the index at top-1.
103*/114*/
104void luaV_gettable (void)115void luaV_gettable (void) {
105{116 TObject *table = L->stack.top-2;
106 struct Stack *S = &L->stack;
107 TObject *im;117 TObject *im;
108 if (ttype(S->top-2) != LUA_T_ARRAY) /* not a table, get "gettable" method */118 if (ttype(table) != LUA_T_ARRAY) { /* not a table, get gettable method */
109 im = luaT_getimbyObj(S->top-2, IM_GETTABLE);119 im = luaT_getimbyObj(table, IM_GETTABLE);
120 if (ttype(im) == LUA_T_NIL)
121 lua_error("indexed expression not a table");
122 }
110 else { /* object is a table... */123 else { /* object is a table... */
111 int tg = (S->top-2)->value.a->htag;124 int tg = table->value.a->htag;
112 im = luaT_getim(tg, IM_GETTABLE);125 im = luaT_getim(tg, IM_GETTABLE);
113 if (ttype(im) == LUA_T_NIL) { /* and does not have a "gettable" method */126 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);127 TObject *h = luaH_get(avalue(table), table+1);
115 if (h != NULL && ttype(h) != LUA_T_NIL) {128 if (ttype(h) == LUA_T_NIL &&
116 --S->top;129 (ttype(im=luaT_getim(tg, IM_INDEX)) != LUA_T_NIL)) {
117 *(S->top-1) = *h;130 /* result is nil and there is an "index" tag method */
131 luaD_callTM(im, 2, 1); /* calls it */
118 }132 }
119 else if (ttype(im=luaT_getim(tg, IM_INDEX)) != LUA_T_NIL)
120 luaD_callTM(im, 2, 1);
121 else {133 else {
122 --S->top;134 L->stack.top--;
123 ttype(S->top-1) = LUA_T_NIL;135 *table = *h; /* "push" result into table position */
124 }136 }
125 return;137 return;
126 }138 }
127 /* else it has a "gettable" method, go through to next command */139 /* else it has a "gettable" method, go through to next command */
128 }140 }
129 /* object is not a table, or it has a "gettable" method */141 /* object is not a table, or it has a "gettable" method */
130 if (ttype(im) != LUA_T_NIL)142 luaD_callTM(im, 2, 1);
131 luaD_callTM(im, 2, 1);
132 else
133 lua_error("indexed expression not a table");
134}143}
135 144
136 145
137/*146/*
138** Function to store indexed based on values at the stack.top147** Receives table at *t, index at *(t+1) and value at 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)
142*/148*/
143void luaV_settable (TObject *t, int mode)149void luaV_settable (TObject *t) {
144{
145 struct Stack *S = &L->stack;150 struct Stack *S = &L->stack;
146 TObject *im = (mode == 0) ? NULL : luaT_getimbyObj(t, IM_SETTABLE);151 TObject *im;
147 if (ttype(t) == LUA_T_ARRAY && (im == NULL || ttype(im) == LUA_T_NIL)) {152 if (ttype(t) != LUA_T_ARRAY) { /* not a table, get "settable" method */
148 TObject *h = luaH_set(avalue(t), t+1);153 im = luaT_getimbyObj(t, IM_SETTABLE);
149 *h = *(S->top-1);154 if (ttype(im) == LUA_T_NIL)
150 S->top -= (mode == 2) ? 1 : 3;155 lua_error("indexed expression not a table");
151 }156 }
152 else { /* object is not a table, and/or has a specific "settable" method */157 else { /* object is a table... */
153 if (im && ttype(im) != LUA_T_NIL) {158 im = luaT_getim(avalue(t)->htag, IM_SETTABLE);
154 if (mode == 2) {159 if (ttype(im) == LUA_T_NIL) { /* and does not have a "settable" method */
155 *(S->top+1) = *(L->stack.top-1);160 luaH_set(avalue(t), t+1, S->top-1);
156 *(S->top) = *(t+1);161 S->top--; /* pop value */
157 *(S->top-1) = *t;162 return;
158 S->top += 2; /* WARNING: caller must assure stack space */
159 }
160 luaD_callTM(im, 3, 0);
161 }163 }
162 else164 /* else it has a "settable" method, go through to next command */
163 lua_error("indexed expression not a table");
164 }165 }
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);
165}173}
166 174
167 175
168void luaV_getglobal (TaggedString *ts)176void luaV_rawsettable (TObject *t) {
169{177 if (ttype(t) != LUA_T_ARRAY)
170 /* WARNING: caller must assure stack space */178 lua_error("indexed expression not a table");
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 else {179 else {
177 struct Stack *S = &L->stack;180 struct Stack *S = &L->stack;
178 ttype(S->top) = LUA_T_STRING;181 luaH_set(avalue(t), t+1, S->top-1);
179 tsvalue(S->top) = ts;182 S->top -= 3;
180 S->top++;
181 *S->top++ = *value;
182 luaD_callTM(im, 2, 1);
183 }183 }
184}184}
185 185
186 186
187void luaV_setglobal (TaggedString *ts)187void luaV_getglobal (TaggedString *ts) {
188{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
209void luaV_setglobal (TaggedString *ts) {
189 TObject *oldvalue = &ts->u.s.globalval;210 TObject *oldvalue = &ts->u.s.globalval;
190 TObject *im = luaT_getimbyObj(oldvalue, IM_SETGLOBAL);211 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? */
192 luaS_rawsetglobal(ts, --L->stack.top);213 luaS_rawsetglobal(ts, --L->stack.top);
193 else {214 else {
194 /* WARNING: caller must assure stack space */215 /* WARNING: caller must assure stack space */
195 struct Stack *S = &L->stack;216 struct Stack *S = &L->stack;
196 TObject newvalue = *(S->top-1);217 TObject newvalue;
218 newvalue = *(S->top-1);
197 ttype(S->top-1) = LUA_T_STRING;219 ttype(S->top-1) = LUA_T_STRING;
198 tsvalue(S->top-1) = ts;220 tsvalue(S->top-1) = ts;
199 *S->top++ = *oldvalue;221 *S->top++ = *oldvalue;
@@ -225,7 +247,7 @@ static void call_arith (IMS event) · 25 unmodified lines
225}247}
226 248
227 249
228static int strcomp (char *l, long ll, char *r, long lr)250static int luaV_strcomp (char *l, long ll, char *r, long lr)
229{251{
230 for (;;) {252 for (;;) {
231 long temp = strcoll(l, r);253 long temp = strcoll(l, r);
@@ -242,18 +264,17 @@ static int strcomp (char *l, long ll, char *r, long lr) · 10 unmodified lines
242 }264 }
243}265}
244 266
245static void comparison (lua_Type ttype_less, lua_Type ttype_equal,267void luaV_comparison (lua_Type ttype_less, lua_Type ttype_equal,
246 lua_Type ttype_great, IMS op)268 lua_Type ttype_great, IMS op) {
247{
248 struct Stack *S = &L->stack;269 struct Stack *S = &L->stack;
249 TObject *l = S->top-2;270 TObject *l = S->top-2;
250 TObject *r = S->top-1;271 TObject *r = S->top-1;
251 int result;272 real result;
252 if (ttype(l) == LUA_T_NUMBER && ttype(r) == LUA_T_NUMBER)273 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);
254 else if (ttype(l) == LUA_T_STRING && ttype(r) == LUA_T_STRING)275 else if (ttype(l) == LUA_T_STRING && ttype(r) == LUA_T_STRING)
255 result = strcomp(svalue(l), tsvalue(l)->u.s.len,276 result = luaV_strcomp(svalue(l), tsvalue(l)->u.s.len,
256 svalue(r), tsvalue(r)->u.s.len);277 svalue(r), tsvalue(r)->u.s.len);
257 else {278 else {
258 call_binTM(op, "unexpected type in comparison");279 call_binTM(op, "unexpected type in comparison");
259 return;280 return;
@@ -265,27 +286,16 @@ static void comparison (lua_Type ttype_less, lua_Type ttype_equal, · 5 unmodified lines
265}286}
266 287
267 288
268void luaV_pack (StkId firstel, int nvararg, TObject *tab)289void luaV_pack (StkId firstel, int nvararg, TObject *tab) {
269{
270 TObject *firstelem = L->stack.stack+firstel;290 TObject *firstelem = L->stack.stack+firstel;
271 int i;291 int i;
292 Hash *htab;
272 if (nvararg < 0) nvararg = 0;293 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' */
274 ttype(tab) = LUA_T_ARRAY;295 ttype(tab) = LUA_T_ARRAY;
275 for (i=0; i<nvararg; i++) {296 for (i=0; i<nvararg; i++)
276 TObject index;297 luaH_setint(htab, i+1, firstelem+i);
277 ttype(&index) = LUA_T_NUMBER;298 luaV_setn(htab, nvararg); /* store counter in field "n" */
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 }
289}299}
290 300
291 301
@@ -305,12 +315,11 @@ static void adjust_varargs (StkId first_extra_arg) · 13 unmodified lines
305** [stack+base,top). Returns n such that the the results are between315** [stack+base,top). Returns n such that the the results are between
306** [stack+n,top).316** [stack+n,top).
307*/317*/
308StkId luaV_execute (Closure *cl, TProtoFunc *tf, StkId base)318StkId luaV_execute (Closure *cl, TProtoFunc *tf, StkId base) {
309{
310 struct Stack *S = &L->stack; /* to optimize */319 struct Stack *S = &L->stack; /* to optimize */
311 Byte *pc = tf->code;320 register Byte *pc = tf->code;
312 TObject *consts = tf->consts;321 TObject *consts = tf->consts;
313 if (lua_callhook)322 if (L->callhook)
314 luaD_callHook(base, tf, 0);323 luaD_callHook(base, tf, 0);
315 luaD_checkstack((*pc++)+EXTRA_STACK);324 luaD_checkstack((*pc++)+EXTRA_STACK);
316 if (*pc < ZEROVARARG)325 if (*pc < ZEROVARARG)
@@ -319,228 +328,159 @@ StkId luaV_execute (Closure *cl, TProtoFunc *tf, StkId base) · 2 unmodified lines
319 luaC_checkGC();328 luaC_checkGC();
320 adjust_varargs(base+(*pc++)-ZEROVARARG);329 adjust_varargs(base+(*pc++)-ZEROVARARG);
321 }330 }
322 while (1) {331 for (;;) {
323 int aux;332 register int aux = 0;
324 switch ((OpCode)(aux = *pc++)) {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;
325 343
326 case PUSHNIL0:344 case CALL: aux = *pc++;
327 ttype(S->top++) = LUA_T_NIL;345 luaD_calln(*pc++, aux);
328 break;346 break;
329 347
330 case PUSHNIL:348 case TAILCALL: aux = *pc++;
331 aux = *pc++;349 luaD_calln(*pc++, MULT_RET);
350 base += aux;
351 goto ret;
352
353 case PUSHNIL: aux = *pc++;
332 do {354 do {
333 ttype(S->top++) = LUA_T_NIL;355 ttype(S->top++) = LUA_T_NIL;
334 } while (aux--);356 } while (aux--);
335 break;357 break;
336 358
337 case PUSHNUMBER:359 case POP: aux = *pc++;
338 aux = *pc++; goto pushnumber;360 S->top -= aux;
339 361 break;
340 case PUSHNUMBERW:
341 aux = next_word(pc); goto pushnumber;
342 362
343 case PUSHNUMBER0: case PUSHNUMBER1: case PUSHNUMBER2:363 case PUSHNUMBERW: aux += highbyte(*pc++);
344 aux -= PUSHNUMBER0;364 case PUSHNUMBER: aux += *pc++;
345 pushnumber:
346 ttype(S->top) = LUA_T_NUMBER;365 ttype(S->top) = LUA_T_NUMBER;
347 nvalue(S->top) = aux;366 nvalue(S->top) = aux;
348 S->top++;367 S->top++;
349 break;368 break;
350 369
351 case PUSHLOCAL:370 case PUSHNUMBERNEGW: aux += highbyte(*pc++);
352 aux = *pc++; goto pushlocal;371 case PUSHNUMBERNEG: aux += *pc++;
372 ttype(S->top) = LUA_T_NUMBER;
373 nvalue(S->top) = -aux;
374 S->top++;
375 break;
353 376
354 case PUSHLOCAL0: case PUSHLOCAL1: case PUSHLOCAL2: case PUSHLOCAL3:377 case PUSHCONSTANTW: aux += highbyte(*pc++);
355 case PUSHLOCAL4: case PUSHLOCAL5: case PUSHLOCAL6: case PUSHLOCAL7:378 case PUSHCONSTANT: aux += *pc++;
356 aux -= PUSHLOCAL0;379 *S->top++ = consts[aux];
357 pushlocal:
358 *S->top++ = *((S->stack+base) + aux);
359 break;380 break;
360 381
361 case GETGLOBALW:382 case PUSHUPVALUE: aux = *pc++;
362 aux = next_word(pc); goto getglobal;383 *S->top++ = cl->consts[aux+1];
384 break;
363 385
364 case GETGLOBAL:386 case PUSHLOCAL: aux = *pc++;
365 aux = *pc++; goto getglobal;387 *S->top++ = *((S->stack+base) + aux);
388 break;
366 389
367 case GETGLOBAL0: case GETGLOBAL1: case GETGLOBAL2: case GETGLOBAL3:390 case GETGLOBALW: aux += highbyte(*pc++);
368 case GETGLOBAL4: case GETGLOBAL5: case GETGLOBAL6: case GETGLOBAL7:391 case GETGLOBAL: aux += *pc++;
369 aux -= GETGLOBAL0;
370 getglobal:
371 luaV_getglobal(tsvalue(&consts[aux]));392 luaV_getglobal(tsvalue(&consts[aux]));
372 break;393 break;
373 394
374 case GETTABLE:395 case GETTABLE:
375 luaV_gettable();396 luaV_gettable();
376 break;397 break;
377
378 case GETDOTTEDW:
379 aux = next_word(pc); goto getdotted;
380
381 case GETDOTTED:
382 aux = *pc++; goto getdotted;
383 398
384 case GETDOTTED0: case GETDOTTED1: case GETDOTTED2: case GETDOTTED3:399 case GETDOTTEDW: aux += highbyte(*pc++);
385 case GETDOTTED4: case GETDOTTED5: case GETDOTTED6: case GETDOTTED7:400 case GETDOTTED: aux += *pc++;
386 aux -= GETDOTTED0;
387 getdotted:
388 *S->top++ = consts[aux];401 *S->top++ = consts[aux];
389 luaV_gettable();402 luaV_gettable();
390 break;403 break;
391 404
392 case PUSHSELFW:405 case PUSHSELFW: aux += highbyte(*pc++);
393 aux = next_word(pc); goto pushself;406 case PUSHSELF: aux += *pc++; {
394 407 TObject receiver;
395 case PUSHSELF:408 receiver = *(S->top-1);
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);
403 *S->top++ = consts[aux];409 *S->top++ = consts[aux];
404 luaV_gettable();410 luaV_gettable();
405 *S->top++ = receiver;411 *S->top++ = receiver;
406 break;412 break;
407 }413 }
408 414
409 case PUSHCONSTANTW:415 case CREATEARRAYW: aux += highbyte(*pc++);
410 aux = next_word(pc); goto pushconstant;416 case CREATEARRAY: aux += *pc++;
411 417 luaC_checkGC();
412 case PUSHCONSTANT:418 avalue(S->top) = luaH_new(aux);
413 aux = *pc++; goto pushconstant;419 ttype(S->top) = LUA_T_ARRAY;
414 420 S->top++;
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];
430 break;421 break;
431 422
432 case SETLOCAL:423 case SETLOCAL: aux = *pc++;
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:
439 *((S->stack+base) + aux) = *(--S->top);424 *((S->stack+base) + aux) = *(--S->top);
440 break;425 break;
441 426
442 case SETGLOBALW:427 case SETGLOBALW: aux += highbyte(*pc++);
443 aux = next_word(pc); goto setglobal;428 case SETGLOBAL: aux += *pc++;
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:
452 luaV_setglobal(tsvalue(&consts[aux]));429 luaV_setglobal(tsvalue(&consts[aux]));
453 break;430 break;
454 431
455 case SETTABLE0:432 case SETTABLEPOP:
456 luaV_settable(S->top-3, 1);433 luaV_settable(S->top-3);
457 break;434 S->top -= 2; /* pop table and index */
435 break;
458 436
459 case SETTABLE:437 case SETTABLE:
460 luaV_settable(S->top-3-(*pc++), 2);438 luaV_settable(S->top-3-(*pc++));
461 break;439 break;
462 440
463 case SETLISTW:441 case SETLISTW: aux += highbyte(*pc++);
464 aux = next_word(pc); aux *= LFIELDS_PER_FLUSH; goto setlist;442 case SETLIST: aux += *pc++; {
465
466 case SETLIST:
467 aux = *(pc++) * LFIELDS_PER_FLUSH; goto setlist;
468
469 case SETLIST0:
470 aux = 0;
471 setlist: {
472 int n = *(pc++);443 int n = *(pc++);
473 TObject *arr = S->top-n-1;444 Hash *arr = avalue(S->top-n-1);
474 for (; n; n--) {445 aux *= LFIELDS_PER_FLUSH;
475 ttype(S->top) = LUA_T_NUMBER;446 for (; n; n--)
476 nvalue(S->top) = n+aux;447 luaH_setint(arr, n+aux, --S->top);
477 *(luaH_set(avalue(arr), S->top)) = *(S->top-1);
478 S->top--;
479 }
480 break;448 break;
481 }449 }
482 450
483 case SETMAP0:451 case SETMAP: aux = *pc++; {
484 aux = 0; goto setmap;452 Hash *arr = avalue(S->top-(2*aux)-3);
485
486 case SETMAP:
487 aux = *pc++;
488 setmap: {
489 TObject *arr = S->top-(2*aux)-3;
490 do {453 do {
491 *(luaH_set(avalue(arr), S->top-2)) = *(S->top-1);454 luaH_set(arr, S->top-2, S->top-1);
492 S->top-=2;455 S->top-=2;
493 } while (aux--);456 } while (aux--);
494 break;457 break;
495 }458 }
496 459
497 case POP:460 case NEQOP: aux = 1;
498 aux = *pc++; goto pop;461 case EQOP: {
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: {
522 int res = luaO_equalObj(S->top-2, S->top-1);462 int res = luaO_equalObj(S->top-2, S->top-1);
463 if (aux) res = !res;
523 S->top--;464 S->top--;
524 if (aux == NEQOP) res = !res;
525 ttype(S->top-1) = res ? LUA_T_NUMBER : LUA_T_NIL;465 ttype(S->top-1) = res ? LUA_T_NUMBER : LUA_T_NIL;
526 nvalue(S->top-1) = 1;466 nvalue(S->top-1) = 1;
527 break;467 break;
528 }468 }
529 469
530 case LTOP:470 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);
532 break;472 break;
533 473
534 case LEOP:474 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);
536 break;476 break;
537 477
538 case GTOP:478 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);
540 break;480 break;
541 481
542 case GEOP:482 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);
544 break;484 break;
545 485
546 case ADDOP: {486 case ADDOP: {
@@ -624,98 +564,47 @@ StkId luaV_execute (Closure *cl, TProtoFunc *tf, StkId base) · 77 unmodified lines
624 nvalue(S->top-1) = 1;564 nvalue(S->top-1) = 1;
625 break;565 break;
626 566
627 case ONTJMPW:567 case ONTJMPW: aux += highbyte(*pc++);
628 aux = next_word(pc); goto ontjmp;568 case ONTJMP: aux += *pc++;
629
630 case ONTJMP:
631 aux = *pc++;
632 ontjmp:
633 if (ttype(S->top-1) != LUA_T_NIL) pc += aux;569 if (ttype(S->top-1) != LUA_T_NIL) pc += aux;
634 else S->top--;570 else S->top--;
635 break;571 break;
636 572
637 case ONFJMPW:573 case ONFJMPW: aux += highbyte(*pc++);
638 aux = next_word(pc); goto onfjmp;574 case ONFJMP: aux += *pc++;
639
640 case ONFJMP:
641 aux = *pc++;
642 onfjmp:
643 if (ttype(S->top-1) == LUA_T_NIL) pc += aux;575 if (ttype(S->top-1) == LUA_T_NIL) pc += aux;
644 else S->top--;576 else S->top--;
645 break;577 break;
646 578
647 case JMPW:579 case JMPW: aux += highbyte(*pc++);
648 aux = next_word(pc); goto jmp;580 case JMP: aux += *pc++;
649
650 case JMP:
651 aux = *pc++;
652 jmp:
653 pc += aux;581 pc += aux;
654 break;582 break;
655 583
656 case IFFJMPW:584 case IFFJMPW: aux += highbyte(*pc++);
657 aux = next_word(pc); goto iffjmp;585 case IFFJMP: aux += *pc++;
658
659 case IFFJMP:
660 aux = *pc++;
661 iffjmp:
662 if (ttype(--S->top) == LUA_T_NIL) pc += aux;586 if (ttype(--S->top) == LUA_T_NIL) pc += aux;
663 break;587 break;
664 588
665 case IFTUPJMPW:589 case IFTUPJMPW: aux += highbyte(*pc++);
666 aux = next_word(pc); goto iftupjmp;590 case IFTUPJMP: aux += *pc++;
667
668 case IFTUPJMP:
669 aux = *pc++;
670 iftupjmp:
671 if (ttype(--S->top) != LUA_T_NIL) pc -= aux;591 if (ttype(--S->top) != LUA_T_NIL) pc -= aux;
672 break;592 break;
673 593
674 case IFFUPJMPW:594 case IFFUPJMPW: aux += highbyte(*pc++);
675 aux = next_word(pc); goto iffupjmp;595 case IFFUPJMP: aux += *pc++;
676
677 case IFFUPJMP:
678 aux = *pc++;
679 iffupjmp:
680 if (ttype(--S->top) == LUA_T_NIL) pc -= aux;596 if (ttype(--S->top) == LUA_T_NIL) pc -= aux;
681 break;597 break;
682 598
683 case CLOSUREW:599 case CLOSUREW: aux += highbyte(*pc++);
684 aux = next_word(pc); goto closure;600 case CLOSURE: aux += *pc++;
685
686 case CLOSURE:
687 aux = *pc++;
688 closure:
689 *S->top++ = consts[aux];601 *S->top++ = consts[aux];
690 luaV_closure(*pc++);602 luaV_closure(*pc++);
691 luaC_checkGC();603 luaC_checkGC();
692 break;604 break;
693 605
694 case CALLFUNC:606 case SETLINEW: aux += highbyte(*pc++);
695 aux = *pc++; goto callfunc;607 case SETLINE: aux += *pc++;
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:
719 if ((S->stack+base-1)->ttype != LUA_T_LINE) {608 if ((S->stack+base-1)->ttype != LUA_T_LINE) {
720 /* open space for LINE value */609 /* open space for LINE value */
721 luaD_openstack((S->top-S->stack)-base);610 luaD_openstack((S->top-S->stack)-base);
@@ -723,15 +612,24 @@ StkId luaV_execute (Closure *cl, TProtoFunc *tf, StkId base) · 1 unmodified line
723 (S->stack+base-1)->ttype = LUA_T_LINE;612 (S->stack+base-1)->ttype = LUA_T_LINE;
724 }613 }
725 (S->stack+base-1)->value.i = aux;614 (S->stack+base-1)->value.i = aux;
726 if (lua_linehook)615 if (L->linehook)
727 luaD_lineHook(aux);616 luaD_lineHook(aux);
728 break;617 break;
729 618
730#ifdef DEBUG619 case LONGARGW: aux += highbyte(*pc++);
731 default:620 case LONGARG: aux += *pc++;
732 LUA_INTERNALERROR("opcode doesn't match");621 aux = highbyte(highbyte(aux));
733#endif622 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
734 }629 }
735 }630 } ret:
631 if (L->callhook)
632 luaD_callHook(0, NULL, 1);
633 return base;
736}634}
737 635
src/lvm.h+7−2
@@ -1,5 +1,5 @@
1/*1/*
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 $
3** Lua virtual machine3** Lua virtual machine
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -10,6 +10,7 @@ · 4 unmodified lines
10 10
11#include "ldo.h"11#include "ldo.h"
12#include "lobject.h"12#include "lobject.h"
13#include "ltm.h"
13 14
14 15
15#define tonumber(o) ((ttype(o) != LUA_T_NUMBER) && (luaV_tonumber(o) != 0))16#define tonumber(o) ((ttype(o) != LUA_T_NUMBER) && (luaV_tonumber(o) != 0))
@@ -19,11 +20,15 @@ · 3 unmodified lines
19void luaV_pack (StkId firstel, int nvararg, TObject *tab);20void luaV_pack (StkId firstel, int nvararg, TObject *tab);
20int luaV_tonumber (TObject *obj);21int luaV_tonumber (TObject *obj);
21int luaV_tostring (TObject *obj);22int luaV_tostring (TObject *obj);
23void luaV_setn (Hash *t, int val);
22void luaV_gettable (void);24void luaV_gettable (void);
23void luaV_settable (TObject *t, int mode);25void luaV_settable (TObject *t);
26void luaV_rawsettable (TObject *t);
24void luaV_getglobal (TaggedString *ts);27void luaV_getglobal (TaggedString *ts);
25void luaV_setglobal (TaggedString *ts);28void luaV_setglobal (TaggedString *ts);
26StkId luaV_execute (Closure *cl, TProtoFunc *tf, StkId base);29StkId luaV_execute (Closure *cl, TProtoFunc *tf, StkId base);
27void luaV_closure (int nelems);30void luaV_closure (int nelems);
31void luaV_comparison (lua_Type ttype_less, lua_Type ttype_equal,
32 lua_Type ttype_great, IMS op);
28 33
29#endif34#endif
src/lzio.c+11−11
@@ -1,5 +1,5 @@
1/*1/*
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 $
3** a generic input stream interface3** a generic input stream interface
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -15,11 +15,11 @@ · 9 unmodified lines
15 15
16/* ----------------------------------------------------- memory buffers --- */16/* ----------------------------------------------------- memory buffers --- */
17 17
18static int zmfilbuf (ZIO* z)18static int zmfilbuf (ZIO* z) {
19{
20 return EOZ;19 return EOZ;
21}20}
22 21
22
23ZIO* zmopen (ZIO* z, char* b, int size, char *name)23ZIO* zmopen (ZIO* z, char* b, int size, char *name)
24{24{
25 if (b==NULL) return NULL;25 if (b==NULL) return NULL;
@@ -41,9 +41,10 @@ ZIO* zsopen (ZIO* z, char* s, char *name) · 15 unmodified lines
41 41
42/* -------------------------------------------------------------- FILEs --- */42/* -------------------------------------------------------------- FILEs --- */
43 43
44static int zffilbuf (ZIO* z)44static int zffilbuf (ZIO* z) {
45{45 int n;
46 int n=fread(z->buffer,1,ZBSIZE,z->u);46 if (feof((FILE *)z->u)) return EOZ;
47 n=fread(z->buffer,1,ZBSIZE,z->u);
47 if (n==0) return EOZ;48 if (n==0) return EOZ;
48 z->n=n-1;49 z->n=n-1;
49 z->p=z->buffer;50 z->p=z->buffer;
@@ -64,16 +65,15 @@ ZIO* zFopen (ZIO* z, FILE* f, char *name) · 14 unmodified lines
64 65
65 66
66/* --------------------------------------------------------------- read --- */67/* --------------------------------------------------------------- read --- */
67int zread (ZIO *z, void *b, int n)68int zread (ZIO *z, void *b, int n) {
68{
69 while (n) {69 while (n) {
70 int m;70 int m;
71 if (z->n == 0) {71 if (z->n == 0) {
72 if (z->filbuf(z) == EOZ)72 if (z->filbuf(z) == EOZ)
73 return n; /* retorna quantos faltaram ler */73 return n; /* return number of missing bytes */
74 zungetc(z); /* poe o resultado de filbuf no buffer */74 zungetc(z); /* put result from 'filbuf' in the buffer */
75 }75 }
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 */
77 memcpy(b, z->p, m);77 memcpy(b, z->p, m);
78 z->n -= m;78 z->n -= m;
79 z->p += m;79 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