summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLua Team <team@lua.org>2005-09-09 12:00:00 +0000
committerrepogen <>2005-09-09 12:00:00 +0000
commitbd80c4ee9b6d9464cf9f3ff4ee41890d8b3ca9e6 (patch)
treee1d7c1b341ccb9a3a1fb044ac6e67b5a5e0259b7
parentbf6b5550cdfbc0c4a3a4577776ad76628d80718e (diff)
downloadlua-github-5.1-alpha.tar.gz
Lua 5.1-alpha5.1-alpha
-rw-r--r--COPYRIGHT2
-rw-r--r--HISTORY10
-rw-r--r--INSTALL15
-rw-r--r--MANIFEST210
-rw-r--r--Makefile18
-rw-r--r--README8
-rw-r--r--doc/contents.html90
-rw-r--r--doc/lua.19
-rw-r--r--doc/lua.css15
-rw-r--r--doc/lua.html8
-rw-r--r--doc/luac.114
-rw-r--r--doc/luac.html13
-rw-r--r--doc/manual.html5980
-rw-r--r--doc/readme.html3
-rw-r--r--etc/Makefile11
-rw-r--r--etc/README14
-rw-r--r--etc/luavs.bat7
-rw-r--r--etc/noparser.c22
-rw-r--r--etc/strict.lua34
-rw-r--r--src/lapi.c27
-rw-r--r--src/lauxlib.c181
-rw-r--r--src/lauxlib.h57
-rw-r--r--src/lbaselib.c74
-rw-r--r--src/lcode.c85
-rw-r--r--src/lcode.h5
-rw-r--r--src/ldblib.c18
-rw-r--r--src/ldebug.c24
-rw-r--r--src/ldo.c164
-rw-r--r--src/ldo.h15
-rw-r--r--src/ldump.c79
-rw-r--r--src/lgc.c19
-rw-r--r--src/lgc.h17
-rw-r--r--src/linit.c8
-rw-r--r--src/liolib.c145
-rw-r--r--src/llex.h4
-rw-r--r--src/llimits.h21
-rw-r--r--src/lmathlib.c44
-rw-r--r--src/loadlib.c373
-rw-r--r--src/lobject.c24
-rw-r--r--src/lobject.h23
-rw-r--r--src/lopcodes.c10
-rw-r--r--src/lopcodes.h11
-rw-r--r--src/loslib.c11
-rw-r--r--src/lparser.c166
-rw-r--r--src/lstate.c5
-rw-r--r--src/lstate.h10
-rw-r--r--src/lstrlib.c117
-rw-r--r--src/ltable.c16
-rw-r--r--src/ltable.h4
-rw-r--r--src/ltablib.c14
-rw-r--r--src/ltm.c4
-rw-r--r--src/ltm.h6
-rw-r--r--src/lua.c56
-rw-r--r--src/lua.h17
-rw-r--r--src/luac.c8
-rw-r--r--src/luaconf.h307
-rw-r--r--src/lualib.h4
-rw-r--r--src/lundump.c242
-rw-r--r--src/lundump.h49
-rw-r--r--src/lvm.c143
-rw-r--r--src/lvm.h4
-rw-r--r--src/lzio.c22
-rw-r--r--src/print.c8
-rw-r--r--test/luac.lua2
-rw-r--r--test/trace-calls.lua2
65 files changed, 7696 insertions, 1432 deletions
diff --git a/COPYRIGHT b/COPYRIGHT
index ba498733..282351f3 100644
--- a/COPYRIGHT
+++ b/COPYRIGHT
@@ -9,7 +9,7 @@ For details and rationale, see http://www.lua.org/license.html .
===============================================================================
-Copyright (C) 1994-2005 Tecgraf, PUC-Rio.
+Copyright (C) 1994-2005 Lua.org, PUC-Rio.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
diff --git a/HISTORY b/HISTORY
index bc7c4181..4497c069 100644
--- a/HISTORY
+++ b/HISTORY
@@ -1,4 +1,4 @@
-This is Lua 5.1 (work).
+This is Lua 5.1 (alpha).
* Changes from version 5.0 to 5.1
-------------------------------
@@ -7,16 +7,16 @@ This is Lua 5.1 (work).
+ new semantics for control variables of fors.
+ new semantics for setn/getn.
+ new syntax/semantics for varargs.
- + new long strings.
- + new `mod' (`%') operator
- + new operation *t (for size of t)
+ + new long strings and comments.
+ + new `mod' operator (`%')
+ + new length operator #t
+ metatables for all types
API:
+ new functions: lua_createtable, lua_get(set)field, lua_push(to)integer.
+ user supplies memory allocator (lua_open becomes lua_newstate).
Implementation:
+ + new configuration scheme via luaconf.h.
+ incremental garbage collection.
- + debug works over other threads.
+ better handling of end-of-line in the lexer.
+ fully reentrant parser (new Lua function `load')
+ better support for 64-bit machines (special thanks to Mike Pall).
diff --git a/INSTALL b/INSTALL
index 0ddd37e0..4f17a9e9 100644
--- a/INSTALL
+++ b/INSTALL
@@ -1,12 +1,11 @@
-This is Lua 5.1 (work).
+This is Lua 5.1 (alpha).
* Installation
------------
Building Lua on a Unix system should be very easy: simply doing "make"
should work. This will build Lua in the src directory.
- See below for customization instructions. We strongly recommend that
- you enable dynamic loading.
+ See below for customization instructions.
If you want to install Lua in an official place in your system, then
do "make install". The official place and the way to install files are
@@ -17,7 +16,7 @@ This is Lua 5.1 (work).
follows:
bin: lua luac
- include: lua.h luaconf.h lualib.h lauxlib.h
+ include: lua.h luaconf.h lualib.h lauxlib.h lua.hpp
lib: liblua.a
man/man1: lua.1 luac.1
@@ -43,6 +42,9 @@ This is Lua 5.1 (work).
to edit src/luaconf.h. The edited file will be the one installed, and
it will be used by any Lua clients that you build, to ensure consistency.
+ We strongly recommend that you enable dynamic loading. See src/luaconf.h
+ and also src/Makefile.
+
* Installation on Windows and other systems
-----------------------------------------
The instructions for building Lua on other systems depend on the compiler
@@ -60,7 +62,7 @@ This is Lua 5.1 (work).
compiler: library, luac.c print.c
If all you want is to build the Lua interpreter, you may put all .c files
- in a single project, except for luac.c and print.c.
+ in a single project, except for luac.c and print.c. Or use etc/all.c.
To use Lua as a library in your own programs, you'll need to know how to
create and use libraries with your compiler.
@@ -68,4 +70,7 @@ This is Lua 5.1 (work).
As mentioned above, you may edit luaconf.h to select some features before
building Lua.
+ If you use Visual Studio .NET, you can use etc/luavs.bat
+ in its "Command Prompt".
+
(end of INSTALL)
diff --git a/MANIFEST b/MANIFEST
index dbd86863..5731f184 100644
--- a/MANIFEST
+++ b/MANIFEST
@@ -1,104 +1,108 @@
-MANIFEST contents of Lua 5.1 (work6) distribution on Wed May 18 10:13:40 BRST 2005
-lua-5.1-work6
-lua-5.1-work6/COPYRIGHT
-lua-5.1-work6/HISTORY
-lua-5.1-work6/INSTALL
-lua-5.1-work6/MANIFEST
-lua-5.1-work6/Makefile
-lua-5.1-work6/README
-lua-5.1-work6/doc
-lua-5.1-work6/doc/contents.html
-lua-5.1-work6/doc/logo.gif
-lua-5.1-work6/doc/lua.1
-lua-5.1-work6/doc/lua.html
-lua-5.1-work6/doc/luac.1
-lua-5.1-work6/doc/luac.html
-lua-5.1-work6/doc/readme.html
-lua-5.1-work6/etc
-lua-5.1-work6/etc/Makefile
-lua-5.1-work6/etc/README
-lua-5.1-work6/etc/all.c
-lua-5.1-work6/etc/lua.hpp
-lua-5.1-work6/etc/lua.ico
-lua-5.1-work6/etc/lua.pc
-lua-5.1-work6/etc/min.c
-lua-5.1-work6/etc/noparser.c
-lua-5.1-work6/src
-lua-5.1-work6/src/Makefile
-lua-5.1-work6/src/lapi.c
-lua-5.1-work6/src/lapi.h
-lua-5.1-work6/src/lauxlib.c
-lua-5.1-work6/src/lauxlib.h
-lua-5.1-work6/src/lbaselib.c
-lua-5.1-work6/src/lcode.c
-lua-5.1-work6/src/lcode.h
-lua-5.1-work6/src/ldblib.c
-lua-5.1-work6/src/ldebug.c
-lua-5.1-work6/src/ldebug.h
-lua-5.1-work6/src/ldo.c
-lua-5.1-work6/src/ldo.h
-lua-5.1-work6/src/ldump.c
-lua-5.1-work6/src/lfunc.c
-lua-5.1-work6/src/lfunc.h
-lua-5.1-work6/src/lgc.c
-lua-5.1-work6/src/lgc.h
-lua-5.1-work6/src/linit.c
-lua-5.1-work6/src/liolib.c
-lua-5.1-work6/src/llex.c
-lua-5.1-work6/src/llex.h
-lua-5.1-work6/src/llimits.h
-lua-5.1-work6/src/lmathlib.c
-lua-5.1-work6/src/lmem.c
-lua-5.1-work6/src/lmem.h
-lua-5.1-work6/src/loadlib.c
-lua-5.1-work6/src/lobject.c
-lua-5.1-work6/src/lobject.h
-lua-5.1-work6/src/lopcodes.c
-lua-5.1-work6/src/lopcodes.h
-lua-5.1-work6/src/loslib.c
-lua-5.1-work6/src/lparser.c
-lua-5.1-work6/src/lparser.h
-lua-5.1-work6/src/lstate.c
-lua-5.1-work6/src/lstate.h
-lua-5.1-work6/src/lstring.c
-lua-5.1-work6/src/lstring.h
-lua-5.1-work6/src/lstrlib.c
-lua-5.1-work6/src/ltable.c
-lua-5.1-work6/src/ltable.h
-lua-5.1-work6/src/ltablib.c
-lua-5.1-work6/src/ltm.c
-lua-5.1-work6/src/ltm.h
-lua-5.1-work6/src/lua.c
-lua-5.1-work6/src/lua.h
-lua-5.1-work6/src/luac.c
-lua-5.1-work6/src/luaconf.h
-lua-5.1-work6/src/lualib.h
-lua-5.1-work6/src/lundump.c
-lua-5.1-work6/src/lundump.h
-lua-5.1-work6/src/lvm.c
-lua-5.1-work6/src/lvm.h
-lua-5.1-work6/src/lzio.c
-lua-5.1-work6/src/lzio.h
-lua-5.1-work6/src/print.c
-lua-5.1-work6/test
-lua-5.1-work6/test/README
-lua-5.1-work6/test/bisect.lua
-lua-5.1-work6/test/cf.lua
-lua-5.1-work6/test/echo.lua
-lua-5.1-work6/test/env.lua
-lua-5.1-work6/test/factorial.lua
-lua-5.1-work6/test/fib.lua
-lua-5.1-work6/test/fibfor.lua
-lua-5.1-work6/test/globals.lua
-lua-5.1-work6/test/hello.lua
-lua-5.1-work6/test/life.lua
-lua-5.1-work6/test/luac.lua
-lua-5.1-work6/test/printf.lua
-lua-5.1-work6/test/readonly.lua
-lua-5.1-work6/test/sieve.lua
-lua-5.1-work6/test/sort.lua
-lua-5.1-work6/test/table.lua
-lua-5.1-work6/test/trace-calls.lua
-lua-5.1-work6/test/trace-globals.lua
-lua-5.1-work6/test/xd.lua
+MANIFEST contents of Lua 5.1 (alpha) distribution on Fri Sep 9 16:55:12 BRST 2005
+lua-5.1-alpha
+lua-5.1-alpha/COPYRIGHT
+lua-5.1-alpha/HISTORY
+lua-5.1-alpha/INSTALL
+lua-5.1-alpha/MANIFEST
+lua-5.1-alpha/Makefile
+lua-5.1-alpha/README
+lua-5.1-alpha/doc
+lua-5.1-alpha/doc/contents.html
+lua-5.1-alpha/doc/logo.gif
+lua-5.1-alpha/doc/lua.1
+lua-5.1-alpha/doc/lua.css
+lua-5.1-alpha/doc/lua.html
+lua-5.1-alpha/doc/luac.1
+lua-5.1-alpha/doc/luac.html
+lua-5.1-alpha/doc/manual.html
+lua-5.1-alpha/doc/readme.html
+lua-5.1-alpha/etc
+lua-5.1-alpha/etc/Makefile
+lua-5.1-alpha/etc/README
+lua-5.1-alpha/etc/all.c
+lua-5.1-alpha/etc/lua.hpp
+lua-5.1-alpha/etc/lua.ico
+lua-5.1-alpha/etc/lua.pc
+lua-5.1-alpha/etc/luavs.bat
+lua-5.1-alpha/etc/min.c
+lua-5.1-alpha/etc/noparser.c
+lua-5.1-alpha/etc/strict.lua
+lua-5.1-alpha/src
+lua-5.1-alpha/src/Makefile
+lua-5.1-alpha/src/lapi.c
+lua-5.1-alpha/src/lapi.h
+lua-5.1-alpha/src/lauxlib.c
+lua-5.1-alpha/src/lauxlib.h
+lua-5.1-alpha/src/lbaselib.c
+lua-5.1-alpha/src/lcode.c
+lua-5.1-alpha/src/lcode.h
+lua-5.1-alpha/src/ldblib.c
+lua-5.1-alpha/src/ldebug.c
+lua-5.1-alpha/src/ldebug.h
+lua-5.1-alpha/src/ldo.c
+lua-5.1-alpha/src/ldo.h
+lua-5.1-alpha/src/ldump.c
+lua-5.1-alpha/src/lfunc.c
+lua-5.1-alpha/src/lfunc.h
+lua-5.1-alpha/src/lgc.c
+lua-5.1-alpha/src/lgc.h
+lua-5.1-alpha/src/linit.c
+lua-5.1-alpha/src/liolib.c
+lua-5.1-alpha/src/llex.c
+lua-5.1-alpha/src/llex.h
+lua-5.1-alpha/src/llimits.h
+lua-5.1-alpha/src/lmathlib.c
+lua-5.1-alpha/src/lmem.c
+lua-5.1-alpha/src/lmem.h
+lua-5.1-alpha/src/loadlib.c
+lua-5.1-alpha/src/lobject.c
+lua-5.1-alpha/src/lobject.h
+lua-5.1-alpha/src/lopcodes.c
+lua-5.1-alpha/src/lopcodes.h
+lua-5.1-alpha/src/loslib.c
+lua-5.1-alpha/src/lparser.c
+lua-5.1-alpha/src/lparser.h
+lua-5.1-alpha/src/lstate.c
+lua-5.1-alpha/src/lstate.h
+lua-5.1-alpha/src/lstring.c
+lua-5.1-alpha/src/lstring.h
+lua-5.1-alpha/src/lstrlib.c
+lua-5.1-alpha/src/ltable.c
+lua-5.1-alpha/src/ltable.h
+lua-5.1-alpha/src/ltablib.c
+lua-5.1-alpha/src/ltm.c
+lua-5.1-alpha/src/ltm.h
+lua-5.1-alpha/src/lua.c
+lua-5.1-alpha/src/lua.h
+lua-5.1-alpha/src/luac.c
+lua-5.1-alpha/src/luaconf.h
+lua-5.1-alpha/src/lualib.h
+lua-5.1-alpha/src/lundump.c
+lua-5.1-alpha/src/lundump.h
+lua-5.1-alpha/src/lvm.c
+lua-5.1-alpha/src/lvm.h
+lua-5.1-alpha/src/lzio.c
+lua-5.1-alpha/src/lzio.h
+lua-5.1-alpha/src/print.c
+lua-5.1-alpha/test
+lua-5.1-alpha/test/README
+lua-5.1-alpha/test/bisect.lua
+lua-5.1-alpha/test/cf.lua
+lua-5.1-alpha/test/echo.lua
+lua-5.1-alpha/test/env.lua
+lua-5.1-alpha/test/factorial.lua
+lua-5.1-alpha/test/fib.lua
+lua-5.1-alpha/test/fibfor.lua
+lua-5.1-alpha/test/globals.lua
+lua-5.1-alpha/test/hello.lua
+lua-5.1-alpha/test/life.lua
+lua-5.1-alpha/test/luac.lua
+lua-5.1-alpha/test/printf.lua
+lua-5.1-alpha/test/readonly.lua
+lua-5.1-alpha/test/sieve.lua
+lua-5.1-alpha/test/sort.lua
+lua-5.1-alpha/test/table.lua
+lua-5.1-alpha/test/trace-calls.lua
+lua-5.1-alpha/test/trace-globals.lua
+lua-5.1-alpha/test/xd.lua
END OF MANIFEST
diff --git a/Makefile b/Makefile
index beb36e86..58cbcca4 100644
--- a/Makefile
+++ b/Makefile
@@ -26,7 +26,7 @@ INSTALL_DATA= cp
# What to install.
TO_BIN= lua luac
-TO_INC= lua.h luaconf.h lualib.h lauxlib.h
+TO_INC= lua.h luaconf.h lualib.h lauxlib.h ../etc/lua.hpp
TO_LIB= liblua.a
TO_MAN= lua.1 luac.1
@@ -49,6 +49,22 @@ install: all
local:
$(MAKE) install INSTALL_TOP=.. INSTALL_EXEC="cp -p" INSTALL_DATA="cp -p"
+# convenience targets for usual platforms
+
+ansi:
+ cd src; $(MAKE) MYCFLAGS=-DLUA_ANSI
+
+linux:
+ cd src; $(MAKE) MYCFLAGS=-DLUA_USE_DLOPEN MYLIBS="-Wl,-E -ldl"
+
+bsd:
+ cd src; $(MAKE) MYCFLAGS=-DLUA_USE_DLOPEN MYLIBS="-Wl,-E"
+
+mingw:
+ cd src; $(MAKE) "LUA_A=lua51.dll" "LUA_T=lua.exe" \
+ "AR=gcc -shared -o" "RANLIB=strip --strip-unneeded" \
+ "MYCFLAGS=-DLUA_BUILD_AS_DLL" "MYLIBS=" MYLDFLAGS=-s" lua.exe
+
# echo config parameters
echo:
@echo ""
diff --git a/README b/README
index 1efe91ff..668f569d 100644
--- a/README
+++ b/README
@@ -1,4 +1,4 @@
-This is Lua 5.1 (work).
+This is Lua 5.1 (alpha).
See HISTORY for a summary of changes since the last released version.
* What is Lua?
@@ -27,9 +27,9 @@ See HISTORY for a summary of changes since the last released version.
* Origin
------
- Lua is developed at Tecgraf, the Computer Graphics Technology Group
- of PUC-Rio (the Pontifical Catholic University of Rio de Janeiro in Brazil).
- Tecgraf is a laboratory of the Department of Computer Science.
+ Lua is developed at Lua.org, a laboratory of the Department of Computer
+ Science of PUC-Rio (the Pontifical Catholic University of Rio de Janeiro
+ in Brazil).
For more information about the authors, see http://www.lua.org/authors.html .
(end of README)
diff --git a/doc/contents.html b/doc/contents.html
index 06bd6fb4..9db0cafa 100644
--- a/doc/contents.html
+++ b/doc/contents.html
@@ -1,32 +1,25 @@
<HTML>
<HEAD>
-<TITLE>Lua: 5.0 reference manual - contents</TITLE>
+<TITLE>Lua 5.1 reference manual - contents</TITLE>
+<LINK REL="stylesheet" TYPE="text/css" HREF="lua.css">
</HEAD>
<BODY BGCOLOR="#FFFFFF">
<HR>
<H1>
-<A HREF="http://www.lua.org/home.html"><IMG SRC="logo.gif" ALT="Lua" BORDER=0></A>
-Reference manual for Lua 5.0
+<A HREF="http://www.lua.org/"><IMG SRC="logo.gif" ALT="Lua" BORDER=0></A>
+Lua 5.1 Reference Manual
</H1>
-<A HREF="manual.html">Lua 5.0 Reference Manual</A>
-[
-<A HREF="manual.html">top</A>
-|
-<A HREF="http://www.lua.org/ftp/refman-5.0.ps.gz">ps</A>
-|
-<A HREF="http://www.lua.org/ftp/refman-5.0.pdf">pdf</A>
-]
-<P>
-
<SMALL>
<A HREF="http://www.lua.org/copyright.html">Copyright</A>
-&copy; 2003 Tecgraf, PUC-Rio. All rights reserved.</SMALL>
+&copy; 2005 Lua.org, PUC-Rio. All rights reserved.
+</SMALL>
<HR>
<UL>
+<LI><A HREF="manual.html">Top</A>
<LI><A HREF="manual.html#1">1 - Introduction</A>
<LI><A HREF="manual.html#2">2 - The Language</A>
<UL>
@@ -52,62 +45,49 @@ Reference manual for Lua 5.0
<LI><A HREF="manual.html#2.5.2">2.5.2 - Relational Operators</A>
<LI><A HREF="manual.html#2.5.3">2.5.3 - Logical Operators</A>
<LI><A HREF="manual.html#2.5.4">2.5.4 - Concatenation</A>
-<LI><A HREF="manual.html#2.5.5">2.5.5 - Precedence</A>
-<LI><A HREF="manual.html#2.5.6">2.5.6 - Table Constructors</A>
-<LI><A HREF="manual.html#2.5.7">2.5.7 - Function Calls</A>
-<LI><A HREF="manual.html#2.5.8">2.5.8 - Function Definitions</A>
+<LI><A HREF="manual.html#2.5.5">2.5.5 - The Length Operator</A>
+<LI><A HREF="manual.html#2.5.6">2.5.6 - Precedence</A>
+<LI><A HREF="manual.html#2.5.7">2.5.7 - Table Constructors</A>
+<LI><A HREF="manual.html#2.5.8">2.5.8 - Function Calls</A>
+<LI><A HREF="manual.html#2.5.9">2.5.9 - Function Definitions</A>
</UL>
-</UL>
-<UL>
<LI><A HREF="manual.html#2.6">2.6 - Visibility Rules</A>
<LI><A HREF="manual.html#2.7">2.7 - Error Handling</A>
<LI><A HREF="manual.html#2.8">2.8 - Metatables</A>
-<LI><A HREF="manual.html#2.9">2.9 - Garbage Collection</A>
+<LI><A HREF="manual.html#2.9">2.9 - Environments</A>
+<LI><A HREF="manual.html#2.10">2.10 - Garbage Collection</A>
<UL>
-<LI><A HREF="manual.html#2.9.1">2.9.1 - Garbage-Collection Metamethods</A>
-<LI><A HREF="manual.html#2.9.2">2.9.2 - Weak Tables</A>
+<LI><A HREF="manual.html#2.10.1">2.10.1 - Garbage-Collection Metamethods</A>
+<LI><A HREF="manual.html#2.10.2">2.10.2 - Weak Tables</A>
</UL>
-<LI><A HREF="manual.html#2.10">2.10 - Coroutines</A>
+<LI><A HREF="manual.html#2.11">2.11 - Coroutines</A>
</UL>
<LI><A HREF="manual.html#3">3 - The Application Program Interface</A>
<UL>
-<LI><A HREF="manual.html#3.1">3.1 - States</A>
-<LI><A HREF="manual.html#3.2">3.2 - The Stack and Indices</A>
-<LI><A HREF="manual.html#3.3">3.3 - Stack Manipulation</A>
-<LI><A HREF="manual.html#3.4">3.4 - Querying the Stack</A>
-<LI><A HREF="manual.html#3.5">3.5 - Getting Values from the Stack</A>
-<LI><A HREF="manual.html#3.6">3.6 - Pushing Values onto the Stack</A>
-<LI><A HREF="manual.html#3.7">3.7 - Controlling Garbage Collection</A>
-<LI><A HREF="manual.html#3.8">3.8 - Userdata</A>
-<LI><A HREF="manual.html#3.9">3.9 - Metatables</A>
-<LI><A HREF="manual.html#3.10">3.10 - Loading Lua Chunks</A>
-<LI><A HREF="manual.html#3.11">3.11 - Manipulating Tables</A>
-<LI><A HREF="manual.html#3.12">3.12 - Manipulating Environments</A>
-<LI><A HREF="manual.html#3.13">3.13 - Using Tables as Arrays</A>
-<LI><A HREF="manual.html#3.14">3.14 - Calling Functions</A>
-<LI><A HREF="manual.html#3.15">3.15 - Protected Calls</A>
-<LI><A HREF="manual.html#3.16">3.16 - Defining C Functions</A>
-<LI><A HREF="manual.html#3.17">3.17 - Defining C Closures</A>
-<LI><A HREF="manual.html#3.18">3.18 - Registry</A>
-<LI><A HREF="manual.html#3.19">3.19 - Error Handling in C</A>
-<LI><A HREF="manual.html#3.20">3.20 - Threads</A>
+<LI><A HREF="manual.html#3.1">3.1 - The Stack</A>
+<LI><A HREF="manual.html#3.2">3.2 - Stack Size</A>
+<LI><A HREF="manual.html#3.3">3.3 - Pseudo-Indices</A>
+<LI><A HREF="manual.html#3.4">3.4 - C Closures</A>
+<LI><A HREF="manual.html#3.5">3.5 - Registry</A>
+<LI><A HREF="manual.html#3.6">3.6 - Error Handling in C</A>
+<LI><A HREF="manual.html#3.7">3.7 - Functions and Types</A>
+<LI><A HREF="manual.html#3.8">3.8 - The Debug Interface</A>
</UL>
-<LI><A HREF="manual.html#4">4 - The Debug Interface</A>
+<LI><A HREF="manual.html#4">4 - The Auxiliary Library</A>
<UL>
-<LI><A HREF="manual.html#4.1">4.1 - Stack and Function Information</A>
-<LI><A HREF="manual.html#4.2">4.2 - Manipulating Local Variables and Upvalues</A>
-<LI><A HREF="manual.html#4.3">4.3 - Hooks</A>
+<LI><A HREF="manual.html#4.1">4.1 - Functions and Types</A>
</UL>
<LI><A HREF="manual.html#5">5 - Standard Libraries</A>
<UL>
<LI><A HREF="manual.html#5.1">5.1 - Basic Functions</A>
<LI><A HREF="manual.html#5.2">5.2 - Coroutine Manipulation</A>
-<LI><A HREF="manual.html#5.3">5.3 - String Manipulation</A>
-<LI><A HREF="manual.html#5.4">5.4 - Table Manipulation</A>
-<LI><A HREF="manual.html#5.5">5.5 - Mathematical Functions</A>
-<LI><A HREF="manual.html#5.6">5.6 - Input and Output Facilities</A>
-<LI><A HREF="manual.html#5.7">5.7 - Operating System Facilities</A>
-<LI><A HREF="manual.html#5.8">5.8 - The Reflexive Debug Interface</A>
+<LI><A HREF="manual.html#5.3">5.3 - Packages and Modules</A>
+<LI><A HREF="manual.html#5.4">5.4 - String Manipulation</A>
+<LI><A HREF="manual.html#5.5">5.5 - Table Manipulation</A>
+<LI><A HREF="manual.html#5.6">5.6 - Mathematical Functions</A>
+<LI><A HREF="manual.html#5.7">5.7 - Input and Output Facilities</A>
+<LI><A HREF="manual.html#5.8">5.8 - Operating System Facilities</A>
+<LI><A HREF="manual.html#5.9">5.9 - The Reflexive Debug Interface</A>
</UL>
<LI><A HREF="manual.html#6">6 - Lua Stand-alone</A>
<LI><A HREF="manual.html#BNF">The Complete Syntax of Lua</A>
@@ -116,7 +96,7 @@ Reference manual for Lua 5.0
<HR>
<SMALL>
Last update:
-Wed May 7 18:34:34 EST 2003
+Fri Sep 9 14:44:10 BRST 2005
</SMALL>
</BODY>
diff --git a/doc/lua.1 b/doc/lua.1
index c9bba7d7..39c7d8e4 100644
--- a/doc/lua.1
+++ b/doc/lua.1
@@ -1,5 +1,5 @@
-.\" lua.man,v 1.8 2003/04/02 00:05:20 lhf Exp
-.TH LUA 1 "2003/04/02 00:05:20"
+.\" $Id: lua.man,v 1.9 2005/09/02 16:29:34 lhf Exp $
+.TH LUA 1 "$Date: 2005/09/02 16:29:34 $"
.SH NAME
lua \- Lua interpreter
.SH SYNOPSIS
@@ -141,9 +141,9 @@ enter interactive mode after
.I script
is executed.
.TP
-.BI \-l " file"
+.BI \-l " module"
call
-.BI require( file )
+.BI require( module )
before executing
.IR script.
Typically used to load libraries
@@ -163,5 +163,4 @@ R. Ierusalimschy,
L. H. de Figueiredo,
and
W. Celes
-(lua@tecgraf.puc-rio.br)
.\" EOF
diff --git a/doc/lua.css b/doc/lua.css
new file mode 100644
index 00000000..90f62312
--- /dev/null
+++ b/doc/lua.css
@@ -0,0 +1,15 @@
+body {
+ color: #000000 ;
+ background-color: #FFFFFF ;
+ font-family: sans-serif ;
+}
+
+a:link {
+ color: #000080 ;
+}
+
+a:link:hover, a:visited:hover {
+ color: #000080 ;
+ background-color: #E0E0FF ;
+}
+
diff --git a/doc/lua.html b/doc/lua.html
index 073d4b52..3bc0d8ae 100644
--- a/doc/lua.html
+++ b/doc/lua.html
@@ -1,7 +1,8 @@
-<!-- lua.man,v 1.8 2003/04/02 00:05:20 lhf Exp -->
+<!-- $Id: lua.man,v 1.9 2005/09/02 16:29:34 lhf Exp $ -->
<HTML>
<HEAD>
<TITLE>LUA man page</TITLE>
+<LINK REL="stylesheet" TYPE="text/css" HREF="lua.css">
</HEAD>
<BODY BGCOLOR="#FFFFFF">
@@ -147,9 +148,9 @@ enter interactive mode after
<I>script</I>
is executed.
<P>
-<B>-l "</B><I>file"</I>
+<B>-l "</B><I>module"</I>
call
-<B>require( file</B><I>)</I>
+<B>require( module</B><I>)</I>
before executing
<I></I>script.
Typically used to load libraries
@@ -169,7 +170,6 @@ R. Ierusalimschy,
L. H. de Figueiredo,
and
W. Celes
-(<A HREF="mailto:lua-NO-SPAM-THANKS@tecgraf.puc-rio.br">lua AT tecgraf.puc-rio.br</A>)
<!-- EOF -->
</BODY>
</HTML>
diff --git a/doc/luac.1 b/doc/luac.1
index c6523060..7a44e2f2 100644
--- a/doc/luac.1
+++ b/doc/luac.1
@@ -1,5 +1,5 @@
-.\" luac.man,v 1.25 2002/12/13 11:45:12 lhf Exp
-.TH LUAC 1 "2002/12/13 11:45:12"
+.\" $Id: luac.man,v 1.26 2005/09/02 16:29:34 lhf Exp $
+.TH LUAC 1 "$Date: 2005/09/02 16:29:34 $"
.SH NAME
luac \- Lua compiler
.SH SYNOPSIS
@@ -38,14 +38,7 @@ option.
.LP
The binary files created by
.B luac
-are portable to all architectures with the same word size.
-This means that
-binary files created on a 32-bit platform (such as Intel)
-can be read without change in another 32-bit platform (such as Sparc),
-even if the byte order (``endianness'') is different.
-On the other hand,
-binary files created on a 16-bit platform cannot be read in a 32-bit platform,
-nor vice-versa.
+are portable only among architectures with the same word size and byte order.
.LP
In the command line,
you can mix
@@ -132,5 +125,4 @@ Error messages should be self explanatory.
L. H. de Figueiredo,
R. Ierusalimschy and
W. Celes
-(lua@tecgraf.puc-rio.br)
.\" EOF
diff --git a/doc/luac.html b/doc/luac.html
index 3a71622e..586b38e8 100644
--- a/doc/luac.html
+++ b/doc/luac.html
@@ -1,7 +1,8 @@
-<!-- luac.man,v 1.25 2002/12/13 11:45:12 lhf Exp -->
+<!-- $Id: luac.man,v 1.26 2005/09/02 16:29:34 lhf Exp $ -->
<HTML>
<HEAD>
<TITLE>LUAC man page</TITLE>
+<LINK REL="stylesheet" TYPE="text/css" HREF="lua.css">
</HEAD>
<BODY BGCOLOR="#FFFFFF">
@@ -44,14 +45,7 @@ option.
<P>
The binary files created by
<B>luac</B>
-are portable to all architectures with the same word size.
-This means that
-binary files created on a 32-bit platform (such as Intel)
-can be read without change in another 32-bit platform (such as Sparc),
-even if the byte order (``endianness'') is different.
-On the other hand,
-binary files created on a 16-bit platform cannot be read in a 32-bit platform,
-nor vice-versa.
+are portable only among architectures with the same word size and byte order.
<P>
In the command line,
you can mix
@@ -138,7 +132,6 @@ Error messages should be self explanatory.
L. H. de Figueiredo,
R. Ierusalimschy and
W. Celes
-(<A HREF="mailto:lua-NO-SPAM-THANKS@tecgraf.puc-rio.br">lua AT tecgraf.puc-rio.br</A>)
<!-- EOF -->
</BODY>
</HTML>
diff --git a/doc/manual.html b/doc/manual.html
new file mode 100644
index 00000000..b55232bd
--- /dev/null
+++ b/doc/manual.html
@@ -0,0 +1,5980 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
+<html>
+
+<head>
+<title>Lua 5.1 Reference Manual</title>
+<LINK REL="stylesheet" TYPE="text/css" HREF="lua.css">
+</head>
+
+<body BGCOLOR="#FFFFFF">
+
+<hr>
+<h1>
+<a href="http://www.lua.org/home.html"><img src="logo.gif" ALT="[Lua logo]" border=0></a>
+Lua 5.1 Reference Manual
+</h1>
+
+by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes
+<p>
+<small>
+<a href="http://www.lua.org/copyright.html">Copyright</a>
+&copy; 2005 Lua.org, PUC-Rio. All rights reserved.
+</small>
+<hr>
+
+<p>
+<p>
+<!-- ====================================================================== -->
+
+
+
+<p>
+<a name="1"></a><h1>1 - Introduction</h1>
+
+<p>Lua is an extension programming language designed to support
+general procedural programming with data description
+facilities.
+It also offers good support for object-oriented programming,
+functional programming, and data-driven programming.
+Lua is intended to be used as a powerful, light-weight
+configuration language for any program that needs one.
+Lua is implemented as a library, written in <em>clean</em> C
+(that is, in the common subset of ANSI C and C++).
+
+<p>Being an extension language, Lua has no notion of a "main" program:
+it only works <em>embedded</em> in a host client,
+called the <em>embedding program</em> or simply the <em>host</em>.
+This host program can invoke functions to execute a piece of Lua code,
+can write and read Lua variables,
+and can register C functions to be called by Lua code.
+Through the use of C functions, Lua can be augmented to cope with
+a wide range of different domains,
+thus creating customized programming languages sharing a syntactical framework.
+
+<p>The Lua distribution includes a stand-alone embedding program,
+<code>lua</code>, that uses the Lua library to offer a complete Lua interpreter.
+
+<p>Lua is free software,
+and is provided as usual with no guarantees,
+as stated in its copyright notice.
+The implementation described in this manual is available
+at Lua's official web site, <code>www.lua.org</code>.
+
+<p>Like any other reference manual,
+this document is dry in places.
+For a discussion of the decisions behind the design of Lua,
+see the papers below,
+which are available at Lua's web site.
+<ul>
+<li>
+R. Ierusalimschy, L. H. de Figueiredo, and W. Celes.
+Lua&mdash;an extensible extension language.
+<em>Software: Practice &#038; Experience</em> <b>26</b>:6 (1996) 635&ndash;652.
+<li>
+L. H. de Figueiredo, R. Ierusalimschy, and W. Celes.
+The design and implementation of a language for extending applications.
+<em>Proceedings of XXI Brazilian Seminar on Software and Hardware</em>
+(1994) 273&ndash;283.
+<li>
+L. H. de Figueiredo, R. Ierusalimschy, and W. Celes.
+Lua: an extensible embedded language.
+<em>Dr. Dobb's Journal</em> <b>21</b>:12 (Dec 1996) 26&ndash;33.
+<li>
+R. Ierusalimschy, L. H. de Figueiredo, and W. Celes.
+The evolution of an extension language: a history of Lua,
+<em>Proceedings of V Brazilian Symposium on Programming Languages</em> (2001) B-14&ndash;B-28.
+</ul>
+
+<p>Lua means "moon" in Portuguese and is pronounced LOO-ah.
+
+<p>
+<a name="language"></a><a name="2"></a><h1>2 - The Language</h1>
+
+<p>This section describes the lexis, the syntax, and the semantics of Lua.
+In other words,
+this section describes
+which tokens are valid,
+how they can be combined,
+and what their combinations mean.
+
+<p>The language constructs will be explained using the usual extended BNF,
+in which
+{<em>a</em>} means 0 or more <em>a</em>'s, and
+[<em>a</em>] means an optional <em>a</em>.
+Non-terminals are shown in <em>italics</em>,
+keywords are shown in <b>bold</b>,
+and other terminal symbols are shown in <code>typewriter</code> font,
+enclosed in single quotes.
+
+<p><a name="lexical"></a><a name="2.1"></a><h2>2.1 - Lexical Conventions</h2>
+
+<p><em>Names</em> in Lua can be any string of letters,
+digits, and underscores,
+not beginning with a digit.
+This coincides with the definition of names in most languages.
+(The definition of letter depends on the current locale:
+any character considered alphabetic by the current locale
+can be used in an identifier.)
+
+<p>The following <em>keywords</em> are reserved
+and cannot be used as names:
+
+<PRE>
+ and break do else elseif
+ end false for function if
+ in local nil not or
+ repeat return then true until while
+</PRE>
+
+<p>Lua is a case-sensitive language:
+<code>and</code> is a reserved word, but <code>And</code> and <code>AND</code>
+are two different, valid names.
+As a convention, names starting with an underscore followed by
+uppercase letters (such as <a href="#pdf-_VERSION"><code>_VERSION</code></a>)
+are reserved for internal variables used by Lua.
+
+<p>The following strings denote other tokens:
+<PRE>
+ + - * / % ^ #
+ == ~= &#060;= >= &#060; > =
+ ( ) { } [ ]
+ ; : , . .. ...
+</PRE>
+
+<p><em>Literal strings</em>
+can be delimited by matching single or double quotes,
+and can contain the following C-like escape sequences:
+<ul>
+<li><b><code>\a</code></b> &mdash; bell
+<li><b><code>\b</code></b> &mdash; backspace
+<li><b><code>\f</code></b> &mdash; form feed
+<li><b><code>\n</code></b> &mdash; newline
+<li><b><code>\r</code></b> &mdash; carriage return
+<li><b><code>\t</code></b> &mdash; horizontal tab
+<li><b><code>\v</code></b> &mdash; vertical tab
+<li><b><code>\\</code></b> &mdash; backslash
+<li><b><code>\"</code></b> &mdash; quotation mark
+<li><b><code>\'</code></b> &mdash; apostrophe
+</ul>
+Moreover, a `<code>\</code><em>newline</em>&acute;
+(that is, a backslash followed by a real newline)
+results in a newline in the string.
+A character in a string may also be specified by its numerical value
+using the escape sequence `<code>\</code><em>ddd</em>&acute;,
+where <em>ddd</em> is a sequence of up to three decimal digits.
+Strings in Lua may contain any 8-bit value, including embedded zeros,
+which can be specified as `<code>\0</code>&acute;.
+
+<p>Literal strings can also be defined using a long format
+enclosed by <em>l-brackets</em> (long brackets).
+We define an <em>opening l-bracket of level <em>n</em></em> as an opening
+square bracket followed by <em>n</em> equal signs followed by another
+opening square bracket.
+So, an opening l-bracket of level 0 is written as <code>[[</code>,
+an opening l-bracket of level 1 is written as <code>[=[</code>,
+and so on.
+A <em>closing l-bracket</em> is defined similarly;
+for instance, a closing l-bracket of level 4 is written as <code>]====]</code>.
+A long string starts with an opening l-bracket of any level and
+ends at the first closing l-bracket of the same level.
+Literals in this bracketed form may run for several lines,
+do not interpret any escape sequences,
+and ignore l-brackets of any other level.
+
+<p>For convenience,
+when the opening l-bracket is immediately followed by a newline,
+the newline is not included in the string.
+As an example, in a system using ASCII
+(in which `<code>a</code>&acute; is coded as 97,
+newline is coded as 10, and `<code>1</code>&acute; is coded as 49),
+the four literals below denote the same string:
+<PRE>
+ (1) "alo\n123\""
+ (2) '\97lo\10\04923"'
+ (3) [[alo
+ 123"]]
+ (4) [==[
+ alo
+ 123"]==]
+</PRE>
+
+<p><em>Numerical constants</em> may be written with an optional decimal part
+and an optional decimal exponent.
+Examples of valid numerical constants are
+<PRE>
+ 3 3.0 3.1416 314.16e-2 0.31416E1
+</PRE>
+
+<p><em>Comments</em> start anywhere outside a string with a
+double hyphen (<code>--</code>).
+If the text immediately after <code>--</code> is not an opening l-bracket,
+the comment is a <em>short comment</em>,
+which runs until the end of the line.
+Otherwise, it is a <em>long comment</em>,
+which runs until the corresponding closing l-bracket.
+
+<p><a name="TypesSec"></a><a name="2.2"></a><h2>2.2 - Values and Types</h2>
+
+<p>Lua is a <em>dynamically typed language</em>.
+That means that
+variables do not have types; only values do.
+There are no type definitions in the language.
+All values carry their own type.
+
+<p>There are eight basic types in Lua:
+<em>nil</em>, <em>boolean</em>, <em>number</em>,
+<em>string</em>, <em>function</em>, <em>userdata</em>,
+<em>thread</em>, and <em>table</em>.
+<em>Nil</em> is the type of the value <B>nil</B>,
+whose main property is to be different from any other value;
+usually it represents the absence of a useful value.
+<em>Boolean</em> is the type of the values <B>false</B> and <B>true</B>.
+In Lua, both <B>nil</B> and <B>false</B> make a condition false;
+any other value makes it true.
+<em>Number</em> represents real (double-precision floating-point) numbers.
+(It is easy to build Lua interpreters that use other
+internal representations for numbers,
+such as single-precision float or long integers.
+See file <code>luaconf.h</code>.)
+<em>String</em> represents arrays of characters.
+
+Lua is 8-bit clean:
+Strings may contain any 8-bit character,
+including embedded zeros (<code>'\0'</code>) (see <a href="#lexical">2.1</a>).
+
+<p>Functions are <em>first-class values</em> in Lua.
+That means that functions can be stored in variables,
+passed as arguments to other functions, and returned as results.
+Lua can call (and manipulate) functions written in Lua and
+functions written in C
+(see <a href="#functioncall">2.5.8</a>).
+
+<p>The type <em>userdata</em> is provided to allow arbitrary C data to
+be stored in Lua variables.
+This type corresponds to a block of raw memory
+and has no pre-defined operations in Lua,
+except assignment and identity test.
+However, by using <em>metatables</em>,
+the programmer can define operations for userdata values
+(see <a href="#metatable">2.8</a>).
+Userdata values cannot be created or modified in Lua,
+only through the C API.
+This guarantees the integrity of data owned by the host program.
+
+<p>The type <em>thread</em> represents independent threads of execution
+and it is used to implement coroutines (see <a href="#coroutine">2.11</a>).
+
+<p>The type <em>table</em> implements associative arrays,
+that is, arrays that can be indexed not only with numbers,
+but with any value (except <B>nil</B>).
+Moreover,
+tables can be <em>heterogeneous</em>,
+that is, they can contain values of all types (except <B>nil</B>).
+Tables are the sole data structuring mechanism in Lua;
+they may be used to represent ordinary arrays,
+symbol tables, sets, records, graphs, trees, etc.
+To represent records, Lua uses the field name as an index.
+The language supports this representation by
+providing <code>a.name</code> as syntactic sugar for <code>a["name"]</code>.
+There are several convenient ways to create tables in Lua
+(see <a href="#tableconstructor">2.5.7</a>).
+
+<p>Like indices,
+the value of a table field can be of any type (except <B>nil</B>).
+In particular,
+because functions are first class values,
+table fields may contain functions.
+Thus tables may also carry <em>methods</em> (see <a href="#func-def">2.5.9</a>).
+
+<p>Tables, functions, and userdata values are <em>objects</em>:
+variables do not actually <em>contain</em> these values,
+only <em>references</em> to them.
+Assignment, parameter passing, and function returns
+always manipulate references to such values;
+these operations do not imply any kind of copy.
+
+<p>The library function <a href="#pdf-type"><code>type</code></a> returns a string describing the type
+of a given value.
+
+<p><a name="coercion"></a><a name="2.2.1"></a><h3>2.2.1 - Coercion</h3>
+
+<p>Lua provides automatic conversion between
+string and number values at run time.
+Any arithmetic operation applied to a string tries to convert
+that string to a number, following the usual rules.
+Conversely, whenever a number is used where a string is expected,
+the number is converted to a string, in a reasonable format.
+For complete control of how numbers are converted to strings,
+use the <code>format</code> function from the string library
+(see <a href="#pdf-string.format"><code>string.format</code></a>).
+
+<p><a name="variables"></a><a name="2.3"></a><h2>2.3 - Variables</h2>
+
+<p>Variables are places that store values.
+
+There are three kinds of variables in Lua:
+global variables, local variables, and table fields.
+
+<p>A single name can denote a global variable or a local variable
+(or a formal parameter of a function,
+which is a particular form of local variable):
+<pre>
+ var ::= Name
+</pre>
+Variables are assumed to be global unless explicitly declared local
+(see <a href="#localvar">2.4.7</a>).
+Local variables are <em>lexically scoped</em>:
+Local variables can be freely accessed by functions
+defined inside their scope (see <a href="#visibility">2.6</a>).
+
+<p>Before the first assignment to a variable, its value is <B>nil</B>.
+
+<p>Square brackets are used to index a table:
+<pre>
+ var ::= prefixexp `<b>[</b>&acute; exp `<b>]</b>&acute;
+</pre>
+The first expression (<em>prefixexp</em>) should result in a table value;
+the second expression (<em>exp</em>)
+identifies a specific entry inside that table.
+The expression denoting the table to be indexed has a restricted syntax;
+see <a href="#expressions">2.5</a> for details.
+
+<p>The syntax <code>var.NAME</code> is just syntactic sugar for
+<code>var["NAME"]</code>:
+<pre>
+ var ::= prefixexp `<b>.</b>&acute; Name
+</pre>
+
+<p>The meaning of accesses to global variables
+and table fields can be changed via metatables.
+An access to an indexed variable <code>t[i]</code> is equivalent to
+a call <code>gettable_event(t,i)</code>.
+(See <a href="#metatable">2.8</a> for a complete description of the
+<code>gettable_event</code> function.
+This function is not defined or callable in Lua.
+We use it here only for explanatory purposes.)
+
+<p>All global variables live as fields in ordinary Lua tables,
+called <em>environment tables</em> or simply
+<em>environments</em> (see <a href="#environ">2.9</a>).
+Each function has its own reference to an environment,
+so that all global variables in that function
+will refer to that environment table.
+When a function is created,
+it inherits the environment from the function that created it.
+To replace or get the environment table of a Lua function,
+you call <a href="#pdf-setfenv"><code>setfenv</code></a> or <a href="#pdf-getfenv"><code>getfenv</code></a>.
+(You can only manipulate the environment of C functions
+through the debug library; (see <a href="#libdebug">5.9</a>).)
+
+<p>An access to a global variable <code>x</code>
+is equivalent to <code>_env.x</code>,
+which in turn is equivalent to
+<PRE>
+ gettable_event(_env, "x")
+</PRE>
+where <code>_env</code> is the environment of the running function.
+(See <a href="#metatable">2.8</a> for a complete description of the
+<code>gettable_event</code> function.
+This function is not defined or callable in Lua.
+Similarly, the <code>_env</code> variable is not defined in Lua.
+We use them here only for explanatory purposes.)
+
+<p><a name="stats"></a><a name="2.4"></a><h2>2.4 - Statements</h2>
+
+<p>Lua supports an almost conventional set of statements,
+similar to those in Pascal or C.
+This set includes
+assignment, control structures, procedure calls,
+table constructors, and variable declarations.
+
+<p><a name="chunks"></a><a name="2.4.1"></a><h3>2.4.1 - Chunks</h3>
+
+<p>The unit of execution of Lua is called a <em>chunk</em>.
+A chunk is simply a sequence of statements,
+which are executed sequentially.
+Each statement can be optionally followed by a semicolon:
+<pre>
+ chunk ::= {stat [`<b>;</b>&acute;]}
+</pre>
+
+<p>Lua handles a chunk as the body of an anonymous function
+with a variable number of arguments
+(see <a href="#func-def">2.5.9</a>).
+As such, chunks can define local variables,
+receive arguments, and return values.
+
+<p>A chunk may be stored in a file or in a string inside the host program.
+When a chunk is executed, first it is pre-compiled into opcodes for
+a virtual machine,
+and then the compiled code is executed
+by an interpreter for the virtual machine.
+
+<p>Chunks may also be pre-compiled into binary form;
+see program <code>luac</code> for details.
+Programs in source and compiled forms are interchangeable;
+Lua automatically detects the file type and acts accordingly.
+
+
+<p><a name="2.4.2"></a><h3>2.4.2 - Blocks</h3>
+A block is a list of statements;
+syntactically, a block is equal to a chunk:
+<pre>
+ block ::= chunk
+</pre>
+
+<p>A block may be explicitly delimited to produce a single statement:
+<pre>
+ stat ::= <b>do</b> block <b>end</b>
+</pre>
+Explicit blocks are useful
+to control the scope of variable declarations.
+Explicit blocks are also sometimes used to
+add a <b>return</b> or <b>break</b> statement in the middle
+of another block (see <a href="#control">2.4.4</a>).
+
+
+<p><a name="assignment"></a><a name="2.4.3"></a><h3>2.4.3 - Assignment</h3>
+
+<p>Lua allows multiple assignment.
+Therefore, the syntax for assignment
+defines a list of variables on the left side
+and a list of expressions on the right side.
+The elements in both lists are separated by commas:
+<pre>
+ stat ::= varlist1 `<b>=</b>&acute; explist1
+ varlist1 ::= var {`<b>,</b>&acute; var}
+ explist1 ::= exp {`<b>,</b>&acute; exp}
+</pre>
+Expressions are discussed in <a href="#expressions">2.5</a>.
+
+<p>Before the assignment,
+the list of values is <em>adjusted</em> to the length of
+the list of variables.
+If there are more values than needed,
+the excess values are thrown away.
+If there are fewer values than needed,
+the list is extended with as many <B>nil</B>'s as needed.
+If the list of expressions ends with a function call,
+then all values returned by that function call enter in the list of values,
+before the adjustment
+(except when the call is enclosed in parentheses; see <a href="#expressions">2.5</a>).
+
+<p>The assignment statement first evaluates all its expressions
+and only then are the assignments performed.
+Thus the code
+<PRE>
+ i = 3
+ i, a[i] = i+1, 20
+</PRE>
+sets <code>a[3]</code> to 20, without affecting <code>a[4]</code>
+because the <code>i</code> in <code>a[i]</code> is evaluated (to 3)
+before it is assigned 4.
+Similarly, the line
+<PRE>
+ x, y = y, x
+</PRE>
+exchanges the values of <code>x</code> and <code>y</code>.
+
+<p>The meaning of assignments to global variables
+and table fields can be changed via metatables.
+An assignment to an indexed variable <code>t[i] = val</code> is equivalent to
+<code>settable_event(t,i,val)</code>.
+(See <a href="#metatable">2.8</a> for a complete description of the
+<code>settable_event</code> function.
+This function is not defined or callable in Lua.
+We use it here only for explanatory purposes.)
+
+<p>An assignment to a global variable <code>x = val</code>
+is equivalent to the assignment
+<code>_env.x = val</code>,
+which in turn is equivalent to
+<PRE>
+ settable_event(_env, "x", val)
+</PRE>
+where <code>_env</code> is the environment of the running function.
+(The <code>_env</code> variable is not defined in Lua.
+We use it here only for explanatory purposes.)
+
+<p><a name="control"></a><a name="2.4.4"></a><h3>2.4.4 - Control Structures</h3>
+The control structures
+<b>if</b>, <b>while</b>, and <b>repeat</b> have the usual meaning and
+familiar syntax:
+
+
+
+<pre>
+ stat ::= <b>while</b> exp <b>do</b> block <b>end</b>
+ stat ::= <b>repeat</b> block <b>until</b> exp
+ stat ::= <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b>
+</pre>
+Lua also has a <b>for</b> statement, in two flavors (see <a href="#for">2.4.5</a>).
+
+<p>The condition expression <em>exp</em> of a
+control structure may return any value.
+Both <B>false</B> and <B>nil</B> are considered false.
+All values different from <B>nil</B> and <B>false</B> are considered true
+(in particular, the number 0 and the empty string are also true).
+
+<p>In the <b>repeat</b>&ndash;<b>until</b> loop,
+the inner block does not end at the <b>until</b> keyword,
+but only after the condition.
+That means the condition can refer to local variables
+declared inside the loop.
+
+<p>The <b>return</b> statement is used to return values
+from a function or from a chunk.
+
+Functions and chunks may return more than one value,
+so the syntax for the <b>return</b> statement is
+<pre>
+ stat ::= <b>return</b> [explist1]
+</pre>
+
+<p>The <b>break</b> statement can be used to terminate the execution of a
+<b>while</b>, <b>repeat</b>, or <b>for</b> loop,
+skipping to the next statement after the loop:
+
+<pre>
+ stat ::= <b>break</b>
+</pre>
+A <b>break</b> ends the innermost enclosing loop.
+
+<p>For syntactic reasons, <b>return</b> and <b>break</b>
+statements can only be written as the <em>last</em> statement of a block.
+If it is really necessary to <b>return</b> or <b>break</b> in the
+middle of a block,
+then an explicit inner block can be used,
+as in the idioms
+`<code>do return end</code>&acute; and
+`<code>do break end</code>&acute;,
+because now <b>return</b> and <b>break</b> are the last statements in
+their (inner) blocks.
+
+<p><a name="for"></a><a name="2.4.5"></a><h3>2.4.5 - For Statement</h3>
+
+<p>The <b>for</b> statement has two forms:
+one numeric and one generic.
+
+
+<p>The numeric <b>for</b> loop repeats a block of code while a
+control variable runs through an arithmetic progression.
+It has the following syntax:
+<pre>
+ stat ::= <b>for</b> Name `<b>=</b>&acute; exp `<b>,</b>&acute; exp [`<b>,</b>&acute; exp] <b>do</b> block <b>end</b>
+</pre>
+The <em>block</em> is repeated for <em>name</em> starting at the value of
+the first <em>exp</em>, until it passes the second <em>exp</em> by steps of the
+third <em>exp</em>.
+More precisely, a <b>for</b> statement like
+<PRE>
+ for var = e1, e2, e3 do block end
+</PRE>
+is equivalent to the code:
+<PRE>
+ do
+ local _var, _limit, _step = tonumber(e1), tonumber(e2), tonumber(e3)
+ if not (_var and _limit and _step) then error() end
+ while (_step>0 and _var&#060;=_limit) or (_step&#060;=0 and _var>=_limit) do
+ local var = _var
+ block
+ _var = _var + _step
+ end
+ end
+</PRE>
+Note the following:
+<ul>
+<li> All three control expressions are evaluated only once,
+before the loop starts.
+They must all result in numbers.
+<li> <code>_var</code>, <code>_limit</code>, and <code>_step</code> are invisible variables.
+The names are here for explanatory purposes only.
+<li> If the third expression (the step) is absent,
+then a step of 1 is used.
+<li> You can use <b>break</b> to exit a <b>for</b> loop.
+<li> The loop variable <code>var</code> is local to the loop;
+you cannot use its value after the <b>for</b> ends or is broken.
+If you need the value of the loop variable <code>var</code>,
+then assign it to another variable before breaking or exiting the loop.
+</ul>
+
+<p>The generic <b>for</b> statement works over functions,
+called <em>iterators</em>.
+For each iteration, it calls its iterator function to produce a new value,
+stopping when the new value is <B>nil</B>.
+The generic <b>for</b> loop has the following syntax:
+<pre>
+ stat ::= <b>for</b> Name {`<b>,</b>&acute; Name} <b>in</b> explist1 <b>do</b> block <b>end</b>
+</pre>
+A <b>for</b> statement like
+<PRE>
+ for var_1, ..., var_n in explist do block end
+</PRE>
+is equivalent to the code:
+<PRE>
+ do
+ local _f, _s, _var = explist
+ while true do
+ local var_1, ... , var_n = _f(_s, _var)
+ _var = var_1
+ if _var == nil then break end
+ block
+ end
+ end
+</PRE>
+Note the following:
+<ul>
+<li> <code>explist</code> is evaluated only once.
+Its results are an <em>iterator</em> function,
+a <em>state</em>, and an initial value for the first <em>iterator variable</em>.
+<li> <code>_f</code>, <code>_s</code>, and <code>_var</code> are invisible variables.
+The names are here for explanatory purposes only.
+<li> You can use <b>break</b> to exit a <b>for</b> loop.
+<li> The loop variables <code>var_i</code> are local to the loop;
+you cannot use their values after the <b>for</b> ends.
+If you need these values,
+then assign them to other variables before breaking or exiting the loop.
+</ul>
+
+<p><a name="funcstat"></a><a name="2.4.6"></a><h3>2.4.6 - Function Calls as Statements</h3>
+To allow possible side-effects,
+function calls can be executed as statements:
+<pre>
+ stat ::= functioncall
+</pre>
+In this case, all returned values are thrown away.
+Function calls are explained in <a href="#functioncall">2.5.8</a>.
+
+<p><a name="localvar"></a><a name="2.4.7"></a><h3>2.4.7 - Local Declarations</h3>
+Local variables may be declared anywhere inside a block.
+The declaration may include an initial assignment:
+<pre>
+ stat ::= <b>local</b> namelist [`<b>=</b>&acute; explist1]
+ namelist ::= Name {`<b>,</b>&acute; Name}
+</pre>
+If present, an initial assignment has the same semantics
+of a multiple assignment (see <a href="#assignment">2.4.3</a>).
+Otherwise, all variables are initialized with <B>nil</B>.
+
+<p>A chunk is also a block (see <a href="#chunks">2.4.1</a>),
+so local variables can be declared in a chunk outside any explicit block.
+The scope of such local variables extends until the end of the chunk.
+
+<p>The visibility rules for local variables are explained in <a href="#visibility">2.6</a>.
+
+<p><a name="expressions"></a><a name="2.5"></a><h2>2.5 - Expressions</h2>
+
+<p>
+The basic expressions in Lua are the following:
+<pre>
+ exp ::= prefixexp
+ exp ::= <b>nil</b> | <b>false</b> | <b>true</b>
+ exp ::= Number
+ exp ::= Literal
+ exp ::= function
+ exp ::= tableconstructor
+ exp ::= `<b>...</b>&acute;
+ exp ::= exp binop exp
+ exp ::= unop exp
+ prefixexp ::= var | functioncall | `<b>(</b>&acute; exp `<b>)</b>&acute;
+</pre>
+
+<p>Numbers and literal strings are explained in <a href="#lexical">2.1</a>;
+variables are explained in <a href="#variables">2.3</a>;
+function definitions are explained in <a href="#func-def">2.5.9</a>;
+function calls are explained in <a href="#functioncall">2.5.8</a>;
+table constructors are explained in <a href="#tableconstructor">2.5.7</a>.
+Vararg expressions,
+denoted by three dots (...), can only be used inside
+vararg functions;
+they are explained in <a href="#func-def">2.5.9</a>.
+
+
+<p>Binary operators comprise arithmetic operators (see <a href="#arith">2.5.1</a>),
+relational operators (see <a href="#rel-ops">2.5.2</a>), and logical operators (see <a href="#logic">2.5.3</a>).
+Unary operators comprise the unary minus (see <a href="#arith">2.5.1</a>),
+the unary <b>not</b> (see <a href="#logic">2.5.3</a>),
+and the unary <em>length operator</em> (see <a href="#len-op">2.5.5</a>).
+
+<p>Both function calls and vararg expressions may result in multiple values.
+If the expression is used as a statement (see <a href="#funcstat">2.4.6</a>)
+(only possible for function calls),
+then its return list is adjusted to zero elements,
+thus discarding all returned values.
+If the expression is used inside another expression
+or in the middle of a list of expressions,
+then its result list is adjusted to one element,
+thus discarding all values except the first one.
+If the expression is used as the last element of a list of expressions,
+then no adjustment is made,
+unless the call is enclosed in parentheses.
+
+<p>Here are some examples:
+<PRE>
+ f() -- adjusted to 0 results
+ g(f(), x) -- f() is adjusted to 1 result
+ g(x, f()) -- g gets x plus all values returned by f()
+ a,b,c = f(), x -- f() is adjusted to 1 result (c gets nil)
+ a,b = ... -- a gets the first vararg parameter, b gets
+ -- the second (both a and b may get nil if there is
+ -- no corresponding vararg parameter)
+ a,b,c = x, f() -- f() is adjusted to 2 results
+ a,b,c = f() -- f() is adjusted to 3 results
+ return f() -- returns all values returned by f()
+ return ... -- returns all received vararg parameters
+ return x,y,f() -- returns x, y, and all values returned by f()
+ {f()} -- creates a list with all values returned by f()
+ {...} -- creates a list with all vararg parameters
+ {f(), nil} -- f() is adjusted to 1 result
+</PRE>
+
+<p>An expression enclosed in parentheses always results in only one value.
+Thus,
+<code>(f(x,y,z))</code> is always a single value,
+even if <code>f</code> returns several values.
+(The value of <code>(f(x,y,z))</code> is the first value returned by <code>f</code>
+or <B>nil</B> if <code>f</code> does not return any values.)
+
+<p><a name="arith"></a><a name="2.5.1"></a><h3>2.5.1 - Arithmetic Operators</h3>
+Lua supports the usual arithmetic operators:
+the binary <code>+</code> (addition),
+<code>-</code> (subtraction), <code>*</code> (multiplication),
+<code>/</code> (division), <code>%</code> (modulus), and <code>^</code> (exponentiation);
+and unary <code>-</code> (negation).
+If the operands are numbers, or strings that can be converted to
+numbers (see <a href="#coercion">2.2.1</a>),
+then all operations have the usual meaning.
+Exponentiation works for any exponent.
+For instance, <code>x^-0.5</code> computes the inverse of the square root of <code>x</code>.
+Modulus is defined as
+<PRE>
+ a % b == a - math.floor(a/b)*b
+</PRE>
+That is, it is the remaining of a division that rounds
+the quotient towards minus infinity.
+
+<p><a name="rel-ops"></a><a name="2.5.2"></a><h3>2.5.2 - Relational Operators</h3>
+The relational operators in Lua are
+<PRE>
+ == ~= &#060; > &#060;= >=
+</PRE>
+These operators always result in <B>false</B> or <B>true</B>.
+
+<p>Equality (<code>==</code>) first compares the type of its operands.
+If the types are different, then the result is <B>false</B>.
+Otherwise, the values of the operands are compared.
+Numbers and strings are compared in the usual way.
+Objects (tables, userdata, threads, and functions)
+are compared by <em>reference</em>:
+Two objects are considered equal only if they are the <em>same</em> object.
+Every time you create a new object (a table, userdata, or function),
+this new object is different from any previously existing object.
+
+<p>You can change the way that Lua compares tables and userdata
+using the "eq" metamethod (see <a href="#metatable">2.8</a>).
+
+<p>The conversion rules of <a href="#coercion">2.2.1</a>
+<em>do not</em> apply to equality comparisons.
+Thus, <code>"0"==0</code> evaluates to <B>false</B>,
+and <code>t[0]</code> and <code>t["0"]</code> denote different
+entries in a table.
+
+
+<p>The operator <code>~=</code> is exactly the negation of equality (<code>==</code>).
+
+<p>The order operators work as follows.
+If both arguments are numbers, then they are compared as such.
+Otherwise, if both arguments are strings,
+then their values are compared according to the current locale.
+Otherwise, Lua tries to call the "lt" or the "le"
+metamethod (see <a href="#metatable">2.8</a>).
+
+<p><a name="logic"></a><a name="2.5.3"></a><h3>2.5.3 - Logical Operators</h3>
+The logical operators in Lua are
+
+<PRE>
+ and or not
+</PRE>
+Like the control structures (see <a href="#control">2.4.4</a>),
+all logical operators consider both <B>false</B> and <B>nil</B> as false
+and anything else as true.
+
+
+<p>The operator <b>not</b> always returns <B>false</B> or <B>true</B>.
+
+<p>The conjunction operator <b>and</b> returns its first argument
+if this value is <B>false</B> or <B>nil</B>;
+otherwise, <b>and</b> returns its second argument.
+The disjunction operator <b>or</b> returns its first argument
+if this value is different from <B>nil</B> and <B>false</B>;
+otherwise, <b>or</b> returns its second argument.
+Both <b>and</b> and <b>or</b> use short-cut evaluation,
+that is,
+the second operand is evaluated only if necessary.
+For example,
+<PRE>
+ 10 or error() -> 10
+ nil or "a" -> "a"
+ nil and 10 -> nil
+ false and error() -> false
+ false and nil -> false
+ false or nil -> nil
+ 10 and 20 -> 20
+</PRE>
+
+<p><a name="concat"></a><a name="2.5.4"></a><h3>2.5.4 - Concatenation</h3>
+The string concatenation operator in Lua is
+denoted by two dots (`<code>..</code>&acute;).
+If both operands are strings or numbers, then they are converted to
+strings according to the rules mentioned in <a href="#coercion">2.2.1</a>.
+Otherwise, the "concat" metamethod is called (see <a href="#metatable">2.8</a>).
+
+<p><a name="len-op"></a><a name="2.5.5"></a><h3>2.5.5 - The Length Operator</h3>
+
+<p>The length operator is denoted by the prefix <code>#</code>.
+The length of a string is its number of bytes
+(that is, the usual meaning of string length when each
+character is one byte).
+The length of a table <code>t</code> is defined to be any
+integer index <code>n</code>
+such that <code>t[n]</code> is not <B>nil</B> and <code>t[n+1]</code> is <B>nil</B>;
+moreover, if <code>t[1]</code> is <B>nil</B>, <code>n</code> may be zero.
+
+<p>For a regular array, with non-nil values from 1 to a given <code>n</code>,
+its length is exactly that <code>n</code>,
+the index of its last value.
+If the array has "holes"
+(that is, <B>nil</B> values between other non-nil values),
+then <code>#t</code> may be any of the indices that precede a <B>nil</B> value
+(that is, it may consider any such <B>nil</B> value as the end of
+the array).
+
+<p><a name="2.5.6"></a><h3>2.5.6 - Precedence</h3>
+Operator precedence in Lua follows the table below,
+from lower to higher priority:
+<PRE>
+ or
+ and
+ &#060; > &#060;= >= ~= ==
+ ..
+ + -
+ * / %
+ not # - (unary)
+ ^
+</PRE>
+You can use parentheses to change the precedences of an expression.
+The concatenation (`<code>..</code>&acute;) and exponentiation (`<code>^</code>&acute;)
+operators are right associative.
+All other binary operators are left associative.
+
+<p><a name="tableconstructor"></a><a name="2.5.7"></a><h3>2.5.7 - Table Constructors</h3>
+Table constructors are expressions that create tables.
+Every time a constructor is evaluated, a new table is created.
+Constructors can be used to create empty tables,
+or to create a table and initialize some of its fields.
+The general syntax for constructors is
+<pre>
+ tableconstructor ::= `<b>{</b>&acute; [fieldlist] `<b>}</b>&acute;
+ fieldlist ::= field {fieldsep field} [fieldsep]
+ field ::= `<b>[</b>&acute; exp `<b>]</b>&acute; `<b>=</b>&acute; exp | Name `<b>=</b>&acute; exp | exp
+ fieldsep ::= `<b>,</b>&acute; | `<b>;</b>&acute;
+</pre>
+
+<p>Each field of the form <code>[exp1] = exp2</code> adds to the new table an entry
+with key <code>exp1</code> and value <code>exp2</code>.
+A field of the form <code>name = exp</code> is equivalent to
+<code>["name"] = exp</code>.
+Finally, fields of the form <code>exp</code> are equivalent to
+<code>[i] = exp</code>, where <code>i</code> are consecutive numerical integers,
+starting with 1.
+Fields in the other formats do not affect this counting.
+For example,
+<PRE>
+ a = {[f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45}
+</PRE>
+is equivalent to
+<PRE>
+ do
+ local temp = {}
+ temp[f(1)] = g
+ temp[1] = "x" -- 1st exp
+ temp[2] = "y" -- 2nd exp
+ temp.x = 1 -- temp["x"] = 1
+ temp[3] = f(x) -- 3rd exp
+ temp[30] = 23
+ temp[4] = 45 -- 4th exp
+ a = temp
+ end
+</PRE>
+
+<p>If the last field in the list has the form <code>exp</code>
+and the expression is a function call or a vararg expression,
+then all values returned by that expression enter the list consecutively
+(see <a href="#functioncall">2.5.8</a>).
+To avoid this,
+enclose the function call (or the vararg expression)
+in parentheses (see <a href="#expressions">2.5</a>).
+
+<p>The field list may have an optional trailing separator,
+as a convenience for machine-generated code.
+
+<p><a name="functioncall"></a><a name="2.5.8"></a><h3>2.5.8 - Function Calls</h3>
+A function call in Lua has the following syntax:
+<pre>
+ functioncall ::= prefixexp args
+</pre>
+In a function call,
+first <em>prefixexp</em> and <em>args</em> are evaluated.
+If the value of <em>prefixexp</em> has type <em>function</em>,
+then that function is called
+with the given arguments.
+Otherwise, its "call" metamethod is called,
+having as first parameter the value of <em>prefixexp</em>,
+followed by the original call arguments
+(see <a href="#metatable">2.8</a>).
+
+<p>The form
+<pre>
+ functioncall ::= prefixexp `<b>:</b>&acute; Name args
+</pre>
+can be used to call "methods".
+A call <code>v:name(...)</code>
+is syntactic sugar for <code>v.name(v,...)</code>,
+except that <code>v</code> is evaluated only once.
+
+<p>Arguments have the following syntax:
+<pre>
+ args ::= `<b>(</b>&acute; [explist1] `<b>)</b>&acute;
+ args ::= tableconstructor
+ args ::= Literal
+</pre>
+All argument expressions are evaluated before the call.
+A call of the form <code>f{...}</code> is syntactic sugar for
+<code>f({...})</code>, that is,
+the argument list is a single new table.
+A call of the form <code>f'...'</code>
+(or <code>f"..."</code> or <code>f[[...]]</code>) is syntactic sugar for
+<code>f('...')</code>, that is,
+the argument list is a single literal string.
+
+<p>As an exception to the free-format syntax of Lua,
+you cannot put a line break before the `<code>(</code>&acute; in a function call.
+That restriction avoids some ambiguities in the language.
+If you write
+<PRE>
+ a = f
+ (g).x(a)
+</PRE>
+Lua would read that as <code>a = f(g).x(a)</code>.
+So, if you want two statements, you must add a semi-colon between them.
+If you actually want to call <code>f</code>,
+you must remove the line break before <code>(g)</code>.
+
+<p>A call of the form <code>return</code> <em>functioncall</em> is called
+a <em>tail call</em>.
+Lua implements <em>proper tail calls</em>
+(or <em>proper tail recursion</em>):
+In a tail call,
+the called function reuses the stack entry of the calling function.
+Therefore, there is no limit on the number of nested tail calls that
+a program can execute.
+However, a tail call erases any debug information about the
+calling function.
+Note that a tail call only happens with a particular syntax,
+where the <b>return</b> has one single function call as argument;
+this syntax makes the calling function returns exactly
+the returns of the called function.
+So, all the following examples are not tail calls:
+<PRE>
+ return (f(x)) -- results adjusted to 1
+ return 2 * f(x)
+ return x, f(x) -- additional results
+ f(x); return -- results discarded
+ return x or f(x) -- results adjusted to 1
+</PRE>
+
+<p><a name="func-def"></a><a name="2.5.9"></a><h3>2.5.9 - Function Definitions</h3>
+
+<p>The syntax for function definition is
+<pre>
+ function ::= <b>function</b> funcbody
+ funcbody ::= `<b>(</b>&acute; [parlist1] `<b>)</b>&acute; block <b>end</b>
+</pre>
+
+<p>The following syntactic sugar simplifies function definitions:
+<pre>
+ stat ::= <b>function</b> funcname funcbody
+ stat ::= <b>local</b> <b>function</b> Name funcbody
+ funcname ::= Name {`<b>.</b>&acute; Name} [`<b>:</b>&acute; Name]
+</pre>
+The statement
+<PRE>
+ function f () ... end
+</PRE>
+translates to
+<PRE>
+ f = function () ... end
+</PRE>
+The statement
+<PRE>
+ function t.a.b.c.f () ... end
+</PRE>
+translates to
+<PRE>
+ t.a.b.c.f = function () ... end
+</PRE>
+The statement
+<PRE>
+ local function f () ... end
+</PRE>
+translates to
+<PRE>
+ local f; f = function () ... end
+</PRE>
+
+<p>A function definition is an executable expression,
+whose value has type <em>function</em>.
+When Lua pre-compiles a chunk,
+all its function bodies are pre-compiled too.
+Then, whenever Lua executes the function definition,
+the function is <em>instantiated</em> (or <em>closed</em>).
+This function instance (or <em>closure</em>)
+is the final value of the expression.
+Different instances of the same function
+may refer to different external local variables
+and may have different environment tables.
+
+<p>Parameters act as local variables that are
+initialized with the argument values:
+<pre>
+ parlist1 ::= namelist [`<b>,</b>&acute; `<b>...</b>&acute;] | `<b>...</b>&acute;
+</pre>
+When a function is called,
+the list of arguments is adjusted to
+the length of the list of parameters,
+unless the function is a variadic or <em>vararg function</em>,
+which is
+indicated by three dots (`<code>...</code>&acute;) at the end of its parameter list.
+A vararg function does not adjust its argument list;
+instead, it collects all extra arguments and supplies them
+to the function through a <em>vararg expression</em>,
+which is also written as three dots.
+The value of this expression is a list of all actual extra arguments,
+similar to a function with multiple results.
+If a vararg expression is used inside another expression
+or in the middle of a list of expressions,
+then its return list is adjusted to one element.
+If the expression is used as the last element of a list of expressions,
+then no adjustment is made
+(unless the call is enclosed in parentheses).
+
+<p>As an example, consider the following definitions:
+<PRE>
+ function f(a, b) end
+ function g(a, b, ...) end
+ function r() return 1,2,3 end
+</PRE>
+Then, we have the following mapping from arguments to parameters and
+to the vararg expression:
+<PRE>
+ CALL PARAMETERS
+
+ f(3) a=3, b=nil
+ f(3, 4) a=3, b=4
+ f(3, 4, 5) a=3, b=4
+ f(r(), 10) a=1, b=10
+ f(r()) a=1, b=2
+
+ g(3) a=3, b=nil, ... -> (nothing)
+ g(3, 4) a=3, b=4, ... -> (nothing)
+ g(3, 4, 5, 8) a=3, b=4, ... -> 5 8
+ g(5, r()) a=5, b=1, ... -> 2 3
+</PRE>
+
+<p>Results are returned using the <b>return</b> statement (see <a href="#control">2.4.4</a>).
+If control reaches the end of a function
+without encountering a <b>return</b> statement,
+then the function returns with no results.
+
+<p>The <em>colon</em> syntax
+is used for defining <em>methods</em>,
+that is, functions that have an implicit extra parameter <code>self</code>.
+Thus, the statement
+<PRE>
+ function t.a.b.c:f (...) ... end
+</PRE>
+is syntactic sugar for
+<PRE>
+ t.a.b.c.f = function (self, ...) ... end
+</PRE>
+
+<p><a name="visibility"></a><a name="2.6"></a><h2>2.6 - Visibility Rules</h2>
+
+
+<p>Lua is a lexically scoped language.
+The scope of variables begins at the first statement <em>after</em>
+their declaration and lasts until the end of the innermost block that
+includes the declaration.
+For instance:
+<PRE>
+ x = 10 -- global variable
+ do -- new block
+ local x = x -- new `x', with value 10
+ print(x) --> 10
+ x = x+1
+ do -- another block
+ local x = x+1 -- another `x'
+ print(x) --> 12
+ end
+ print(x) --> 11
+ end
+ print(x) --> 10 (the global one)
+</PRE>
+Notice that, in a declaration like <code>local x = x</code>,
+the new <code>x</code> being declared is not in scope yet,
+and so the second <code>x</code> refers to the outside variable.
+
+<p>Because of the lexical scoping rules,
+local variables can be freely accessed by functions
+defined inside their scope.
+For instance:
+<PRE>
+ local counter = 0
+ function inc (x)
+ counter = counter + x
+ return counter
+ end
+</PRE>
+A local variable used by an inner function is called
+an <em>upvalue</em>, or <em>external local variable</em>,
+inside the inner function.
+
+<p>Notice that each execution of a <b>local</b> statement
+defines new local variables.
+Consider the following example:
+<PRE>
+ a = {}
+ local x = 20
+ for i=1,10 do
+ local y = 0
+ a[i] = function () y=y+1; return x+y end
+ end
+</PRE>
+The loop creates ten closures
+(that is, ten instances of the anonymous function).
+Each of these closures uses a different <code>y</code> variable,
+while all of them share the same <code>x</code>.
+
+<p><a name="error"></a><a name="2.7"></a><h2>2.7 - Error Handling</h2>
+
+<p>Because Lua is an extension language,
+all Lua actions start from C code in the host program
+calling a function from the Lua library (see <a href="#lua_pcall"></a>).
+Whenever an error occurs during Lua compilation or execution,
+control returns to C,
+which can take appropriate measures
+(such as print an error message).
+
+<p>Lua code can explicitly generate an error by calling the
+<a href="#pdf-error"><code>error</code></a> function.
+If you need to catch errors in Lua,
+you can use the <a href="#pdf-pcall"><code>pcall</code></a> function.
+
+<p><a name="metatable"></a><a name="2.8"></a><h2>2.8 - Metatables</h2>
+
+<p>Every value in Lua may have a <em>metatable</em>.
+This <em>metatable</em> is an ordinary Lua table
+that defines the behavior of the original value
+under certain special operations.
+You can change several aspects of the behavior
+of operations over a value by setting specific fields in its metatable.
+For instance, when a non-numeric value is the operand of an addition,
+Lua checks for a function in the field <code>"__add"</code> in its metatable.
+If it finds one,
+Lua calls that function to perform the addition.
+
+<p>We call the keys in a metatable <em>events</em>
+and the values <em>metamethods</em>.
+In the previous example, the event is <code>"add"</code>
+and the metamethod is the function that performs the addition.
+
+<p>You can query the metatable of any value
+through the <a href="#pdf-getmetatable"><code>getmetatable</code></a> function.
+
+<p>You can replace the metatable of tables
+through the <a href="#pdf-setmetatable"><code>setmetatable</code></a>
+function.
+You cannot change the metatable of other types from Lua
+(except using the debug library);
+you must use the C API for that.
+
+<p>Tables and userdata have individual metatables
+(although multiple tables and userdata can share
+a same table as their metatable);
+values of all other types share one single metatable per type.
+So, there is one single metatable for all numbers,
+and for all strings, etc.
+
+<p>A metatable may control how an object behaves in arithmetic operations,
+order comparisons, concatenation, and indexing.
+A metatable can also define a function to be called when a userdata
+is garbage collected.
+For each of those operations Lua associates a specific key
+called an <em>event</em>.
+When Lua performs one of those operations over a value,
+it checks whether that value has a metatable with the corresponding event.
+If so, the value associated with that key (the <em>metamethod</em>)
+controls how Lua will perform the operation.
+
+<p>Metatables control the operations listed next.
+Each operation is identified by its corresponding name.
+The key for each operation is a string with its name prefixed by
+two underscores;
+for instance, the key for operation "add" is the
+string <code>"__add"</code>.
+The semantics of these operations is better explained by a Lua function
+describing how the interpreter executes that operation.
+
+<p>The code shown here in Lua is only illustrative;
+the real behavior is hard coded in the interpreter
+and it is much more efficient than this simulation.
+All functions used in these descriptions
+(<a href="#pdf-rawget"><code>rawget</code></a>, <a href="#pdf-tonumber"><code>tonumber</code></a>, etc.)
+are described in <a href="#predefined">5.1</a>.
+In particular, to retrieve the metamethod of a given object,
+we use the expression
+<PRE>
+ metatable(obj)[event]
+</PRE>
+This should be read as
+<PRE>
+ rawget(metatable(obj) or {}, event)
+</PRE>
+That is, the access to a metamethod does not invoke other metamethods,
+and the access to objects with no metatables does not fail
+(it simply results in <B>nil</B>).
+
+<p><ul>
+<li><b>"add":</b>
+the <code>+</code> operation.
+
+<p>The function <code>getbinhandler</code> below defines how Lua chooses a handler
+for a binary operation.
+First, Lua tries the first operand.
+If its type does not define a handler for the operation,
+then Lua tries the second operand.
+<PRE>
+ function getbinhandler (op1, op2, event)
+ return metatable(op1)[event] or metatable(op2)[event]
+ end
+</PRE>
+Using that function,
+the behavior of the <code>op1 + op2</code> is
+<PRE>
+ function add_event (op1, op2)
+ local o1, o2 = tonumber(op1), tonumber(op2)
+ if o1 and o2 then -- both operands are numeric?
+ return o1 + o2 -- `+' here is the primitive `add'
+ else -- at least one of the operands is not numeric
+ local h = getbinhandler(op1, op2, "__add")
+ if h then
+ -- call the handler with both operands
+ return h(op1, op2)
+ else -- no handler available: default behavior
+ error("...")
+ end
+ end
+ end
+</PRE>
+
+<p><li><b>"sub":</b>
+the <code>-</code> operation.
+Behavior similar to the "add" operation.
+
+<p><li><b>"mul":</b>
+the <code>*</code> operation.
+Behavior similar to the "add" operation.
+
+<p><li><b>"div":</b>
+the <code>/</code> operation.
+Behavior similar to the "add" operation.
+
+<p><li><b>"mod":</b>
+the <code>%</code> operation.
+Behavior similar to the "add" operation,
+with the operation
+<code>o1 - floor(o1/o2)*o2</code> as the primitive operation.
+
+<p><li><b>"pow":</b>
+the <code>^</code> (exponentiation) operation.
+Behavior similar to the "add" operation,
+with the function <code>pow</code> (from the C math library)
+as the primitive operation.
+
+<p><li><b>"unm":</b>
+the unary <code>-</code> operation.
+<PRE>
+ function unm_event (op)
+ local o = tonumber(op)
+ if o then -- operand is numeric?
+ return -o -- `-' here is the primitive `unm'
+ else -- the operand is not numeric.
+ -- Try to get a handler from the operand
+ local h = metatable(op).__unm
+ if h then
+ -- call the handler with the operand
+ return h(op)
+ else -- no handler available: default behavior
+ error("...")
+ end
+ end
+ end
+</PRE>
+
+<p><li><b>"concat":</b>
+the <code>..</code> (concatenation) operation.
+<PRE>
+ function concat_event (op1, op2)
+ if (type(op1) == "string" or type(op1) == "number") and
+ (type(op2) == "string" or type(op2) == "number") then
+ return op1 .. op2 -- primitive string concatenation
+ else
+ local h = getbinhandler(op1, op2, "__concat")
+ if h then
+ return h(op1, op2)
+ else
+ error("...")
+ end
+ end
+ end
+</PRE>
+
+<p><li><b>"len":</b>
+the <code>#</code> operation.
+<PRE>
+ function len_event (op)
+ if type(op) == "string" then
+ return strlen(op) -- primitive string length
+ elseif type(op) == "table" then
+ return #op -- primitive table length
+ else
+ local h = metatable(op).__len
+ if h then
+ -- call the handler with the operand
+ return h(op)
+ else -- no handler available: default behavior
+ error("...")
+ end
+ end
+ end
+</PRE>
+See <a href="#len-op">2.5.5</a> for a description of the length of a table.
+
+<p><li><b>"eq":</b>
+the <code>==</code> operation.
+The function <code>getcomphandler</code> defines how Lua chooses a metamethod
+for comparison operators.
+A metamethod only is selected when both objects
+being compared have the same type
+and the same metamethod for the selected operation.
+<PRE>
+ function getcomphandler (op1, op2, event)
+ if type(op1) ~= type(op2) then return nil end
+ local mm1 = metatable(op1)[event]
+ local mm2 = metatable(op2)[event]
+ if mm1 == mm2 then return mm1 else return nil end
+ end
+</PRE>
+The "eq" event is defined as follows:
+<PRE>
+ function eq_event (op1, op2)
+ if type(op1) ~= type(op2) then -- different types?
+ return false -- different objects
+ end
+ if op1 == op2 then -- primitive equal?
+ return true -- objects are equal
+ end
+ -- try metamethod
+ local h = getcomphandler(op1, op2, "__eq")
+ if h then
+ return h(op1, op2)
+ else
+ return false
+ end
+ end
+</PRE>
+<code>a ~= b</code> is equivalent to <code>not (a == b)</code>.
+
+<p><li><b>"lt":</b>
+the <code>&#060;</code> operation.
+<PRE>
+ function lt_event (op1, op2)
+ if type(op1) == "number" and type(op2) == "number" then
+ return op1 &#060; op2 -- numeric comparison
+ elseif type(op1) == "string" and type(op2) == "string" then
+ return op1 &#060; op2 -- lexicographic comparison
+ else
+ local h = getcomphandler(op1, op2, "__lt")
+ if h then
+ return h(op1, op2)
+ else
+ error("...");
+ end
+ end
+ end
+</PRE>
+<code>a > b</code> is equivalent to <code>b &#060; a</code>.
+
+<p><li><b>"le":</b>
+the <code>&#060;=</code> operation.
+<PRE>
+ function le_event (op1, op2)
+ if type(op1) == "number" and type(op2) == "number" then
+ return op1 &#060;= op2 -- numeric comparison
+ elseif type(op1) == "string" and type(op2) == "string" then
+ return op1 &#060;= op2 -- lexicographic comparison
+ else
+ local h = getcomphandler(op1, op2, "__le")
+ if h then
+ return h(op1, op2)
+ else
+ h = getcomphandler(op1, op2, "__lt")
+ if h then
+ return not h(op2, op1)
+ else
+ error("...");
+ end
+ end
+ end
+ end
+</PRE>
+<code>a >= b</code> is equivalent to <code>b &#060;= a</code>.
+Note that, in the absence of a "le" metamethod,
+Lua tries the "lt", assuming that <code>a &#060;= b</code> is
+equivalent to <code>not (b &#060; a)</code>.
+
+<p><li><b>"index":</b>
+The indexing access <code>table[key]</code>.
+<PRE>
+ function gettable_event (table, key)
+ local h
+ if type(table) == "table" then
+ local v = rawget(table, key)
+ if v ~= nil then return v end
+ h = metatable(table).__index
+ if h == nil then return nil end
+ else
+ h = metatable(table).__index
+ if h == nil then
+ error("...");
+ end
+ end
+ if type(h) == "function" then
+ return h(table, key) -- call the handler
+ else return h[key] -- or repeat operation on it
+ end
+ end
+</PRE>
+
+<p><li><b>"newindex":</b>
+The indexing assignment <code>table[key] = value</code>.
+<PRE>
+ function settable_event (table, key, value)
+ local h
+ if type(table) == "table" then
+ local v = rawget(table, key)
+ if v ~= nil then rawset(table, key, value); return end
+ h = metatable(table).__newindex
+ if h == nil then rawset(table, key, value); return end
+ else
+ h = metatable(table).__newindex
+ if h == nil then
+ error("...");
+ end
+ end
+ if type(h) == "function" then
+ return h(table, key,value) -- call the handler
+ else h[key] = value -- or repeat operation on it
+ end
+ end
+</PRE>
+
+<p><li><b>"call":</b>
+called when Lua calls a value.
+<PRE>
+ function function_event (func, ...)
+ if type(func) == "function" then
+ return func(unpack(arg)) -- primitive call
+ else
+ local h = metatable(func).__call
+ if h then
+ return h(func, unpack(arg))
+ else
+ error("...")
+ end
+ end
+ end
+</PRE>
+
+<p></ul>
+
+<p><a name="environ"></a><a name="2.9"></a><h2>2.9 - Environments</h2>
+
+<p>Besides metatables,
+objects of types thread, function, and userdata
+have another table associated with them,
+called <em>environment</em>.
+Like metatables, environments are regular tables and
+multiple objects can share the same environment.
+
+<p>Environments associated with userdata has no meaning for Lua.
+It is only a feature for programmers to associate a table to
+a userdata.
+
+<p>Environments associated with threads are called
+<em>global environments</em>.
+They are used as the default environment for threads and
+non-nested functions created by that thread
+(through <a href="#pdf-loadfile"><code>loadfile</code></a>, <a href="#pdf-loadstring"><code>loadstring</code></a> or <a href="#pdf-load"><code>load</code></a>)
+and can be directly accessed by C code (see <a href="#pseudo-index">3.3</a>).
+
+<p>Environments associated with C functions can be directly
+accessed by C code (see <a href="#pseudo-index">3.3</a>).
+They are used as the default environment for other C functions
+created by that function.
+
+<p>Environments associated with Lua functions are used to resolve
+all accesses to global variables within that function (see <a href="#variables">2.3</a>).
+They are used as the default environment for other Lua functions
+created by that function.
+
+<p>You can change the environment of a Lua function of the
+running thread calling <a href="#pdf-setfenv"><code>setfenv</code></a>.
+You can get the environment of a Lua function or the running thread
+calling <a href="#pdf-getfenv"><code>getfenv</code></a>.
+To manipulate the environment of other objects
+(userdata, C functions, other threads) you must
+use the C API.
+
+<p><a name="GC"></a><a name="2.10"></a><h2>2.10 - Garbage Collection</h2>
+
+<p>Lua does automatic memory management.
+That means that
+you do not have to worry about allocating memory for new objects
+and freeing it when the objects are no longer needed.
+Lua manages memory automatically by running
+a <em>garbage collector</em> from time to time
+to collect all <em>dead objects</em>
+(that is, those objects that are no longer accessible from Lua).
+All objects in Lua are subject to automatic management:
+tables, userdata, functions, threads, and strings.
+
+<p>Lua 5.1 implements an incremental mark-and-sweep collector.
+It uses two numbers to control its garbage-collection cycles.
+One number, the <em>garbage-collector pause</em>,
+controls how long the collector waits before starting a new cycle.
+Larger values make the collector less aggressive.
+Values smaller than 1 mean the collector will not wait to
+start a new cycle.
+A value of 2 means that the collector waits more or less to double
+the total memory in use before starting a new cycle.
+
+<p>The other number, the <em>garbage-collector multiplier</em>,
+controls the relative speed of the collector relative to
+memory allocation.
+Larger values make the collector more aggressive but also increases
+the size of each incremental step.
+Values smaller than 1 make the collector too slow and
+may result in the collector never finishing a cycle.
+The default, 2, means that the collector runs at "twice"
+the speed of memory allocation.
+
+<p>You can change those numbers calling <a href="#lua_gc"><code>lua_gc</code></a> in C
+or <a href="#pdf-collectgarbage"><code>collectgarbage</code></a> in Lua.
+Both get as arguments percentage points
+(so an argument 100 means a real value of 1).
+With those functions you can also get direct control
+of the collector (e.g., stop and restart it).
+
+<p><a name="2.10.1"></a><h3>2.10.1 - Garbage-Collection Metamethods</h3>
+
+<p>Using the C API,
+you can set garbage-collector metamethods for userdata (see <a href="#metatable">2.8</a>).
+These metamethods are also called <em>finalizers</em>.
+Finalizers allow you to coordinate Lua's garbage collection
+with external resource management
+(such as closing files, network or database connections,
+or freeing your own memory).
+
+<p>Free userdata with a field <code>__gc</code> in their metatables are not
+collected immediately by the garbage collector.
+Instead, Lua puts them in a list.
+After the collection,
+Lua does the equivalent of the following function
+for each userdata in that list:
+<PRE>
+ function gc_event (udata)
+ local h = metatable(udata).__gc
+ if h then
+ h(udata)
+ end
+ end
+</PRE>
+
+<p>At the end of each garbage-collection cycle,
+the finalizers for userdata are called in <em>reverse</em>
+order of their creation,
+among those collected in that cycle.
+That is, the first finalizer to be called is the one associated
+with the userdata created last in the program.
+
+<p><a name="weak-table"></a><a name="2.10.2"></a><h3>2.10.2 - Weak Tables</h3>
+
+<p>A <em>weak table</em> is a table whose elements are
+<em>weak references</em>.
+A weak reference is ignored by the garbage collector.
+In other words,
+if the only references to an object are weak references,
+then the garbage collector will collect that object.
+
+<p>A weak table can have weak keys, weak values, or both.
+A table with weak keys allows the collection of its keys,
+but prevents the collection of its values.
+A table with both weak keys and weak values allows the collection of
+both keys and values.
+In any case, if either the key or the value is collected,
+the whole pair is removed from the table.
+The weakness of a table is controlled by the value of the
+<code>__mode</code> field of its metatable.
+If the <code>__mode</code> field is a string containing the character `<code>k</code>&acute;,
+the keys in the table are weak.
+If <code>__mode</code> contains `<code>v</code>&acute;,
+the values in the table are weak.
+
+<p>After you use a table as a metatable,
+you should not change the value of its field <code>__mode</code>.
+Otherwise, the weak behavior of the tables controlled by this
+metatable is undefined.
+
+<p><a name="coroutine"></a><a name="2.11"></a><h2>2.11 - Coroutines</h2>
+
+<p>Lua supports coroutines,
+also called <em>collaborative multithreading</em>.
+A coroutine in Lua represents an independent thread of execution.
+Unlike threads in multithread systems, however,
+a coroutine only suspends its execution by explicitly calling
+a yield function.
+
+<p>You create a coroutine with a call to <code>coroutine.create</code>.
+Its sole argument is a function
+that is the main function of the coroutine.
+The <code>create</code> function only creates a new coroutine and
+returns a handle to it (an object of type <em>thread</em>);
+it does not start the coroutine execution.
+
+<p>When you first call <code>coroutine.resume</code>,
+passing as its first argument
+the thread returned by <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
+the coroutine starts its execution,
+at the first line of its main function.
+Extra arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> are given as
+parameters for the coroutine main function.
+After the coroutine starts running,
+it runs until it terminates or <em>yields</em>.
+
+<p>A coroutine can terminate its execution in two ways:
+Normally, when its main function returns
+(explicitly or implicitly, after the last instruction);
+and abnormally, if there is an unprotected error.
+In the first case, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <B>true</B>,
+plus any values returned by the coroutine main function.
+In case of errors, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <B>false</B>
+plus an error message.
+
+<p>A coroutine yields by calling <code>coroutine.yield</code>.
+When a coroutine yields,
+the corresponding <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns immediately,
+even if the yield happens inside nested function calls
+(that is, not in the main function,
+but in a function directly or indirectly called by the main function).
+In the case of a yield, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> also returns <B>true</B>,
+plus any values passed to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
+The next time you resume the same coroutine,
+it continues its execution from the point where it yielded,
+with the call to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a> returning any extra
+arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
+
+<p>The <code>coroutine.wrap</code> function creates a coroutine
+like <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
+but instead of returning the coroutine itself,
+it returns a function that, when called, resumes the coroutine.
+Any arguments passed to that function
+go as extra arguments to resume.
+The function returns all the values returned by resume,
+except the first one (the boolean error code).
+Unlike <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
+this function does not catch errors;
+any error is propagated to the caller.
+
+<p>As an example,
+consider the next code:
+<PRE>
+function foo1 (a)
+ print("foo", a)
+ return coroutine.yield(2*a)
+end
+
+co = coroutine.create(function (a,b)
+ print("co-body", a, b)
+ local r = foo1(a+1)
+ print("co-body", r)
+ local r, s = coroutine.yield(a+b, a-b)
+ print("co-body", r, s)
+ return b, "end"
+end)
+
+a, b = coroutine.resume(co, 1, 10)
+print("main", a, b)
+a, b, c = coroutine.resume(co, "r")
+print("main", a, b, c)
+a, b, c = coroutine.resume(co, "x", "y")
+print("main", a, b, c)
+a, b = coroutine.resume(co, "x", "y")
+print("main", a, b)
+</PRE>
+When you run it, it produces the following output:
+<PRE>
+co-body 1 10
+foo 2
+main true 4
+co-body r
+main true 11 -9
+co-body x y
+main true 10 end
+main false cannot resume dead coroutine
+</PRE>
+
+<p>
+<a name="API"></a><a name="3"></a><h1>3 - The Application Program Interface</h1>
+
+
+<p>This section describes the C API for Lua, that is,
+the set of C functions available to the host program to communicate
+with Lua.
+All API functions and related types and constants
+are declared in the header file <code>lua.h</code>.
+
+<p>Even when we use the term "function",
+any facility in the API may be provided as a macro instead.
+All such macros use each of its arguments exactly once
+(except for the first argument, which is always a Lua state),
+and so do not generate hidden side-effects.
+
+<p>Like in most C libraries,
+the Lua API functions do not check their arguments.
+However, you can change this behavior by compiling Lua
+with a proper definition for the macro <code>luai_apicheck</code>,
+in file <code>luaconf.h</code>.
+
+<p><a name="3.1"></a><h2>3.1 - The Stack</h2>
+
+<p>Lua uses a <em>virtual stack</em> to pass values to and from C.
+Each element in this stack represents a Lua value
+(<B>nil</B>, number, string, etc.).
+
+<p>Whenever Lua calls C, the called function gets a new stack,
+which is independent of previous stacks and of stacks of
+C functions that are still active.
+That stack initially contains any arguments to the C function,
+and it is where the C function pushes its results
+to be returned to the caller (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
+
+<p>For convenience,
+most query operations in the API do not follow a strict stack discipline.
+Instead, they can refer to any element in the stack
+by using an <em>index</em>:
+A positive index represents an <em>absolute</em> stack position
+(starting at 1);
+a negative index represents an <em>offset</em> from the top of the stack.
+More specifically, if the stack has <em>n</em> elements,
+then index 1 represents the first element
+(that is, the element that was pushed onto the stack first)
+and
+index <em>n</em> represents the last element;
+index <em>-1</em> also represents the last element
+(that is, the element at the top)
+and index <em>-n</em> represents the first element.
+We say that an index is <em>valid</em>
+if it lies between 1 and the stack top
+(that is, if <code>1 &#060;= abs(index) &#060;= top</code>).
+
+
+<p><a name="3.2"></a><h2>3.2 - Stack Size</h2>
+
+<p>When you interact with Lua API,
+<em>you are responsible for controlling stack overflow</em>.
+You can use the function <a href="#lua_checkstack"><code>lua_checkstack</code></a>
+to grow the stack size.
+
+<p>Whenever Lua calls C,
+it ensures that at least <code>LUA_MINSTACK</code> stack positions are available.
+<code>LUA_MINSTACK</code> is defined as 20,
+so that usually you do not have to worry about stack space
+unless your code has loops pushing elements onto the stack.
+
+<p>Most query functions accept as indices any value inside the
+available stack space, that is, indices up to the maximum stack size
+you have set through <a href="#lua_checkstack"><code>lua_checkstack</code></a>.
+Such indices are called <em>acceptable indices</em>.
+More formally, we define an <em>acceptable index</em>
+as follows:
+<PRE>
+ (index &#060; 0 &#038;&#038; abs(index) &#060;= top) || (index > 0 &#038;&#038; index &#060;= stackspace)
+</PRE>
+Note that 0 is never an acceptable index.
+
+<p><a name="pseudo-index"></a><a name="3.3"></a><h2>3.3 - Pseudo-Indices</h2>
+
+<p>Unless otherwise noted,
+any function that accepts valid indices can also be called with
+<em>pseudo-indices</em>,
+which represent some Lua values that are accessible to the C code
+but are not in the stack.
+Pseudo-indices are used to access the thread environment,
+the function environment,
+the registry,
+and the upvalues of a C function (see <a href="#c-closure">3.4</a>).
+
+<p>The thread environment (where global variables live) is
+always at pseudo-index <code>LUA_GLOBALSINDEX</code>.
+The environment of the running C function is always
+at pseudo-index <code>LUA_ENVIRONINDEX</code>.
+
+<p>To access and change the value of global variables,
+you can use regular table operations over an environment table.
+For instance, to access the value of a global variable, do
+<PRE>
+ lua_getfield(L, LUA_GLOBALSINDEX, varname);
+</PRE>
+
+<p><a name="c-closure"></a><a name="3.4"></a><h2>3.4 - C Closures</h2>
+
+<p>When a C function is created,
+it is possible to associate some values with it,
+thus creating a <em>C closure</em>;
+these values are then accessible to the function whenever it is called
+(see <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>).
+
+<p>Whenever a C function is called,
+its associated values are located at specific pseudo-indices.
+Those pseudo-indices are produced by the macro
+<code>lua_upvalueindex</code>.
+The first value associated with a function is at position
+<code>lua_upvalueindex(1)</code>, and so on.
+Any access to <code>lua_upvalueindex(<em>n</em>)</code>,
+where <em>n</em> is greater than the number of upvalues of the
+current function,
+produces an acceptable (but invalid) index.
+
+<p><a name="registry"></a><a name="3.5"></a><h2>3.5 - Registry</h2>
+
+<p>Lua provides a registry,
+a pre-defined table that can be used by any C code to
+store whatever Lua value it needs to store.
+This table is always located at pseudo-index
+<code>LUA_REGISTRYINDEX</code>.
+Any C library can store data into this table,
+as long as it chooses keys different from other libraries.
+Typically, you should use as key a string containing your library name
+or a light userdata with the address of a C object in your code.
+
+<p>The integer keys in the registry are used by the reference mechanism,
+implemented by the auxiliary library,
+and therefore should not be used by other purposes.
+
+<p><a name="3.6"></a><h2>3.6 - Error Handling in C</h2>
+
+<p>Internally, Lua uses the C <code>longjmp</code> facility to handle errors.
+When Lua faces any error
+(such as memory allocation errors, type errors, syntax errors)
+it <em>raises</em> an error, that is, it does a long jump.
+A <em>protected environment</em> uses <code>setjmp</code>
+to set a recover point;
+any error jumps to the most recent active recover point.
+
+<p>Almost any function in the API may raise an error,
+for instance due to a memory allocation error.
+The following functions run in protected mode
+(that is, they create a protected environment to run),
+so they never raise an error:
+<a href="#lua_newstate"><code>lua_newstate</code></a>, <a href="#lua_close"><code>lua_close</code></a>, <a href="#lua_load"><code>lua_load</code></a>,
+<a href="#lua_pcall"><code>lua_pcall</code></a>, and <a href="#lua_cpcall"><code>lua_cpcall</code></a>.
+
+<p>Inside a C function you can raise an error calling <a href="#lua_error"><code>lua_error</code></a>.
+
+<p><a name="3.7"></a><h2>3.7 - Functions and Types</h2>
+
+<p>Here we list all functions and types from the C API in
+alphabetical order.
+
+<p><a name="lua_Alloc"></a>
+<hr><h3><code>lua_Alloc</code></h3>
+<pre>
+ typedef void * (*lua_Alloc) (void *ud,
+ void *ptr,
+ size_t osize,
+ size_t nsize);
+
+</pre>
+
+
+<p>The allocator function used by Lua states.
+The allocator function must provide a
+functionality similar to <code>realloc</code>,
+but not exactly the same.
+Its arguments are <code>ud</code>,
+the opaque pointer passed to <a href="#lua_newstate"><code>lua_newstate</code></a>;
+<code>ptr</code>, a pointer to the block being allocated/reallocated/freed;
+<code>osize</code>, the original size of the block;
+<code>nsize</code>, the new size of the block.
+<code>ptr</code> is <code>NULL</code> if and only if <code>osize</code> is zero.
+When <code>nsize</code> is zero, the allocator must return <code>NULL</code>;
+if <code>osize</code> is not zero,
+it should free the block pointed by <code>ptr</code>.
+When <code>nsize</code> is not zero, the allocator returns <code>NULL</code>
+if and only if it cannot fill the request.
+When <code>nsize</code> is not zero and <code>osize</code> is zero,
+the allocator behaves like <code>malloc</code>.
+When <code>nsize</code> and <code>osize</code> are not zero,
+the allocator behaves like <code>realloc</code>.
+Lua assumes that the allocator never fails when
+<code>osize >= nsize</code>.
+
+<p>A simple implementation for the allocator function could be like this:
+<PRE>
+static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
+ (void)ud; /* not used */
+ (void)osize; /* not used */
+ if (nsize == 0) {
+ free(ptr); /* ANSI ensures that free(NULL) has no effect */
+ return NULL;
+ }
+ else
+ /* ANSI ensures that realloc(NULL, size) == malloc(size) */
+ return realloc(ptr, nsize);
+}
+</PRE>
+
+<p><a name="lua_atpanic"></a>
+<hr><h3><code>lua_atpanic</code></h3>
+<pre>
+ lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);
+</pre>
+
+
+<p>Sets a new panic function and returns the old one.
+
+<p>If an error happens outside any protected environment,
+Lua calls a <em>panic function</em>
+and then calls <code>exit(EXIT_FAILURE)</code>.
+Your new panic function may avoid the application exit by
+never returning (e.g., doing a long jump).
+
+<p>The panic function can access the error message at the top of the stack.
+
+<p><a name="lua_call"></a>
+<hr><h3><code>lua_call</code></h3>
+<pre>
+ void lua_call (lua_State *L, int nargs, int nresults);
+</pre>
+
+
+<p>Calls a function.
+
+<p>To call a function you must use the following protocol:
+First, the function to be called is pushed onto the stack;
+then, the arguments to the function are pushed
+in direct order, that is, the first argument is pushed first.
+Finally you call <a href="#lua_call"><code>lua_call</code></a>;
+<code>nargs</code> is the number of arguments that you pushed onto the stack.
+All arguments and the function value are popped from the stack,
+and the function results are pushed.
+The number of results are adjusted to <code>nresults</code>,
+unless <code>nresults</code> is <code>LUA_MULTRET</code>.
+In that case, <em>all</em> results from the function are pushed.
+Lua takes care that the returned values fit into the stack space.
+The function results are pushed onto the stack in direct order
+(the first result is pushed first),
+so that after the call the last result is on the top.
+
+<p>Any error inside the called function is propagated upwards
+(with a <code>longjmp</code>).
+
+<p>The following example shows how the host program may do the
+equivalent to this Lua code:
+<PRE>
+ a = f("how", t.x, 14)
+</PRE>
+Here it is in C:
+<PRE>
+ lua_getfield(L, LUA_GLOBALSINDEX, "t"); /* global `t' (for later use) */
+ lua_getfield(L, LUA_GLOBALSINDEX, "f"); /* function to be called */
+ lua_pushstring(L, "how"); /* 1st argument */
+ lua_getfield(L, -3, "x"); /* push result of t.x (2nd arg) */
+ lua_pushinteger(L, 14); /* 3rd argument */
+ lua_call(L, 3, 1); /* call function with 3 arguments and 1 result */
+ lua_setfield(L, LUA_GLOBALSINDEX, "a"); /* set global variable `a' */
+ lua_pop(L, 1); /* remove `t' from the stack */
+</PRE>
+Note that the code above is "balanced":
+at its end, the stack is back to its original configuration.
+This is considered good programming practice.
+
+<p><a name="lua_CFunction"></a>
+<hr><h3><code>lua_CFunction</code></h3>
+<pre>
+ typedef int (*lua_CFunction) (lua_State *L);
+</pre>
+
+
+<p>Type for C functions.
+
+<p>In order to communicate properly with Lua,
+a C function must follow the following protocol,
+which defines the way parameters and results are passed:
+A C function receives its arguments from Lua in its stack
+in direct order (the first argument is pushed first).
+So, when the function starts,
+its first argument (if any) is at index 1.
+To return values to Lua, a C function just pushes them onto the stack,
+in direct order (the first result is pushed first),
+and returns the number of results.
+Any other value in the stack below the results will be properly
+discharged by Lua.
+Like a Lua function, a C function called by Lua can also return
+many results.
+
+<p>As an example, the following function receives a variable number
+of numerical arguments and returns their average and sum:
+<PRE>
+ static int foo (lua_State *L) {
+ int n = lua_gettop(L); /* number of arguments */
+ lua_Number sum = 0;
+ int i;
+ for (i = 1; i &#060;= n; i++) {
+ if (!lua_isnumber(L, i)) {
+ lua_pushstring(L, "incorrect argument to function `average'");
+ lua_error(L);
+ }
+ sum += lua_tonumber(L, i);
+ }
+ lua_pushnumber(L, sum/n); /* first result */
+ lua_pushnumber(L, sum); /* second result */
+ return 2; /* number of results */
+ }
+</PRE>
+
+<p><a name="lua_checkstack"></a>
+<hr><h3><code>lua_checkstack</code></h3>
+<pre>
+ int lua_checkstack (lua_State *L, int extra);
+</pre>
+
+
+<p>Grows the stack size to <code>top + extra</code> elements;
+it returns false if it cannot grow the stack to that size.
+This function never shrinks the stack;
+if the stack is already larger than the new size,
+it is left unchanged.
+
+<p><a name="lua_close"></a>
+<hr><h3><code>lua_close</code></h3>
+<pre>
+ void lua_close (lua_State *L);
+</pre>
+
+
+<p>Destroys all objects in the given Lua state
+(calling the corresponding garbage-collection metamethods, if any)
+and frees all dynamic memory used by that state.
+On several platforms, you may not need to call this function,
+because all resources are naturally released when the host program ends.
+On the other hand, long-running programs,
+such as a daemon or a web server,
+might need to release states as soon as they are not needed,
+to avoid growing too large.
+
+<p><a name="lua_concat"></a>
+<hr><h3><code>lua_concat</code></h3>
+<pre>
+ void lua_concat (lua_State *L, int n);
+</pre>
+
+
+<p>Concatenates the <code>n</code> values at the top of the stack,
+pops them, and leaves the result at the top.
+If <code>n</code> is 1, the result is that single string
+(that is, the function does nothing);
+if <code>n</code> is 0, the result is the empty string.
+Concatenation is done following the usual semantics of Lua
+(see <a href="#concat">2.5.4</a>).
+
+<p><a name="lua_cpcall"></a>
+<hr><h3><code>lua_cpcall</code></h3>
+<pre>
+ int lua_cpcall (lua_State *L, lua_CFunction func, void *ud);
+</pre>
+
+
+<p>Calls the C function <code>func</code> in protected mode.
+<code>func</code> starts with only one element in its stack,
+a light userdata containing <code>ud</code>.
+In case of errors,
+<a href="#lua_cpcall"><code>lua_cpcall</code></a> returns the same error codes as <a href="#lua_pcall"><code>lua_pcall</code></a>,
+plus the error object on the top of the stack;
+otherwise, it returns zero, and does not change the stack.
+Any value returned by <code>func</code> is discarded.
+
+<p><a name="lua_createtable"></a>
+<hr><h3><code>lua_createtable</code></h3>
+<pre>
+ void lua_createtable (lua_State *L, int narr, int nrec);
+</pre>
+
+
+<p>Creates a new empty table and pushes it onto the stack.
+The new table has space pre-allocated
+for <code>narr</code> array elements plus <code>nrec</code> non-array elements.
+This pre-allocation is useful when you know exactly how many elements
+the table will have.
+Otherwise you can use the function <a href="#lua_newtable"><code>lua_newtable</code></a>.
+
+<p><a name="lua_dump"></a>
+<hr><h3><code>lua_dump</code></h3>
+<pre>
+ int lua_dump (lua_State *L, lua_Writer writer, void *data);
+</pre>
+
+
+<p>Dumps a function as a binary chunk.
+This function receives a Lua function on the top of the stack
+and produces a binary chunk that,
+if loaded again,
+results in a function equivalent to the one dumped.
+As it produces parts of the chunk,
+<a href="#lua_dump"><code>lua_dump</code></a> calls function <code>writer</code> (see <a href="#lua_Writer"><code>lua_Writer</code></a>)
+to write them.
+
+<p>The value returned is the error code returned by the last
+call to the writer;
+0 means no errors.
+
+<p>This function does not pop the function from the stack.
+
+<p><a name="lua_equal"></a>
+<hr><h3><code>lua_equal</code></h3>
+<pre>
+ int lua_equal (lua_State *L, int index1, int index2);
+</pre>
+
+
+<p>Returns 1 if the two values in acceptable indices <code>index1</code> and
+<code>index2</code> are equal,
+following the semantics of the Lua <code>=</code> operator
+(that is, may call metamethods).
+Otherwise returns 0.
+Also returns 0 if any of the indices are non valid.
+
+<p><a name="lua_error"></a>
+<hr><h3><code>lua_error</code></h3>
+<pre>
+ int lua_error (lua_State *L);
+</pre>
+
+
+<p>Generates a Lua error.
+The error message (which actually can be any type of object)
+must be on the stack top.
+This function does a long jump,
+and therefore never returns.
+
+<p><a name="lua_gc"></a>
+<hr><h3><code>lua_gc</code></h3>
+<pre>
+ int lua_gc (lua_State *L, int what, int data);
+</pre>
+
+
+<p>Controls the garbage collector.
+
+<p>This function performs several tasks,
+according to the value of the parameter <code>what</code>:
+<ul>
+<li> <code>LUA_GCSTOP</code>&mdash; stops the garbage collector.
+<li> <code>LUA_GCRESTART</code>&mdash; restarts the garbage collector.
+<li> <code>LUA_GCCOLLECT</code>&mdash; performs a full garbage-collection cycle.
+<li> <code>LUA_GCCOUNT</code>&mdash; returns the current
+amount of memory (in Kbytes) in use by Lua.
+<li> <code>LUA_GCSTEP</code>&mdash; performs an incremental step of
+garbage collection.
+The step "size" is controlled by <code>data</code>
+(larger values mean more steps) in a non-specified way.
+If you want to control the step size
+you must tune experimentally the value of <code>data</code>.
+The function returns 1 if that step finished a
+garbage-collection cycle.
+<li> <code>LUA_GCSETPAUSE</code>&mdash;
+sets <em><code>data</code>/100</em> as the new value
+for the <em>pause</em> of the collector (see <a href="#GC">2.10</a>).
+<li> <code>LUA_GCSETSTEPMUL</code>&mdash;
+sets <em><code>arg</code>/100</em> as the new value for the <em>step multiplier</em> of
+the collector (see <a href="#GC">2.10</a>).
+</ul>
+
+<p><a name="lua_getallocf"></a>
+<hr><h3><code>lua_getallocf</code></h3>
+<pre>
+ lua_Alloc lua_getallocf (lua_State *L, void **ud);
+</pre>
+
+
+<p>Returns the allocator function of a given state.
+If <code>ud</code> is not <code>NULL</code> Lua stores in <code>*ud</code> the
+opaque pointer passed to <a href="#lua_newstate"><code>lua_newstate</code></a>.
+
+<p><a name="lua_getfenv"></a>
+<hr><h3><code>lua_getfenv</code></h3>
+<pre>
+ void lua_getfenv (lua_State *L, int index);
+</pre>
+
+
+<p>Pushes on the stack the environment table of
+the value at the given index.
+
+<p><a name="lua_getfield"></a>
+<hr><h3><code>lua_getfield</code></h3>
+<pre>
+ void lua_getfield (lua_State *L, int index, const char *k);
+</pre>
+
+
+<p>Pushes onto the stack the value <code>t[k]</code>,
+where <code>t</code> is the value at the given valid index <code>index</code>.
+As in Lua, this function may trigger a metamethod
+for the "index" event (see <a href="#metatable">2.8</a>).
+
+<p><a name="lua_getmetatable"></a>
+<hr><h3><code>lua_getmetatable</code></h3>
+<pre>
+ int lua_getmetatable (lua_State *L, int index);
+</pre>
+
+
+<p>Pushes onto the stack the metatable of the value at the given
+acceptable index.
+If the index is not valid,
+or if the value does not have a metatable,
+returns 0 and pushes nothing on the stack.
+
+<p><a name="lua_gettable"></a>
+<hr><h3><code>lua_gettable</code></h3>
+<pre>
+ void lua_gettable (lua_State *L, int index);
+</pre>
+
+
+<p>Pushes onto the stack the value <code>t[k]</code>,
+where <code>t</code> is the value at the given valid index <code>index</code>
+and <code>k</code> is the value at the top of the stack.
+
+<p>This function pops the key from the stack
+(putting the resulting value in its place).
+As in Lua, this function may trigger a metamethod
+for the "index" event (see <a href="#metatable">2.8</a>).
+
+<p><a name="lua_gettop"></a>
+<hr><h3><code>lua_gettop</code></h3>
+<pre>
+ int lua_gettop (lua_State *L);
+</pre>
+
+
+<p>Returns the index of the top element in the stack.
+Because indices start at 1,
+that result is equal to the number of elements in the stack
+(and so 0 means an empty stack).
+
+<p><a name="lua_insert"></a>
+<hr><h3><code>lua_insert</code></h3>
+<pre>
+ void lua_insert (lua_State *L, int index);
+</pre>
+
+
+<p>Moves the top element into the given valid index,
+shifting up the elements above that position to open space.
+Cannot be called with a pseudo-index,
+because a pseudo-index is not an actual stack position.
+
+<p><a name="lua_Integer"></a>
+<hr><h3><code>lua_Integer</code></h3>
+<pre>
+ typedef ptrdiff_t lua_Integer;
+</pre>
+
+
+<p>The type used by the Lua API to represent integral values.
+
+<p>By default it is a <code>ptrdiff_t</code>,
+which is usually the largest type the machine handles
+"comfortably".
+
+<p><a name="lua_isboolean"></a>
+<hr><h3><code>lua_isboolean</code></h3>
+<pre>
+ int lua_isboolean (lua_State *L, int index);
+</pre>
+
+
+<p>Returns 1 if the value at the given acceptable index has type boolean,
+and 0 otherwise.
+
+<p><a name="lua_iscfunction"></a>
+<hr><h3><code>lua_iscfunction</code></h3>
+<pre>
+ int lua_iscfunction (lua_State *L, int index);
+</pre>
+
+
+<p>Returns 1 if the value at the given acceptable index is a C function,
+and 0 otherwise.
+
+<p><a name="lua_isfunction"></a>
+<hr><h3><code>lua_isfunction</code></h3>
+<pre>
+ int lua_isfunction (lua_State *L, int index);
+</pre>
+
+
+<p>Returns 1 if the value at the given acceptable index is a function
+(either C or Lua), and 0 otherwise.
+
+<p><a name="lua_islightuserdata"></a>
+<hr><h3><code>lua_islightuserdata</code></h3>
+<pre>
+ int lua_islightuserdata (lua_State *L, int index);
+</pre>
+
+
+<p>Returns 1 if the value at the given acceptable index is a light userdata,
+and 0 otherwise.
+
+<p><a name="lua_isnil"></a>
+<hr><h3><code>lua_isnil</code></h3>
+<pre>
+ int lua_isnil (lua_State *L, int index);
+</pre>
+
+
+<p>Returns 1 if the value at the given acceptable index is <B>nil</B>,
+and 0 otherwise.
+
+<p><a name="lua_isnumber"></a>
+<hr><h3><code>lua_isnumber</code></h3>
+<pre>
+ int lua_isnumber (lua_State *L, int index);
+</pre>
+
+
+<p>Returns 1 if the value at the given acceptable index is a number
+or a string convertible to a number,
+and 0 otherwise.
+
+<p><a name="lua_isstring"></a>
+<hr><h3><code>lua_isstring</code></h3>
+<pre>
+ int lua_isstring (lua_State *L, int index);
+</pre>
+
+
+<p>Returns 1 if the value at the given acceptable index is a string
+or a number (which is always convertible to a string),
+and 0 otherwise.
+
+<p><a name="lua_istable"></a>
+<hr><h3><code>lua_istable</code></h3>
+<pre>
+ int lua_istable (lua_State *L, int index);
+</pre>
+
+
+<p>Returns 1 if the value at the given acceptable index is a table,
+and 0 otherwise.
+
+<p><a name="lua_isthread"></a>
+<hr><h3><code>lua_isthread</code></h3>
+<pre>
+ int lua_isthread (lua_State *L, int index);
+</pre>
+
+
+<p>Returns 1 if the value at the given acceptable index is a thread,
+and 0 otherwise.
+
+<p><a name="lua_isuserdata"></a>
+<hr><h3><code>lua_isuserdata</code></h3>
+<pre>
+ int lua_isuserdata (lua_State *L, int index);
+</pre>
+
+
+<p>Returns 1 if the value at the given acceptable index is a userdata
+(either full or light), and 0 otherwise.
+
+<p><a name="lua_lessthan"></a>
+<hr><h3><code>lua_lessthan</code></h3>
+<pre>
+ int lua_lessthan (lua_State *L, int index1, int index2);
+</pre>
+
+
+<p>Returns 1 if the value in acceptable index <code>index1</code> is smaller
+than the value in acceptable index <code>index2</code>,
+following the semantics of the Lua <code>&#060;</code> operator
+(that is, may call metamethods).
+Otherwise returns 0.
+Also returns 0 if any of the indices are non valid.
+
+<p><a name="lua_load"></a>
+<hr><h3><code>lua_load</code></h3>
+<pre>
+ int lua_load (lua_State *L, lua_Reader reader, void *data,
+ const char *chunkname);
+
+</pre>
+
+
+<p>Loads a Lua chunk.
+If there are no errors,
+<a href="#lua_load"><code>lua_load</code></a> pushes the compiled chunk as a Lua
+function on top of the stack.
+Otherwise, it pushes an error message.
+The return values of <a href="#lua_load"><code>lua_load</code></a> are:
+<ul>
+<li> 0 &mdash; no errors;
+<li> <code>LUA_ERRSYNTAX</code> &mdash;
+syntax error during pre-compilation.
+<li> <code>LUA_ERRMEM</code> &mdash;
+memory allocation error.
+</ul>
+
+<p><a href="#lua_load"><code>lua_load</code></a> automatically detects whether the chunk is text or binary,
+and loads it accordingly (see program <code>luac</code>).
+
+<p><a href="#lua_load"><code>lua_load</code></a> uses a user-supplied <code>reader</code> function to read the chunk
+(see <a href="#lua_Reader"><code>lua_Reader</code></a>).
+The <code>data</code> argument is an opaque value passed to the reader function.
+
+<p>The <code>chunkname</code> argument gives the chunk name.
+It is used for error messages and debug information (see <a href="#debugI">3.8</a>).
+
+<p><a name="lua_newstate"></a>
+<hr><h3><code>lua_newstate</code></h3>
+<pre>
+ lua_State *lua_newstate (lua_Alloc f, void *ud);
+</pre>
+
+
+<p>Creates a new, independent state.
+Returns <code>NULL</code> if cannot create the state
+(not enough memory).
+The argument <code>f</code> is the allocator function;
+Lua does all memory allocation for that state through that function.
+The second argument, <code>ud</code>, is an opaque pointer that Lua
+simply passes to the allocator in every call.
+
+<p><a name="lua_newtable"></a>
+<hr><h3><code>lua_newtable</code></h3>
+<pre>
+ void lua_newtable (lua_State *L);
+</pre>
+
+
+<p>Creates a new empty table and pushes it onto the stack.
+Equivalent to <code>lua_createtable(L, 0, 0)</code>.
+
+<p><a name="lua_newthread"></a>
+<hr><h3><code>lua_newthread</code></h3>
+<pre>
+ lua_State *lua_newthread (lua_State *L);
+</pre>
+
+
+<p>Creates a new thread, pushes it on the stack,
+and returns a pointer to a <a href="#lua_State"><code>lua_State</code></a> that represents this new thread.
+The new state returned by this function shares with the original state
+all global objects (such as tables),
+but has an independent run-time stack.
+
+<p>There is no explicit function to close or to destroy a thread.
+Threads are subject to garbage collection,
+like any Lua object.
+
+<p><a name="lua_newuserdata"></a>
+<hr><h3><code>lua_newuserdata</code></h3>
+<pre>
+ void *lua_newuserdata (lua_State *L, size_t size);
+</pre>
+
+
+<p>This function allocates a new block of memory with the given size,
+pushes on the stack a new full userdata with the block address,
+and returns this address.
+
+<p>Userdata represents C values in Lua.
+A <em>full userdata</em> represents a block of memory.
+It is an object (like a table):
+You must create it, it can have its own metatable,
+and you can detect when it is being collected.
+A full userdata is only equal to itself (under raw equality).
+
+<p>When Lua collects a full userdata,
+it calls the userdata's <code>gc</code> metamethod, if any,
+and then it frees the userdata's corresponding memory.
+
+<p><a name="lua_next"></a>
+<hr><h3><code>lua_next</code></h3>
+<pre>
+ int lua_next (lua_State *L, int index);
+</pre>
+
+
+<p>Pops a key from the stack,
+and pushes a key-value pair from the table
+(the "next" pair after the given key).
+If there are no more elements,
+then <a href="#lua_next"><code>lua_next</code></a> returns 0 (and pushes nothing).
+
+<p>A typical traversal looks like this:
+<PRE>
+ /* table is in the stack at index `t' */
+ lua_pushnil(L); /* first key */
+ while (lua_next(L, t) != 0) {
+ /* `key' is at index -2 and `value' at index -1 */
+ printf("%s - %s\n",
+ lua_typename(L, lua_type(L, -2)), lua_typename(L, lua_type(L, -1)));
+ lua_pop(L, 1); /* removes `value'; keeps `key' for next iteration */
+ }
+</PRE>
+
+<p>While traversing a table,
+do not call <a href="#lua_tolstring"><code>lua_tolstring</code></a> directly on a key,
+unless you know that the key is actually a string.
+Recall that <a href="#lua_tolstring"><code>lua_tolstring</code></a> <em>changes</em>
+the value at the given index;
+this confuses the next call to <a href="#lua_next"><code>lua_next</code></a>.
+
+<p><a name="lua_Number"></a>
+<hr><h3><code>lua_Number</code></h3>
+<pre>
+ typedef double lua_Number;
+</pre>
+
+
+<p>The type of numbers in Lua.
+
+<p>Through the configuration file you can change
+Lua to operate with other type for numbers (e.g., float or long).
+
+<p><a name="lua_objlen"></a>
+<hr><h3><code>lua_objlen</code></h3>
+<pre>
+ size_t lua_objlen (lua_State *L, int index);
+</pre>
+
+
+<p>Returns the "length" of the value at the given acceptable index:
+For strings, this is the string length;
+for tables, this is the result of the length operator (`<code>#</code>&acute;).
+for userdata, this is the size of the block of memory allocated
+for the userdatum.
+For other values, returns 0.
+
+<p><a name="lua_pcall"></a>
+<hr><h3><code>lua_pcall</code></h3>
+<pre>
+ lua_pcall (lua_State *L, int nargs, int nresults, int errfunc);
+</pre>
+
+
+<p>Calls a function in protected mode.
+
+<p>Both <code>nargs</code> and <code>nresults</code> have the same meaning as
+in <a href="#lua_call"><code>lua_call</code></a>.
+If there are no errors during the call,
+<a href="#lua_pcall"><code>lua_pcall</code></a> behaves exactly like <a href="#lua_call"><code>lua_call</code></a>.
+However, if there is any error,
+<a href="#lua_pcall"><code>lua_pcall</code></a> catches it,
+pushes a single value on the stack (the error message),
+and returns an error code.
+Like <a href="#lua_call"><code>lua_call</code></a>,
+<a href="#lua_pcall"><code>lua_pcall</code></a> always removes the function
+and its arguments from the stack.
+
+<p>If <code>errfunc</code> is 0,
+then the error message returned is exactly the original error message.
+Otherwise, <code>errfunc</code> is the stack index of an
+<em>error handler function</em>.
+(In the current implementation, that index cannot be a pseudo-index.)
+In case of runtime errors,
+that function will be called with the error message
+and its return value will be the message returned by <a href="#lua_pcall"><code>lua_pcall</code></a>.
+
+<p>Typically, the error handler function is used to add more debug
+information to the error message, such as a stack traceback.
+Such information cannot be gathered after the return of <a href="#lua_pcall"><code>lua_pcall</code></a>,
+since by then the stack has unwound.
+
+<p>The <a href="#lua_pcall"><code>lua_pcall</code></a> function returns 0 in case of success
+or one of the following error codes
+(defined in <code>lua.h</code>):
+<ul>
+<li> <code>LUA_ERRRUN</code> &mdash; a runtime error.
+<li> <code>LUA_ERRMEM</code> &mdash; memory allocation error.
+For such errors, Lua does not call the error handler function.
+<li> <code>LUA_ERRERR</code> &mdash;
+error while running the error handler function.
+</ul>
+
+<p><a name="lua_pop"></a>
+<hr><h3><code>lua_pop</code></h3>
+<pre>
+ void lua_pop (lua_State *L, int n);
+</pre>
+
+
+<p>Pops <code>n</code> elements from the stack.
+
+<p><a name="lua_pushboolean"></a>
+<hr><h3><code>lua_pushboolean</code></h3>
+<pre>
+ void lua_pushboolean (lua_State *L, int b);
+</pre>
+
+
+<p>Pushes a boolean value with value <code>b</code> onto the stack.
+
+<p><a name="lua_pushcclosure"></a>
+<hr><h3><code>lua_pushcclosure</code></h3>
+<pre>
+ void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);
+</pre>
+
+
+<p>Pushes a new C closure onto the stack.
+
+<p>When a C function is created,
+it is possible to associate some values with it,
+thus creating a <em>C closure</em> (see <a href="#c-closure">3.4</a>);
+these values are then accessible to the function whenever it is called.
+To associate values with a C function,
+first these values should be pushed onto the stack
+(when there are multiple values, the first value is pushed first).
+Then the function <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>
+is used to create and push the C function onto the stack,
+with the argument <code>n</code> telling how many values should be
+associated with the function.
+<a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> also pops these values from the stack.
+
+<p><a name="lua_pushcfunction"></a>
+<hr><h3><code>lua_pushcfunction</code></h3>
+<pre>
+ void lua_pushcfunction (lua_State *L, lua_CFunction f);
+</pre>
+
+
+<p>Pushes a C function onto the stack.
+This function is equivalent to <code>lua_pushcclosure(L, f, 0);</code>.
+
+<p><a name="lua_pushfstring"></a>
+<hr><h3><code>lua_pushfstring</code></h3>
+<pre>
+ const char *lua_pushfstring (lua_State *L, const char *fmt, ...);
+</pre>
+
+
+<p>Pushes onto the stack a formatted string
+and returns a pointer to that string.
+It is similar to the C function <code>sprintf</code>
+but with some important differences:
+<ul>
+<li> You do not have to allocate the space for the result:
+The result is a Lua string and Lua takes care of memory allocation
+(and deallocation, through garbage collection).
+<li> The conversion specifiers are quite restricted.
+There are no flags, widths, or precisions.
+The conversion specifiers can be simply
+`<code>%%</code>&acute; (inserts a `<code>%</code>&acute; in the string),
+`<code>%s</code>&acute; (inserts a zero-terminated string, with no size restrictions),
+`<code>%f</code>&acute; (inserts a <a href="#lua_Number"><code>lua_Number</code></a>),
+`<code>%p</code>&acute; (inserts a pointer as an hexadecimal numeral),
+`<code>%d</code>&acute; (inserts an <code>int</code>), and
+`<code>%c</code>&acute; (inserts an <code>int</code> as a character).
+</ul>
+
+<p><a name="lua_pushinteger"></a>
+<hr><h3><code>lua_pushinteger</code></h3>
+<pre>
+ void lua_pushinteger (lua_State *L, lua_Integer n);
+</pre>
+
+
+<p>Pushes a number with value <code>n</code> onto the stack.
+
+<p><a name="lua_pushlightuserdata"></a>
+<hr><h3><code>lua_pushlightuserdata</code></h3>
+<pre>
+ void lua_pushlightuserdata (lua_State *L, void *p);
+</pre>
+
+
+<p>Pushes a light userdata onto the stack.
+
+<p>Userdata represents C values in Lua.
+A <em>light userdata</em> represents a pointer.
+It is a value (like a number):
+You do not create it, it has no metatables,
+it is not collected (as it was never created).
+A light userdata is equal to "any"
+light userdata with the same C address.
+
+<p><a name="lua_pushlstring"></a>
+<hr><h3><code>lua_pushlstring</code></h3>
+<pre>
+ void lua_pushlstring (lua_State *L, const char *s, size_t len);
+</pre>
+
+
+<p>Pushes the string pointed by <code>s</code> with size <code>len</code>
+onto the stack.
+Lua makes (or reuses) an internal copy of the given string,
+so the memory at <code>s</code> can be freed or reused immediately after
+the function returns.
+
+<p><a name="lua_pushnil"></a>
+<hr><h3><code>lua_pushnil</code></h3>
+<pre>
+ void lua_pushnil (lua_State *L);
+</pre>
+
+
+<p>Pushes a nil value onto the stack.
+
+<p><a name="lua_pushnumber"></a>
+<hr><h3><code>lua_pushnumber</code></h3>
+<pre>
+ void lua_pushnumber (lua_State *L, lua_Number n);
+</pre>
+
+
+<p>Pushes a number with value <code>n</code> onto the stack.
+
+<p><a name="lua_pushstring"></a>
+<hr><h3><code>lua_pushstring</code></h3>
+<pre>
+ void lua_pushstring (lua_State *L, const char *s);
+</pre>
+
+
+<p>Pushes the zero-terminated string pointed by <code>s</code>
+onto the stack.
+Lua makes (or reuses) an internal copy of the given string,
+so the memory at <code>s</code> can be freed or reused immediately after
+the function returns.
+
+<p><a name="lua_pushvalue"></a>
+<hr><h3><code>lua_pushvalue</code></h3>
+<pre>
+ void lua_pushvalue (lua_State *L, int index);
+</pre>
+
+
+<p>Pushes a copy of the element at the given valid index
+onto the stack.
+
+<p><a name="lua_pushvfstring"></a>
+<hr><h3><code>lua_pushvfstring</code></h3>
+<pre>
+ const char *lua_pushvfstring (lua_State *L, const char *fmt, va_list argp);
+</pre>
+
+
+<p>Equivalent to <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>, except that it receives a <code>va_list</code>
+instead of a variable number of arguments.
+
+<p><a name="lua_rawequal"></a>
+<hr><h3><code>lua_rawequal</code></h3>
+<pre>
+ int lua_rawequal (lua_State *L, int index1, int index2);
+</pre>
+
+
+<p>Returns 1 if the two values in acceptable indices <code>index1</code> and
+<code>index2</code> are primitively equal
+(that is, without calling metamethods).
+Otherwise returns 0.
+Also returns 0 if any of the indices are non valid.
+
+<p><a name="lua_rawget"></a>
+<hr><h3><code>lua_rawget</code></h3>
+<pre>
+ void lua_rawget (lua_State *L, int index);
+</pre>
+
+
+<p>Similar to <a href="#lua_gettable"><code>lua_gettable</code></a>, but doing a raw indexing
+(i.e., without metamethods).
+
+<p><a name="lua_rawgeti"></a>
+<hr><h3><code>lua_rawgeti</code></h3>
+<pre>
+ void lua_rawgeti (lua_State *L, int index, int n);
+</pre>
+
+
+<p>Pushes onto the stack the value <code>t[n]</code>,
+where <code>t</code> is the value at the given valid index <code>index</code>.
+The access is raw,
+that is, it does not invoke metamethods.
+
+<p><a name="lua_rawset"></a>
+<hr><h3><code>lua_rawset</code></h3>
+<pre>
+ void lua_rawset (lua_State *L, int index);
+</pre>
+
+
+<p>Similar to <a href="#lua_settable"><code>lua_settable</code></a>, but doing a raw assignment
+(i.e., without metamethods).
+
+<p><a name="lua_rawseti"></a>
+<hr><h3><code>lua_rawseti</code></h3>
+<pre>
+ void lua_rawseti (lua_State *L, int index, int n);
+</pre>
+
+
+<p>Does the equivalent to <code>t[n] = v</code>,
+where <code>t</code> is the value at the given valid index <code>index</code>
+and <code>v</code> is the value at the top of the stack,
+
+<p>This function pops the value from the stack.
+The assignment is raw,
+that is, it does not invoke metamethods.
+
+<p><a name="lua_Reader"></a>
+<hr><h3><code>lua_Reader</code></h3>
+<pre>
+ typedef const char * (*lua_Reader)
+ (lua_State *L, void *data, size_t *size);
+
+</pre>
+
+
+<p>The reader function used by <a href="#lua_load"><code>lua_load</code></a>.
+Every time it needs another piece of the chunk,
+<a href="#lua_load"><code>lua_load</code></a> calls the reader,
+passing along its <code>data</code> parameter.
+The reader must return a pointer to a block of memory
+with a new piece of the chunk
+and set <code>size</code> to the block size.
+To signal the end of the chunk, the reader returns <code>NULL</code>.
+The reader function may return pieces of any size greater than zero.
+
+<p><a name="lua_remove"></a>
+<hr><h3><code>lua_remove</code></h3>
+<pre>
+ void lua_remove (lua_State *L, int index);
+</pre>
+
+
+<p>Removes the element at the given valid index,
+shifting down the elements above that position to fill the gap.
+Cannot be called with a pseudo-index,
+because a pseudo-index is not an actual stack position.
+
+<p><a name="lua_replace"></a>
+<hr><h3><code>lua_replace</code></h3>
+<pre>
+ void lua_replace (lua_State *L, int index);
+</pre>
+
+
+<p>Moves the top element into the given position (and pops it),
+without shifting any element
+(therefore replacing the value at the given position).
+
+<p><a name="lua_resume"></a>
+<hr><h3><code>lua_resume</code></h3>
+<pre>
+ int lua_resume (lua_State *L, int narg);
+</pre>
+
+
+<p>Starts and resumes a coroutine in a given thread.
+
+<p>To start a coroutine, you first create a new thread
+(see <a href="#lua_newthread"><code>lua_newthread</code></a>);
+then you push on its stack the body function plus any eventual arguments;
+then you call <a href="#lua_resume"><code>lua_resume</code></a>,
+with <code>narg</code> being the number of arguments.
+This call returns when the coroutine suspends or finishes its execution.
+When it returns, the stack contains all values passed to <a href="#lua_yield"><code>lua_yield</code></a>,
+or all values returned by the body function.
+<a href="#lua_resume"><code>lua_resume</code></a> returns 0 if there are no errors running the coroutine,
+or an error code (see <a href="#lua_pcall"><code>lua_pcall</code></a>).
+In case of errors,
+the stack is not unwound,
+so you can use the debug API over it;
+The error message is on the top of the stack.
+To restart a coroutine, you put on its stack only the values to
+be passed as results from <code>yield</code>,
+and then call <a href="#lua_resume"><code>lua_resume</code></a>.
+
+<p><a name="lua_setfenv"></a>
+<hr><h3><code>lua_setfenv</code></h3>
+<pre>
+ int lua_setfenv (lua_State *L, int index);
+</pre>
+
+
+<p>Pops a table from the stack and sets it as
+the new environment for the value at the given index.
+If the value at the given index is
+neither a function nor a thread nor a userdata,
+<a href="#lua_setfenv"><code>lua_setfenv</code></a> returns 0 (false).
+
+<p><a name="lua_setfield"></a>
+<hr><h3><code>lua_setfield</code></h3>
+<pre>
+ void lua_setfield (lua_State *L, int index, const char *k);
+</pre>
+
+
+<p>Does the equivalent to <code>t[k] = v</code>,
+where <code>t</code> is the value at the given valid index <code>index</code>
+and <code>v</code> is the value at the top of the stack,
+
+<p>This function pops the value from the stack.
+As in Lua, this function may trigger a metamethod
+for the "newindex" event (see <a href="#metatable">2.8</a>).
+
+<p><a name="lua_setmetatable"></a>
+<hr><h3><code>lua_setmetatable</code></h3>
+<pre>
+ int lua_setmetatable (lua_State *L, int index);
+</pre>
+
+
+<p>Pops a table from the stack and
+sets it as the new metatable for the value at the given
+acceptable index.
+
+<p><a name="lua_settable"></a>
+<hr><h3><code>lua_settable</code></h3>
+<pre>
+ void lua_settable (lua_State *L, int index);
+</pre>
+
+
+<p>Does the equivalent to <code>t[k] = v</code>,
+where <code>t</code> is the value at the given valid index <code>index</code>,
+<code>v</code> is the value at the top of the stack,
+and <code>k</code> is the value just below the top.
+
+<p>This function pops both the key and the value from the stack.
+As in Lua, this function may trigger a metamethod
+for the "newindex" event (see <a href="#metatable">2.8</a>).
+
+<p><a name="lua_settop"></a>
+<hr><h3><code>lua_settop</code></h3>
+<pre>
+ void lua_settop (lua_State *L, int index);
+</pre>
+
+
+<p>Accepts any acceptable index, or 0,
+and sets the stack top to that index.
+If the new top is larger than the old one,
+then the new elements are filled with <B>nil</B>.
+If <code>index</code> is 0, then all stack elements are removed.
+
+<p><a name="lua_State"></a>
+<hr><h3><code>lua_State</code></h3>
+<pre>
+ typedef struct lua_State lua_State;
+</pre>
+
+
+<p>Opaque structure that keeps the whole state of a Lua interpreter.
+The Lua library is fully reentrant:
+it has no global variables.
+All information about a state is kept in this structure.
+
+<p>A pointer to this state must be passed as the first argument to
+every function in the library, except to <a href="#lua_newstate"><code>lua_newstate</code></a>,
+which creates a Lua state from scratch.
+
+<p><a name="lua_toboolean"></a>
+<hr><h3><code>lua_toboolean</code></h3>
+<pre>
+ int lua_toboolean (lua_State *L, int index);
+</pre>
+
+
+<p>Converts the Lua value at the given acceptable index to a C boolean
+value ((0 or 1).
+Like all tests in Lua,
+<a href="#lua_toboolean"><code>lua_toboolean</code></a> returns 1 for any Lua value
+different from <B>false</B> and <B>nil</B>;
+otherwise it returns 0.
+It also returns 0 when called with a non-valid index.
+(If you want to accept only real boolean values,
+use <a href="#lua_isboolean"><code>lua_isboolean</code></a> to test the value's type.)
+
+<p><a name="lua_tocfunction"></a>
+<hr><h3><code>lua_tocfunction</code></h3>
+<pre>
+ lua_CFunction lua_tocfunction (lua_State *L, int index);
+</pre>
+
+
+<p>Converts a value at the given acceptable index to a C function.
+That value must be a C function;
+otherwise, returns <code>NULL</code>.
+
+<p><a name="lua_tointeger"></a>
+<hr><h3><code>lua_tointeger</code></h3>
+<pre>
+ lua_Integer lua_tointeger (lua_State *L, int idx);
+</pre>
+
+
+<p>Converts the Lua value at the given acceptable index
+to the signed integral type <a href="#lua_Integer"><code>lua_Integer</code></a>.
+The Lua value must be a number or a string convertible to number
+(see <a href="#coercion">2.2.1</a>);
+otherwise, <a href="#lua_tointeger"><code>lua_tointeger</code></a> returns 0.
+
+<p>If the number is not an integer,
+it is truncated in some non-specified way.
+
+<p><a name="lua_tolstring"></a>
+<hr><h3><code>lua_tolstring</code></h3>
+<pre>
+ const char *lua_tolstring (lua_State *L, int index, size_t *len);
+</pre>
+
+
+<p>Converts the Lua value at the given acceptable index to a string
+(<code>const char*</code>).
+If <code>len</code> is not <code>NULL</code>,
+it also sets <code>*len</code> with the string length.
+The Lua value must be a string or a number;
+otherwise, the function returns <code>NULL</code>.
+If the value is a number,
+then <a href="#lua_tolstring"><code>lua_tolstring</code></a> also
+<em>changes the actual value in the stack to a string</em>.
+(This change confuses <a href="#lua_next"><code>lua_next</code></a>
+when <a href="#lua_tolstring"><code>lua_tolstring</code></a> is applied to keys.)
+
+<p><a href="#lua_tolstring"><code>lua_tolstring</code></a> returns a fully aligned pointer
+to a string inside the Lua state.
+This string always has a zero (<code>'\0'</code>)
+after its last character (as in C),
+but may contain other zeros in its body.
+Because Lua has garbage collection,
+there is no guarantee that the pointer returned by <a href="#lua_tolstring"><code>lua_tolstring</code></a>
+will be valid after the corresponding value is removed from the stack.
+
+<p><a name="lua_tonumber"></a>
+<hr><h3><code>lua_tonumber</code></h3>
+<pre>
+ lua_Number lua_tonumber (lua_State *L, int index);
+</pre>
+
+
+<p>Converts the Lua value at the given acceptable index
+to a number (see <a href="#lua_Number"><code>lua_Number</code></a>).
+The Lua value must be a number or a string convertible to number
+(see <a href="#coercion">2.2.1</a>);
+otherwise, <a href="#lua_tonumber"><code>lua_tonumber</code></a> returns 0.
+
+<p><a name="lua_topointer"></a>
+<hr><h3><code>lua_topointer</code></h3>
+<pre>
+ const void *lua_topointer (lua_State *L, int index);
+</pre>
+
+
+<p>Converts the value at the given acceptable index to a generic
+C pointer (<code>void *</code>).
+The value may be a userdata, a table, a thread, or a function;
+otherwise, <a href="#lua_topointer"><code>lua_topointer</code></a> returns <code>NULL</code>.
+Lua ensures that different objects return different pointers.
+There is no direct way to convert the pointer back to its original value.
+
+<p>Typically this function is used for debug information.
+
+<p><a name="lua_tostring"></a>
+<hr><h3><code>lua_tostring</code></h3>
+<pre>
+ const char *lua_tostring (lua_State *L, int index);
+</pre>
+
+
+<p>Equivalent to <a href="#lua_tolstring"><code>lua_tolstring</code></a> with <code>len</code> equal to <code>NULL</code>.
+
+<p><a name="lua_tothread"></a>
+<hr><h3><code>lua_tothread</code></h3>
+<pre>
+ lua_State *lua_tothread (lua_State *L, int index);
+</pre>
+
+
+<p>Converts the value at the given acceptable index to a Lua thread
+(represented as <code>lua_State *</code>).
+This value must be a thread;
+otherwise, the function returns <code>NULL</code>.
+
+<p><a name="lua_touserdata"></a>
+<hr><h3><code>lua_touserdata</code></h3>
+<pre>
+ void *lua_touserdata (lua_State *L, int index);
+</pre>
+
+
+<p>If the value at the given acceptable index is a full userdata,
+returns its block address.
+If the value is a light userdata,
+returns its pointer.
+Otherwise, returns <code>NULL</code>.
+
+<p><a name="lua_type"></a>
+<hr><h3><code>lua_type</code></h3>
+<pre>
+ int lua_type (lua_State *L, int index);
+</pre>
+
+
+<p>Returns the type of a value in the given acceptable index,
+or <code>LUA_TNONE</code> for a non-valid index
+(that is, an index to an "empty" stack position).
+The types returned by <a href="#lua_type"><code>lua_type</code></a> are coded by the following constants
+defined in <code>lua.h</code>:
+<code>LUA_TNIL</code>,
+<code>LUA_TNUMBER</code>,
+<code>LUA_TBOOLEAN</code>,
+<code>LUA_TSTRING</code>,
+<code>LUA_TTABLE</code>,
+<code>LUA_TFUNCTION</code>,
+<code>LUA_TUSERDATA</code>,
+<code>LUA_TTHREAD</code>,
+<code>LUA_TLIGHTUSERDATA</code>.
+
+<p><a name="lua_Writer"></a>
+<hr><h3><code>lua_Writer</code></h3>
+<pre>
+ typedef int (*lua_Writer)
+ (lua_State *L, const void* p, size_t sz, void* ud);
+
+</pre>
+
+
+<p>The writer function used by <a href="#lua_dump"><code>lua_dump</code></a>.
+Every time it produces another piece of chunk,
+<a href="#lua_dump"><code>lua_dump</code></a> calls the writer,
+passing along the buffer to be written (<code>p</code>),
+its size (<code>sz</code>),
+and the <code>data</code> parameter supplied to <a href="#lua_dump"><code>lua_dump</code></a>.
+
+<p>The writer returns an error code:
+0 means no errors;
+any other value means an error and stops <a href="#lua_dump"><code>lua_dump</code></a> from
+calling the writer again.
+
+<p><a name="lua_xmove"></a>
+<hr><h3><code>lua_xmove</code></h3>
+<pre>
+ void lua_xmove (lua_State *from, lua_State *to, int n);
+</pre>
+
+
+<p>Exchange values between different threads of the same global state.
+
+<p>This function pops <code>n</code> values from the stack <code>from</code>,
+and pushes them into the stack <code>to</code>.
+
+<p><a name="lua_yield"></a>
+<hr><h3><code>lua_yield</code></h3>
+<pre>
+ int lua_yield (lua_State *L, int nresults);
+</pre>
+
+
+<p>Yields a coroutine.
+
+<p>This function can only be called as the
+return expression of a C function, as follows:
+<PRE>
+ return lua_yield (L, nresults);
+</PRE>
+When a C function calls <a href="#lua_yield"><code>lua_yield</code></a> in that way,
+the running coroutine suspends its execution,
+and the call to <a href="#lua_resume"><code>lua_resume</code></a> that started this coroutine returns.
+The parameter <code>nresults</code> is the number of values from the stack
+that are passed as results to <a href="#lua_resume"><code>lua_resume</code></a>.
+
+<p>
+<a name="debugI"></a><a name="3.8"></a><h2>3.8 - The Debug Interface</h2>
+
+<p>Lua has no built-in debugging facilities.
+Instead, it offers a special interface
+by means of functions and <em>hooks</em>.
+This interface allows the construction of different
+kinds of debuggers, profilers, and other tools
+that need "inside information" from the interpreter.
+
+<p><a name="lua_Debug"></a>
+<hr><h3><code>lua_Debug</code></h3>
+<pre>
+ typedef struct lua_Debug {
+ int event;
+ const char *name; /* (n) */
+ const char *namewhat; /* (n) */
+ const char *what; /* (S) */
+ const char *source; /* (S) */
+ int currentline; /* (l) */
+ int nups; /* (u) number of upvalues */
+ int linedefined; /* (S) */
+ int lastlinedefined; /* (S) */
+ char short_src[LUA_IDSIZE]; /* (S) */
+
+<p> /* private part */
+ ...
+ } lua_Debug;
+
+</pre>
+
+
+<p>A structure used to carry different pieces of
+information about an active function.
+<a href="#lua_getstack"><code>lua_getstack</code></a> fills only the private part
+of this structure, for later use.
+To fill the other fields of <a href="#lua_Debug"><code>lua_Debug</code></a> with useful information,
+call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
+
+<p>The fields of <a href="#lua_Debug"><code>lua_Debug</code></a> have the following meaning:
+<ul>
+<li><b><code>source</code></b>
+If the function was defined in a string,
+then <code>source</code> is that string.
+If the function was defined in a file,
+then <code>source</code> starts with a `<code>@</code>&acute; followed by the file name.
+
+<p><li><b><code>short_src</code></b>
+A "printable" version of <code>source</code>, to be used in error messages.
+
+<p><li><b><code>linedefined</code></b>
+the line number where the definition of the function starts.
+
+<p><li><b><code>lastlinedefined</code></b>
+the line number where the definition of the function ends.
+
+<p><li><b><code>what</code></b> the string <code>"Lua"</code> if this is a Lua function,
+<code>"C"</code> if this is a C function,
+<code>"main"</code> if this is the main part of a chunk,
+and <code>"tail"</code> if this was a function that did a tail call.
+In the latter case,
+Lua has no other information about this function.
+
+<p><li><b><code>currentline</code></b>
+the current line where the given function is executing.
+When no line information is available,
+<code>currentline</code> is set to <em>-1</em>.
+
+<p><li><b><code>name</code></b>
+a reasonable name for the given function.
+Because functions in Lua are first class values,
+they do not have a fixed name:
+Some functions may be the value of multiple global variables,
+while others may be stored only in a table field.
+The <code>lua_getinfo</code> function checks how the function was
+called to find a suitable name.
+If it cannot find a name,
+then <code>name</code> is set to <code>NULL</code>.
+
+<p><li><b><code>namewhat</code></b>
+Explains the <code>name</code> field.
+The value of <code>namewhat</code> can be
+<code>"global"</code>, <code>"local"</code>, <code>"method"</code>,
+<code>"field"</code>, <code>"upvalue"</code>, or <code>""</code> (the empty string),
+according to how the function was called.
+(Lua uses the empty string when no other option seems to apply.)
+
+<p><li><b><code>nups</code></b>
+The number of upvalues of the function.
+
+<p></ul>
+
+<p><a name="lua_gethook"></a>
+<hr><h3><code>lua_gethook</code></h3>
+<pre>
+ lua_Hook lua_gethook (lua_State *L);
+</pre>
+
+
+<p>Returns the current hook function.
+
+<p><a name="lua_gethookcount"></a>
+<hr><h3><code>lua_gethookcount</code></h3>
+<pre>
+ int lua_gethookcount (lua_State *L);
+</pre>
+
+
+<p>Returns the current hook count.
+
+<p><a name="lua_gethookmask"></a>
+<hr><h3><code>lua_gethookmask</code></h3>
+<pre>
+ int lua_gethookmask (lua_State *L);
+</pre>
+
+
+<p>Returns the current hook mask.
+
+<p><a name="lua_getinfo"></a>
+<hr><h3><code>lua_getinfo</code></h3>
+<pre>
+ int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);
+</pre>
+
+
+<p>Fills the fields of <a href="#lua_Debug"><code>lua_Debug</code></a> with useful information.
+
+<p>This function returns 0 on error
+(for instance, an invalid option in <code>what</code>).
+Each character in the string <code>what</code>
+selects some fields of the structure <code>ar</code> to be filled,
+as indicated by the letter in parentheses in the definition of <a href="#lua_Debug"><code>lua_Debug</code></a>:
+`<code>S</code>&acute; fills in the fields <code>source</code>, <code>linedefined</code>,
+<code>lastlinedefined</code>,
+and <code>what</code>;
+`<code>l</code>&acute; fills in the field <code>currentline</code>, etc.
+Moreover, `<code>f</code>&acute; pushes onto the stack the function that is
+running at the given level.
+
+<p>To get information about a function that is not active
+(that is, not in the stack),
+you push it onto the stack
+and start the <code>what</code> string with the character `<code>></code>&acute;.
+For instance, to know in which line a function <code>f</code> was defined,
+you can write the following code:
+<PRE>
+ lua_Debug ar;
+ lua_getfield(L, LUA_GLOBALSINDEX, "f"); /* get global `f' */
+ lua_getinfo(L, ">S", &#038;ar);
+ printf("%d\n", ar.linedefined);
+</PRE>
+
+<p><a name="lua_getlocal"></a>
+<hr><h3><code>lua_getlocal</code></h3>
+<pre>
+ const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);
+</pre>
+
+
+<p>Gets information about a local variable of a given activation record.
+The parameter <code>ar</code> must be a valid activation record that was
+filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
+given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
+The index <code>n</code> selects which local variable to inspect
+(1 is the first parameter or active local variable, and so on,
+until the last active local variable).
+<a href="#lua_getlocal"><code>lua_getlocal</code></a> pushes the variable's value onto the stack,
+and returns its name.
+
+<p>Returns <code>NULL</code> (and pushes nothing)
+when the index is greater than
+the number of active local variables.
+
+<p><a name="lua_getstack"></a>
+<hr><h3><code>lua_getstack</code></h3>
+<pre>
+ int lua_getstack (lua_State *L, int level, lua_Debug *ar);
+</pre>
+
+
+<p>Get information about the interpreter runtime stack.
+
+<p>This function fills parts of a <a href="#lua_Debug"><code>lua_Debug</code></a> structure with
+an identification of the <em>activation record</em>
+of the function executing at a given level.
+Level 0 is the current running function,
+whereas level <em>n+1</em> is the function that has called level <em>n</em>.
+When there are no errors, <a href="#lua_getstack"><code>lua_getstack</code></a> returns 1;
+when called with a level greater than the stack depth,
+it returns 0.
+
+<p><a name="lua_getupvalue"></a>
+<hr><h3><code>lua_getupvalue</code></h3>
+<pre>
+ const char *lua_getupvalue (lua_State *L, int funcindex, int n);
+</pre>
+
+
+<p>Gets information about a closure's upvalue.
+(For Lua functions,
+upvalues are the external local variables that the function uses,
+and that consequently are included in its closure.)
+<a href="#lua_getupvalue"><code>lua_getupvalue</code></a> gets the index <code>n</code> of an upvalue,
+pushes the upvalue's value onto the stack,
+and returns its name.
+<code>funcindex</code> points to the closure in the stack.
+(Upvalues have no particular order,
+as they are active through the whole function.)
+
+<p>Returns <code>NULL</code> (and pushes nothing)
+when the index is greater than the number of upvalues.
+For C functions, this function uses the empty string <code>""</code>
+as a name for all upvalues.
+
+<p><a name="lua_Hook"></a>
+<hr><h3><code>lua_Hook</code></h3>
+<pre>
+ typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);
+</pre>
+
+
+<p>Type for debugging hook functions.
+
+<p>Whenever a hook is called, its <code>ar</code> argument has its field
+<code>event</code> set to the specific event that triggered the hook.
+Lua identifies these events with the following constants:
+<code>LUA_HOOKCALL</code>, <code>LUA_HOOKRET</code>,
+<code>LUA_HOOKTAILRET</code>, <code>LUA_HOOKLINE</code>,
+and <code>LUA_HOOKCOUNT</code>.
+Moreover, for line events, the field <code>currentline</code> is also set.
+To get the value of any other field in <code>ar</code>,
+the hook must call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
+For return events, <code>event</code> may be <code>LUA_HOOKRET</code>,
+the normal value, or <code>LUA_HOOKTAILRET</code>.
+In the latter case, Lua is simulating a return from
+a function that did a tail call;
+in this case, it is useless to call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
+
+<p>While Lua is running a hook, it disables other calls to hooks.
+Therefore, if a hook calls back Lua to execute a function or a chunk,
+that execution occurs without any calls to hooks.
+
+<p><a name="lua_sethook"></a>
+<hr><h3><code>lua_sethook</code></h3>
+<pre>
+ int lua_sethook (lua_State *L, lua_Hook func, int mask, int count);
+</pre>
+
+
+<p>Sets the debugging hook function.
+
+<p><code>func</code> is the hook function.
+<code>mask</code> specifies on which events the hook will be called:
+It is formed by a disjunction of the constants
+<code>LUA_MASKCALL</code>,
+<code>LUA_MASKRET</code>,
+<code>LUA_MASKLINE</code>,
+and <code>LUA_MASKCOUNT</code>.
+The <code>count</code> argument is only meaningful when the mask
+includes <code>LUA_MASKCOUNT</code>.
+For each event, the hook is called as explained below:
+<ul>
+<li><b>The call hook</b> is called when the interpreter calls a function.
+The hook is called just after Lua enters the new function.
+<li><b>The return hook</b> is called when the interpreter returns from a function.
+The hook is called just before Lua leaves the function.
+<li><b>The line hook</b> is called when the interpreter is about to
+start the execution of a new line of code,
+or when it jumps back in the code (even to the same line).
+(This event only happens while Lua is executing a Lua function.)
+<li><b>The count hook</b> is called after the interpreter executes every
+<code>count</code> instructions.
+(This event only happens while Lua is executing a Lua function.)
+</ul>
+
+<p>A hook is disabled by setting <code>mask</code> to zero.
+
+<p><a name="lua_setlocal"></a>
+<hr><h3><code>lua_setlocal</code></h3>
+<pre>
+ const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);
+</pre>
+
+
+<p>Sets the value of a local variable of a given activation record.
+Parameters <code>ar</code> and <code>n</code> are like in <a href="#lua_getlocal"><code>lua_getlocal</code></a>
+(see <a href="#lua_getlocal"></a>).
+<a href="#lua_setlocal"><code>lua_setlocal</code></a> assigns the value at the top of the stack
+to the variable and returns its name.
+It also pops the value from the stack.
+
+<p>Returns <code>NULL</code> (and pops nothing)
+when the index is greater than
+the number of active local variables.
+
+<p><a name="lua_setupvalue"></a>
+<hr><h3><code>lua_setupvalue</code></h3>
+<pre>
+ const char *lua_setupvalue (lua_State *L, int funcindex, int n);
+</pre>
+
+
+<p>Sets the value of a closure's upvalue.
+Parameters <code>funcindex</code> and <code>n</code> are like in <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>
+(see <a href="#lua_getupvalue"></a>).
+It assigns the value at the top of the stack
+to the upvalue and returns its name.
+It also pops the value from the stack.
+
+<p>Returns <code>NULL</code> (and pops nothing)
+when the index is greater than the number of upvalues.
+
+<p>
+<a name="4"></a><h1>4 - The Auxiliary Library</h1>
+
+<p>
+The <em>auxiliary library</em> provides several convenient functions
+to interface C with Lua.
+While the basic API provides the primitive functions for all
+interactions between C and Lua,
+the auxiliary library provides higher-level functions for some
+common tasks.
+
+<p>All functions from the auxiliary library
+are defined in header file <code>lauxlib.h</code> and
+have a prefix <code>luaL_</code>.
+
+<p>All functions in the auxiliary library are build on
+top of the basic API, so they provide nothing that cannot
+be done with that API.
+
+<p>Several functions in the auxiliary library are used to
+check C function arguments.
+Their names are always <code>luaL_check*</code> or <code>luaL_opt*</code>.
+All those functions raise an error if the check is not satisfied.
+Because the error message is formatted for arguments
+(e.g., <code>"bad argument #1"</code>),
+you should not use those functions for other stack values.
+
+<p><a name="4.1"></a><h2>4.1 - Functions and Types</h2>
+
+<p>Here we list all functions and types from the auxiliary library
+in alphabetical order.
+
+<p><a name="luaL_addchar"></a>
+<hr><h3><code>luaL_addchar</code></h3>
+<pre>
+ void luaL_addchar (luaL_Buffer B, char c);
+</pre>
+
+
+<p>Adds the character <code>c</code> to the buffer <code>B</code>
+(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
+
+<p><a name="luaL_addlstring"></a>
+<hr><h3><code>luaL_addlstring</code></h3>
+<pre>
+ void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);
+</pre>
+
+
+<p>Adds the string pointed by <code>s</code> with length <code>l</code> to
+the buffer <code>B</code>
+(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
+
+<p><a name="luaL_addsize"></a>
+<hr><h3><code>luaL_addsize</code></h3>
+<pre>
+ void luaL_addsize (luaL_Buffer B, size_t n);
+</pre>
+
+
+<p>Adds a string of length <code>n</code> previously copied to the
+buffer area (see <a href="#luaL_prepbuffer"><code>luaL_prepbuffer</code></a>) to the buffer <code>B</code>
+(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
+
+<p><a name="luaL_addstring"></a>
+<hr><h3><code>luaL_addstring</code></h3>
+<pre>
+ void luaL_addstring (luaL_Buffer *B, const char *s);
+</pre>
+
+
+<p>Adds the zero-terminated string pointed by <code>s</code>
+to the buffer <code>B</code>
+(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
+
+<p><a name="luaL_addvalue"></a>
+<hr><h3><code>luaL_addvalue</code></h3>
+<pre>
+ void luaL_addvalue (luaL_Buffer *B);
+</pre>
+
+
+<p>Adds the value at the top of the stack
+to the buffer <code>B</code>
+(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
+Pops the value.
+
+<p>This is the only function on string buffers that can (and must)
+be called with an extra element on the stack,
+which is the value to be added to the buffer.
+
+<p><a name="luaL_argcheck"></a>
+<hr><h3><code>luaL_argcheck</code></h3>
+<pre>
+ void luaL_argcheck (lua_State *L, int cond, int numarg,
+ const char *extramsg);
+</pre>
+
+
+<p>Checks whether <code>cond</code> is true.
+If not, raise an error with message
+<code>"bad argument #&#060;numarg> to &#060;func> (&#060;extramsg>)"</code>,
+where <code>func</code> is retrieved from the call stack.
+
+<p><a name="luaL_argerror"></a>
+<hr><h3><code>luaL_argerror</code></h3>
+<pre>
+ int luaL_argerror (lua_State *L, int numarg, const char *extramsg);
+</pre>
+
+
+<p>Raises an error with message
+<code>"bad argument #&#060;numarg> to &#060;func> (&#060;extramsg>)"</code>,
+where <code>func</code> is retrieved from the call stack.
+
+<p>This function never returns.
+
+<p><a name="luaL_Buffer"></a>
+<hr><h3><code>luaL_Buffer</code></h3>
+<pre>
+ typedef struct luaL_Buffer luaL_Buffer;
+</pre>
+
+
+<p>Type for a <em>string buffer</em>.
+
+<p>A string buffer allows C code to build Lua strings piecemeal.
+Its pattern of use is as follows:
+<ul>
+<li> Fist you declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.
+<li> Then you initialize it with a call <code>luaL_buffinit(L, &#038;b);</code>.
+<li> Then you add string pieces to the buffer calling any of
+the <code>luaL_add*</code> functions.
+<li> You finish calling <code>luaL_pushresult(&#038;b)</code>.
+That call leaves the final string on the top of the stack.
+</ul>
+
+<p>During its normal operation a string buffer uses a
+variable number of stack slots.
+So, while using a buffer, you cannot assume that you know where
+is the top of the stack.
+You can use the stack between successive calls to buffer operations,
+as long as that use is balanced, that is,
+when you call a buffer operation the stack is at the same level
+it was immediately after the previous buffer operation.
+(The only exception to this rule is <a href="#luaL_addvalue"><code>luaL_addvalue</code></a>.)
+After calling <a href="#luaL_pushresult"><code>luaL_pushresult</code></a> the stack is back to its
+level when the buffer was initialized,
+plus the final string on its top.
+
+<p><a name="luaL_buffinit"></a>
+<hr><h3><code>luaL_buffinit</code></h3>
+<pre>
+ void luaL_buffinit (lua_State *L, luaL_Buffer *B);
+</pre>
+
+
+<p>Initializes a buffer <code>B</code>.
+This function does not allocate any space;
+the buffer must be declared as a variable
+(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
+
+<p><a name="luaL_callmeta"></a>
+<hr><h3><code>luaL_callmeta</code></h3>
+<pre>
+ int luaL_callmeta (lua_State *L, int obj, const char *e);
+</pre>
+
+
+<p>Calls a metamethod.
+
+<p>If the object at index <code>obj</code> has a metatable and that
+metatable has a field <code>e</code>,
+calls that field passing the object as argument.
+In that case the function returns 1 and pushes on the
+stack the value returned by the call.
+If there is no metatable or no metamethod returns 0
+(without pushing any value on the stack).
+
+<p><a name="luaL_checkany"></a>
+<hr><h3><code>luaL_checkany</code></h3>
+<pre>
+ void luaL_checkany (lua_State *L, int narg);
+</pre>
+
+
+<p>Checks whether the function has an argument <code>narg</code>.
+
+<p><a name="luaL_checkint"></a>
+<hr><h3><code>luaL_checkint</code></h3>
+<pre>
+ int luaL_checkint (lua_State *L, int narg);
+</pre>
+
+
+<p>Checks whether the function argument <code>narg</code> is a number
+and returns that number casted to an <code>int</code>.
+
+<p><a name="luaL_checkinteger"></a>
+<hr><h3><code>luaL_checkinteger</code></h3>
+<pre>
+ lua_Integer luaL_checkinteger (lua_State *L, int numArg);
+</pre>
+
+
+<p>Checks whether the function argument <code>narg</code> is a number
+and returns that number casted to a <a href="#lua_Integer"><code>lua_Integer</code></a>.
+
+<p><a name="luaL_checklong"></a>
+<hr><h3><code>luaL_checklong</code></h3>
+<pre>
+ long luaL_checklong (lua_State *L, int narg);
+</pre>
+
+
+<p>Checks whether the function argument <code>narg</code> is a number
+and returns that number casted to a <code>long</code>.
+
+<p><a name="luaL_checklstring"></a>
+<hr><h3><code>luaL_checklstring</code></h3>
+<pre>
+ const char *luaL_checklstring (lua_State *L, int numArg, size_t *l);
+</pre>
+
+
+<p>Checks whether the function argument <code>narg</code> is a string
+and returns that string;
+if <code>l</code> is not <code>NULL</code> fills the position <code>*l</code>
+with the string's length.
+
+<p><a name="luaL_checknumber"></a>
+<hr><h3><code>luaL_checknumber</code></h3>
+<pre>
+ lua_Number luaL_checknumber (lua_State *L, int numArg);
+</pre>
+
+
+<p>Checks whether the function argument <code>narg</code> is a number
+and returns that number.
+
+<p><a name="luaL_checkoption"></a>
+<hr><h3><code>luaL_checkoption</code></h3>
+<pre>
+ int luaL_checkoption (lua_State *L, int narg, const char *def,
+ const char *const lst[]);
+</pre>
+
+
+<p>Checks whether the function argument <code>narg</code> is a string and
+searches for that string into the array <code>lst</code>
+(which must be NULL-terminated).
+If <code>def</code> is not <code>NULL</code>,
+uses <code>def</code> as a default value when
+the function has no argument <code>narg</code> or if that argument is <B>nil</B>.
+
+<p>Returns the index in the array where the string was found.
+Raises an error if the argument is not a string or
+if the string cannot be found.
+
+<p><a name="luaL_checkstack"></a>
+<hr><h3><code>luaL_checkstack</code></h3>
+<pre>
+ void luaL_checkstack (lua_State *L, int sz, const char *msg);
+</pre>
+
+
+<p>Grows the stack size to <code>top + sz</code> elements,
+raising an error if the stack cannot grow to that size.
+<code>msg</code> is an additional text to go into the error message.
+
+<p><a name="luaL_checkstring"></a>
+<hr><h3><code>luaL_checkstring</code></h3>
+<pre>
+ const char *luaL_checkstring (lua_State *L, int narg);
+</pre>
+
+
+<p>Checks whether the function argument <code>narg</code> is a string
+and returns that string.
+
+<p><a name="luaL_checktype"></a>
+<hr><h3><code>luaL_checktype</code></h3>
+<pre>
+ void luaL_checktype (lua_State *L, int narg, int t);
+</pre>
+
+
+<p>Checks whether the function argument <code>narg</code> has type <code>t</code>.
+
+<p><a name="luaL_checkudata"></a>
+<hr><h3><code>luaL_checkudata</code></h3>
+<pre>
+ void *luaL_checkudata (lua_State *L, int ud, const char *tname);
+</pre>
+
+
+<p>Checks whether the function argument <code>narg</code> is a userdata
+of the type <code>tname</code> (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
+
+<p><a name="luaL_error"></a>
+<hr><h3><code>luaL_error</code></h3>
+<pre>
+ int luaL_error (lua_State *L, const char *fmt, ...);
+</pre>
+
+
+<p>Raises an error.
+The error message format is given by <code>fmt</code>
+plus any extra argument,
+following the same rules of <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>.
+It also adds at the beginning of the message the file name and
+the line number where the error occurred,
+if that information is available.
+
+<p>This function never returns.
+
+<p><a name="luaL_getmetafield"></a>
+<hr><h3><code>luaL_getmetafield</code></h3>
+<pre>
+ int luaL_getmetafield (lua_State *L, int obj, const char *e);
+</pre>
+
+
+<p>Pushes on the stack the field <code>e</code> from the metatable
+of the object at index <code>obj</code>.
+If the object does not have a metatable,
+or if the metatable does not have that field,
+returns 0 (false) and pushes nothing.
+
+<p><a name="luaL_getmetatable"></a>
+<hr><h3><code>luaL_getmetatable</code></h3>
+<pre>
+ void luaL_getmetatable (lua_State *L, const char *tname);
+</pre>
+
+
+<p>Pushes on the stack the metatable associated to name <code>tname</code>
+in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
+
+<p><a name="luaL_gsub"></a>
+<hr><h3><code>luaL_gsub</code></h3>
+<pre>
+ const char *luaL_gsub (lua_State *L, const char *s,
+ const char *p, const char *r);
+</pre>
+
+
+<p>Creates a copy of string <code>s</code> changing any occurrence of <code>p</code>
+by the string <code>r</code>.
+Pushes the resulting string on the stack and returns it.
+
+<p><a name="luaL_loadbuffer"></a>
+<hr><h3><code>luaL_loadbuffer</code></h3>
+<pre>
+ int luaL_loadbuffer (lua_State *L, const char *buff,
+ size_t sz, const char *name);
+</pre>
+
+
+<p>Loads a buffer as a Lua chunk.
+This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the
+buffer pointed by <code>buff</code> with size <code>sz</code>.
+
+<p>This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
+<code>name</code> is the chunk name,
+used for debug information and error messages.
+
+<p><a name="luaL_loadfile"></a>
+<hr><h3><code>luaL_loadfile</code></h3>
+<pre>
+ int luaL_loadfile (lua_State *L, const char *filename);
+</pre>
+
+
+<p>Loads a file as a Lua chunk.
+This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the file
+named <code>filename</code>.
+If the file's first line starts with a <code>#</code> it is ignored.
+
+<p>This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>,
+but it has an extra error code <code>LUA_ERRFILE</code>
+if it cannot open the file.
+
+<p><a name="luaL_loadstring"></a>
+<hr><h3><code>luaL_loadstring</code></h3>
+<pre>
+ int luaL_loadstring (lua_State *L, const char *s);
+</pre>
+
+
+<p>Loads a string as a Lua chunk.
+This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in
+the zero-terminated string <code>s</code>.
+
+<p>This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
+
+<p><a name="luaL_newmetatable"></a>
+<hr><h3><code>luaL_newmetatable</code></h3>
+<pre>
+ int luaL_newmetatable (lua_State *L, const char *tname);
+</pre>
+
+
+<p>If the register already has the key <code>"tname"</code>,
+returns 0.
+Otherwise,
+creates a new table to be used as metatables for userdata,
+adds it to the register with key <code>"tname"</code>,
+and returns 1.
+
+<p>In both cases pushes on the stack the final value associated
+with <code>"tname"</code> in the registry.
+
+<p><a name="luaL_newstate"></a>
+<hr><h3><code>luaL_newstate</code></h3>
+<pre>
+ lua_State *luaL_newstate (void);
+</pre>
+
+
+<p>Creates a new Lua state, calling <a href="#lua_newstate"><code>lua_newstate</code></a> with an
+allocation function based on the standard C <code>realloc</code> function
+and setting a panic function ((see <a href="#lua_atpanic"><code>lua_atpanic</code></a>)) that prints
+an error message to the standard error output in case of fatal
+errors.
+
+<p>Returns the new state,
+or <code>NULL</code> if there is a memory allocation error.
+
+<p><a name="luaL_optint"></a>
+<hr><h3><code>luaL_optint</code></h3>
+<pre>
+ int luaL_optint (lua_State *L, int narg, int d);
+</pre>
+
+
+<p>If the function argument <code>narg</code> is a number,
+returns that number casted to an <code>int</code>.
+If that argument is absent or is <B>nil</B>,
+returns <code>d</code>.
+Otherwise, raise an error.
+
+<p><a name="luaL_optinteger"></a>
+<hr><h3><code>luaL_optinteger</code></h3>
+<pre>
+ lua_Integer luaL_optinteger (lua_State *L, int nArg, lua_Integer d);
+</pre>
+
+
+<p>If the function argument <code>narg</code> is a number,
+returns that number casted to a <a href="#lua_Integer"><code>lua_Integer</code></a>.
+If that argument is absent or is <B>nil</B>,
+returns <code>d</code>.
+Otherwise, raise an error.
+
+<p><a name="luaL_optlong"></a>
+<hr><h3><code>luaL_optlong</code></h3>
+<pre>
+ long luaL_optlong (lua_State *L, int narg, long d);
+</pre>
+
+
+<p>If the function argument <code>narg</code> is a number,
+returns that number casted to a <code>long</code>.
+If that argument is absent or is <B>nil</B>,
+returns <code>d</code>.
+Otherwise, raise an error.
+
+<p><a name="luaL_optlstring"></a>
+<hr><h3><code>luaL_optlstring</code></h3>
+<pre>
+ const char *luaL_optlstring (lua_State *L, int numArg,
+ const char *d, size_t *l);
+</pre>
+
+
+<p>If the function argument <code>narg</code> is a string,
+returns that string.
+If that argument is absent or is <B>nil</B>,
+returns <code>d</code>.
+Otherwise, raise an error.
+
+<p>If <code>l</code> is not <code>NULL</code> fills the position <code>*l</code>
+with the results's length.
+
+<p><a name="luaL_optnumber"></a>
+<hr><h3><code>luaL_optnumber</code></h3>
+<pre>
+ lua_Number luaL_optnumber (lua_State *L, int nArg, lua_Number d);
+</pre>
+
+
+<p>If the function argument <code>narg</code> is a number,
+returns that number.
+If that argument is absent or is <B>nil</B>,
+returns <code>d</code>.
+Otherwise, raise an error.
+
+<p><a name="luaL_optstring"></a>
+<hr><h3><code>luaL_optstring</code></h3>
+<pre>
+ const char *luaL_optstring (lua_State *L, int narg, const char *d);
+</pre>
+
+
+<p>If the function argument <code>narg</code> is a string,
+returns that string.
+If that argument is absent or is <B>nil</B>,
+returns <code>d</code>.
+Otherwise, raise an error.
+
+<p><a name="luaL_prepbuffer"></a>
+<hr><h3><code>luaL_prepbuffer</code></h3>
+<pre>
+ char *luaL_prepbuffer (luaL_Buffer *B);
+</pre>
+
+
+<p>Returns an address to a space of size <code>LUAL_BUFFERSIZE</code>
+wherein you can copy a string to be added to buffer <code>B</code>
+(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
+After copying the string into that space you must call
+<a href="#luaL_addsize"><code>luaL_addsize</code></a> with the size of the string to actually add
+it to the buffer.
+
+<p><a name="luaL_pushresult"></a>
+<hr><h3><code>luaL_pushresult</code></h3>
+<pre>
+ void luaL_pushresult (luaL_Buffer *B);
+</pre>
+
+
+<p>Finishes the use of buffer <code>B</code> leaving the final string on
+the top of the stack.
+
+<p><a name="luaL_ref"></a>
+<hr><h3><code>luaL_ref</code></h3>
+<pre>
+ int luaL_ref (lua_State *L, int t);
+</pre>
+
+
+<p>Creates and returns a <em>reference</em>,
+in the table at index <code>t</code>,
+for the object at the top of the stack (and pops the object).
+
+<p>A reference is a unique integer key.
+As long as you do not add integer keys into table <code>t</code>,
+<a href="#luaL_ref"><code>luaL_ref</code></a> ensures the uniqueness of the key it returns.
+You can retrieve an object referred by reference <code>r</code>
+calling <code>lua_rawgeti(L, t, r)</code>.
+Function <a href="#luaL_unref"><code>luaL_unref</code></a> frees a reference and its associated object.
+
+<p>Whenever the object at the top of the stack is <B>nil</B>,
+<a href="#luaL_ref"><code>luaL_ref</code></a> returns the same reference <code>LUA_REFNIL</code>.
+The constant <code>LUA_NOREF</code> is garanteed to be different
+from any reference returned by <a href="#luaL_ref"><code>luaL_ref</code></a>.
+
+<p><a name="luaL_Reg"></a>
+<hr><h3><code>luaL_Reg</code></h3>
+<pre>
+ typedef struct luaL_Reg {
+ const char *name;
+ lua_CFunction func;
+ } luaL_Reg;
+
+</pre>
+
+
+<p>Format for arrays of functions to be registered by
+<a href="#luaL_register"><code>luaL_register</code></a>.
+<code>name</code> is the function name and <code>func</code> is a pointer to
+the function.
+Any array of <a href="#luaL_Reg"><code>luaL_Reg</code></a> must end with an sentinel entry
+wherein both <code>name</code> and <code>func</code> are <code>NULL</code>.
+
+<p><a name="luaL_register"></a>
+<hr><h3><code>luaL_register</code></h3>
+<pre>
+ void luaL_register (lua_State *L, const char *libname,
+ const luaL_Reg *l);
+</pre>
+
+
+<p>Opens a library.
+
+<p>When called with <code>libname</code> equal to <code>NULL</code>,
+simply registers all functions in the list <code>l</code>
+(see <a href="#luaL_Reg"><code>luaL_Reg</code></a>) into the table on the top of the stack.
+
+<p>When called with a non-null <code>libname</code>,
+creates a new table <code>t</code>,
+sets it as the value of the variable <code>libname</code>,
+sets it as the value of <code>package.loaded[libname]</code>,
+and registers on it all functions in the list <code>l</code>.
+If there is a table in <code>package.loaded[libname]</code> or in
+variable <code>libname</code>,
+reuses that table instead of creating a new one.
+
+<p>In any case the function leaves the table
+on the top of the stack.
+
+<p><a name="luaL_typename"></a>
+<hr><h3><code>luaL_typename</code></h3>
+<pre>
+ const char *luaL_typename (lua_State *L, int idx);
+</pre>
+
+
+<p>Returns the name of the type of the value at index <code>idx</code>.
+
+<p><a name="luaL_typerror"></a>
+<hr><h3><code>luaL_typerror</code></h3>
+<pre>
+ int luaL_typerror (lua_State *L, int narg, const char *tname);
+</pre>
+
+
+<p>Generates an error with a message like
+<PRE>
+&#060;location>: bad argument &#060;narg> to &#060;function> (&#060;tname> expected, got &#060;realt>)
+</PRE>
+where <code>&#060;location></code> is produced by <a href="#luaL_where"><code>luaL_where</code></a>,
+<code>&#060;function></code> is the name of the current function,
+and <code>&#060;realt></code> is the type name of the actual argument.
+
+<p><a name="luaL_unref"></a>
+<hr><h3><code>luaL_unref</code></h3>
+<pre>
+ void luaL_unref (lua_State *L, int t, int ref);
+</pre>
+
+
+<p>Releases reference <code>ref</code> from the table at index <code>t</code>
+(see <a href="#luaL_ref"><code>luaL_ref</code></a>).
+The entry is removed from the table,
+so that the referred object can be collected.
+The reference <code>ref</code> is also freed to be used again.
+
+<p>If <code>ref</code> is <code>LUA_NOREF</code> or <code>LUA_REFNIL</code>,
+<a href="#luaL_unref"><code>luaL_unref</code></a> does nothing.
+
+<p><a name="luaL_where"></a>
+<hr><h3><code>luaL_where</code></h3>
+<pre>
+ void luaL_where (lua_State *L, int lvl);
+</pre>
+
+
+<p>Pushes on the stack a string identifying the current position
+of the control at level <code>lvl</code> in the call stack.
+Typically this string has the format <code>&#060;chunkname>:&#060;currentline>:</code>.
+Level 0 is the running function,
+level 1 is the function that called the running function.
+
+<p>This function is used to build a prefix for error messages.
+
+<p>
+<a name="libraries"></a><a name="5"></a><h1>5 - Standard Libraries</h1>
+
+<p>The standard libraries provide useful functions
+that are implemented directly through the C API.
+Some of these functions provide essential services to the language
+(e.g., <a href="#pdf-type"><code>type</code></a> and <a href="#pdf-getmetatable"><code>getmetatable</code></a>);
+others provide access to "outside" services (e.g., I/O);
+and others could be implemented in Lua itself,
+but are quite useful or have critical performance to
+deserve an implementation in C (e.g., <code>sort</code>).
+
+<p>All libraries are implemented through the official C API
+and are provided as separate C modules.
+Currently, Lua has the following standard libraries:
+<ul>
+<li> basic library;
+<li> package library;
+<li> string manipulation;
+<li> table manipulation;
+<li> mathematical functions (sin, log, etc.);
+<li> input and output;
+<li> operating system facilities;
+<li> debug facilities.
+</ul>
+Except for the basic and package libraries,
+each library provides all its functions as fields of a global table
+or as methods of its objects.
+
+<p>To have access to these libraries,
+the C host program must first call the function
+<code>luaL_openlibs</code>;
+or else it can open them individually calling
+<code>luaopen_base</code> (for the basic library),
+<code>luaopen_package</code> (for the package library),
+<code>luaopen_string</code> (for the string library),
+<code>luaopen_table</code> (for the table library),
+<code>luaopen_math</code> (for the mathematical library),
+<code>luaopen_io</code> (for the I/O and the Operating System libraries),
+and <code>luaopen_debug</code> (for the debug library).
+These functions are declared in <code>lualib.h</code>.
+
+<p><a name="predefined"></a><a name="5.1"></a><h2>5.1 - Basic Functions</h2>
+
+<p>The basic library provides some core functions to Lua.
+If you do not include this library in your application,
+you should check carefully whether you need to provide some alternative
+implementation for some of its facilities.
+
+<p><a name="pdf-assert"></a><hr><h3><code>assert (v [, message])</code></h3>
+Issues an error when
+the value of its argument <code>v</code> is <B>nil</B> or <B>false</B>;
+otherwise, returns all its arguments.
+<code>message</code> is an error message;
+when absent, it defaults to "assertion failed!"
+
+<p><a name="pdf-collectgarbage"></a><hr><h3><code>collectgarbage (opt [, arg])</code></h3>
+
+<p>This function is a generic interface to the garbage collector.
+It performs different functions according to its first argument, <code>opt</code>:
+<ul>
+<li><b>"stop"</b> stops the garbage collector.
+<li><b>"restart"</b> restarts the garbage collector.
+<li><b>"collect"</b> performs a full garbage-collection cycle.
+<li><b>"count"</b> returns the total memory in use by Lua (in Kbytes).
+<li><b>"step"</b> performs a garbage-collection step.
+The step "size" is controlled by <code>arg</code>
+(larger values mean more steps) in a non-specified way.
+If you want to control the step size
+you must tune experimentally the value of <code>arg</code>.
+<li><b>"steppause"</b>
+sets <em><code>arg</code>/100</em> as the new value for the <em>pause</em> of
+the collector (see <a href="#GC">2.10</a>).
+<li><b>"setstepmul"</b>
+sets <em><code>arg</code>/100</em> as the new value for the <em>step multiplier</em> of
+the collector (see <a href="#GC">2.10</a>).
+</ul>
+
+<p><a name="pdf-dofile"></a><hr><h3><code>dofile (filename)</code></h3>
+Opens the named file and executes its contents as a Lua chunk.
+When called without arguments,
+<a href="#pdf-dofile"><code>dofile</code></a> executes the contents of the standard input (<code>stdin</code>).
+Returns any value returned by the chunk.
+In case of errors, <a href="#pdf-dofile"><code>dofile</code></a> propagates the error
+to its caller (that is, it does not run in protected mode).
+
+<p><a name="pdf-error"></a><hr><h3><code>error (message [, level])</code></h3>
+Terminates the last protected function called
+and returns <code>message</code> as the error message.
+Function <a href="#pdf-error"><code>error</code></a> never returns.
+
+<p>Usually, <a href="#pdf-error"><code>error</code></a> adds some information about the error position
+at the beginning of the message.
+The <code>level</code> argument specifies how to get the error position.
+With level 1 (the default), the error position is where the
+<a href="#pdf-error"><code>error</code></a> function was called.
+Level 2 points the error to where the function
+that called <a href="#pdf-error"><code>error</code></a> was called; and so on.
+Passing a level 0 avoids the addition of error position information
+to the message.
+
+<p><a name="pdf-_G"></a><hr><h3><code>_G</code></h3>
+A global variable (not a function) that
+holds the global environment (that is, <code>_G._G = _G</code>).
+Lua itself does not use this variable;
+changing its value does not affect any environment.
+(Use <a href="#pdf-setfenv"><code>setfenv</code></a> to change environments.)
+
+<p><a name="pdf-getfenv"></a><hr><h3><code>getfenv (f)</code></h3>
+Returns the current environment in use by the function.
+<code>f</code> can be a Lua function or a number,
+which specifies the function at that stack level:
+Level 1 is the function calling <a href="#pdf-getfenv"><code>getfenv</code></a>.
+If the given function is not a Lua function,
+or if <code>f</code> is 0,
+<a href="#pdf-getfenv"><code>getfenv</code></a> returns the global environment.
+The default for <code>f</code> is 1.
+
+<p><a name="pdf-getmetatable"></a><hr><h3><code>getmetatable (object)</code></h3>
+
+<p>If <code>object</code> does not have a metatable, returns <B>nil</B>.
+Otherwise,
+if the object's metatable has a <code>"__metatable"</code> field,
+returns the associated value.
+Otherwise, returns the metatable of the given object.
+
+<p><a name="pdf-ipairs"></a><hr><h3><code>ipairs (t)</code></h3>
+
+<p>Returns an iterator function, the table <code>t</code>, and 0,
+so that the construction
+<PRE>
+ for i,v in ipairs(t) do ... end
+</PRE>
+will iterate over the pairs (<code>1,t[1]</code>), (<code>2,t[2]</code>), ...,
+up to the first integer key with a nil value in the table.
+
+<p><a name="pdf-load"></a><hr><h3><code>load (func [, chunkname])</code></h3>
+
+<p>Loads a chunk using function <code>func</code> to get its pieces.
+Each call to <code>func</code> must return a string that concatenates
+with previous results.
+A return of <B>nil</B> (or no value) signals the end of the chunk.
+
+<p>If there are no errors,
+returns the compiled chunk as a function;
+otherwise, returns <B>nil</B> plus the error message.
+The environment of the returned function is the global environment.
+
+<p><code>chunkname</code> is used as the chunk name for error messages
+and debug information.
+
+<p><a name="pdf-loadfile"></a><hr><h3><code>loadfile (filename)</code></h3>
+
+<p>Similar to <a href="#pdf-load"><code>load</code></a>,
+but gets the chunk from file <code>filename</code>.
+
+<p><a name="pdf-loadstring"></a><hr><h3><code>loadstring (string [, chunkname])</code></h3>
+
+<p>Similar to <a href="#pdf-load"><code>load</code></a>,
+but gets the chunk from the given string.
+
+<p>To load and run a given string, use the idiom
+<PRE>
+ assert(loadstring(s))()
+</PRE>
+
+<p><a name="pdf-next"></a><hr><h3><code>next (table [, index])</code></h3>
+
+<p>Allows a program to traverse all fields of a table.
+Its first argument is a table and its second argument
+is an index in this table.
+<a href="#pdf-next"><code>next</code></a> returns the next index of the table and the
+value associated with the index.
+When called with <B>nil</B> as its second argument,
+<a href="#pdf-next"><code>next</code></a> returns the first index
+of the table and its associated value.
+When called with the last index,
+or with <B>nil</B> in an empty table,
+<a href="#pdf-next"><code>next</code></a> returns <B>nil</B>.
+If the second argument is absent, then it is interpreted as <B>nil</B>.
+
+<p>Lua has no declaration of fields;
+There is no difference between a
+field not present in a table or a field with value <B>nil</B>.
+Therefore, <a href="#pdf-next"><code>next</code></a> only considers fields with non-<B>nil</B> values.
+The order in which the indices are enumerated is not specified,
+<em>even for numeric indices</em>.
+(To traverse a table in numeric order,
+use a numerical <b>for</b> or the <a href="#pdf-ipairs"><code>ipairs</code></a> function.)
+
+<p>The behavior of <a href="#pdf-next"><code>next</code></a> is <em>undefined</em> if,
+during the traversal,
+you assign any value to a non-existent field in the table.
+
+<p><a name="pdf-pairs"></a><hr><h3><code>pairs (t)</code></h3>
+
+<p>Returns the <a href="#pdf-next"><code>next</code></a> function and the table <code>t</code> (plus a <B>nil</B>),
+so that the construction
+<PRE>
+ for k,v in pairs(t) do ... end
+</PRE>
+will iterate over all key&ndash;value pairs of table <code>t</code>.
+
+<p><a name="pdf-pcall"></a><hr><h3><code>pcall (f, arg1, arg2, ...)</code></h3>
+
+<p>Calls function <code>f</code> with
+the given arguments in protected mode.
+That means that any error inside <code>f</code> is not propagated;
+instead, <a href="#pdf-pcall"><code>pcall</code></a> catches the error
+and returns a status code.
+Its first result is the status code (a boolean),
+which is true if the call succeeds without errors.
+In such case, <a href="#pdf-pcall"><code>pcall</code></a> also returns all results from the call,
+after this first result.
+In case of any error, <a href="#pdf-pcall"><code>pcall</code></a> returns <B>false</B> plus the error message.
+
+<p><a name="pdf-print"></a><hr><h3><code>print (e1, e2, ...)</code></h3>
+Receives any number of arguments,
+and prints their values in <code>stdout</code>,
+using the <a href="#pdf-tostring"><code>tostring</code></a> function to convert them to strings.
+This function is not intended for formatted output,
+but only as a quick way to show a value,
+typically for debugging.
+For formatted output, use <code>format</code> (see <a href="#format">5.4</a>).
+
+<p><a name="pdf-rawequal"></a><hr><h3><code>rawequal (v1, v2)</code></h3>
+Checks whether <code>v1</code> is equal to <code>v2</code>,
+without invoking any metamethod.
+Returns a boolean.
+
+<p><a name="pdf-rawget"></a><hr><h3><code>rawget (table, index)</code></h3>
+Gets the real value of <code>table[index]</code>,
+without invoking any metamethod.
+<code>table</code> must be a table;
+<code>index</code> is any value different from <B>nil</B>.
+
+<p><a name="pdf-rawset"></a><hr><h3><code>rawset (table, index, value)</code></h3>
+Sets the real value of <code>table[index]</code> to <code>value</code>,
+without invoking any metamethod.
+<code>table</code> must be a table,
+<code>index</code> is any value different from <B>nil</B>,
+and <code>value</code> is any Lua value.
+
+<p><a name="pdf-select"></a><hr><h3><code>select (index, ...)</code></h3>
+
+<p>If <code>index</code> is a number,
+returns all argument after argument number <code>index</code>.
+Otherwise, <code>index</code> must be the string <code>"#"</code>,
+and <code>select</code> returns the total number of extra arguments it received.
+
+<p><a name="setfenv"></a><a name="pdf-setfenv"></a><hr><h3><code>setfenv (f, table)</code></h3>
+
+<p>Sets the environment to be used by the given function.
+<code>f</code> can be a Lua function or a number,
+which specifies the function at that stack level:
+Level 1 is the function calling <a href="#pdf-setfenv"><code>setfenv</code></a>.
+<a href="#pdf-setfenv"><code>setfenv</code></a> returns the given function.
+
+<p>As a special case, when <code>f</code> is 0 <a href="#pdf-setfenv"><code>setfenv</code></a> changes
+the environment of the running thread.
+In this case, <a href="#pdf-setfenv"><code>setfenv</code></a> returns no values.
+
+<p><a name="pdf-setmetatable"></a><hr><h3><code>setmetatable (table, metatable)</code></h3>
+
+<p>Sets the metatable for the given table.
+(You cannot change the metatable of other types from Lua.)
+If <code>metatable</code> is <B>nil</B>,
+removes the metatable of the given table.
+If the original metatable has a <code>"__metatable"</code> field,
+raises an error.
+
+<p>This function returns <code>table</code>.
+
+<p><a name="pdf-tonumber"></a><hr><h3><code>tonumber (e [, base])</code></h3>
+Tries to convert its argument to a number.
+If the argument is already a number or a string convertible
+to a number, then <a href="#pdf-tonumber"><code>tonumber</code></a> returns that number;
+otherwise, it returns <B>nil</B>.
+
+<p>An optional argument specifies the base to interpret the numeral.
+The base may be any integer between 2 and 36, inclusive.
+In bases above 10, the letter `<code>A</code>&acute; (in either upper or lower case)
+represents 10, `<code>B</code>&acute; represents 11, and so forth,
+with `<code>Z</code>&acute; representing 35.
+In base 10 (the default), the number may have a decimal part,
+as well as an optional exponent part (see <a href="#coercion">2.2.1</a>).
+In other bases, only unsigned integers are accepted.
+
+<p><a name="pdf-tostring"></a><hr><h3><code>tostring (e)</code></h3>
+Receives an argument of any type and
+converts it to a string in a reasonable format.
+For complete control of how numbers are converted,
+use <a href="#pdf-string.format"><code>string.format</code></a> (see <a href="#format">5.4</a>).
+
+<p>If the metatable of <code>e</code> has a <code>"__tostring"</code> field,
+<a href="#pdf-tostring"><code>tostring</code></a> calls the corresponding value
+with <code>e</code> as argument,
+and uses the result of the call as its result.
+
+<p><a name="pdf-type"></a><hr><h3><code>type (v)</code></h3>
+Returns the type of its only argument, coded as a string.
+The possible results of this function are
+<code>"nil"</code> (a string, not the value <B>nil</B>),
+<code>"number"</code>,
+<code>"string"</code>,
+<code>"boolean</code>,
+<code>"table"</code>,
+<code>"function"</code>,
+<code>"thread"</code>,
+and <code>"userdata"</code>.
+
+<p><a name="pdf-unpack"></a><hr><h3><code>unpack (list [, i [, j]])</code></h3>
+Returns the elements from the given list.
+This function is equivalent to
+<PRE>
+ return list[i], list[i+1], ..., list[j]
+</PRE>
+except that the above code can be written only for a fixed number
+of elements.
+By default, <code>i</code> is 1 and <code>j</code> is the length of the list,
+as defined by the length operator.
+
+<p><a name="pdf-_VERSION"></a><hr><h3><code>_VERSION</code></h3>
+A global variable (not a function) that
+holds a string containing the current interpreter version.
+The current contents of this variable is <code>"Lua 5.1"</code>.
+
+<p><a name="pdf-xpcall"></a><hr><h3><code>xpcall (f, err)</code></h3>
+
+<p>This function is similar to <a href="#pdf-pcall"><code>pcall</code></a>,
+except that you can set a new error handler.
+
+<p><a href="#pdf-xpcall"><code>xpcall</code></a> calls function <code>f</code> in protected mode,
+using <code>err</code> as the error handler.
+Any error inside <code>f</code> is not propagated;
+instead, <a href="#pdf-xpcall"><code>xpcall</code></a> catches the error,
+calls the <code>err</code> function with the original error object,
+and returns a status code.
+Its first result is the status code (a boolean),
+which is true if the call succeeds without errors.
+In such case, <a href="#pdf-xpcall"><code>xpcall</code></a> also returns all results from the call,
+after this first result.
+In case of any error,
+<a href="#pdf-xpcall"><code>xpcall</code></a> returns false plus the result from <code>err</code>.
+
+<p><a name="5.2"></a><h2>5.2 - Coroutine Manipulation</h2>
+
+<p>The operations related to coroutines comprise a sub-library of
+the basic library and come inside the table <code>coroutine</code>.
+See <a href="#coroutine">2.11</a> for a general description of coroutines.
+
+<p><a name="pdf-coroutine.create"></a><hr><h3><code>coroutine.create (f)</code></h3>
+
+<p>Creates a new coroutine, with body <code>f</code>.
+<code>f</code> must be a Lua function.
+Returns this new coroutine,
+an object with type <code>"thread"</code>.
+
+<p><a name="pdf-coroutine.resume"></a><hr><h3><code>coroutine.resume (co, val1, ...)</code></h3>
+
+<p>Starts or continues the execution of coroutine <code>co</code>.
+The first time you resume a coroutine,
+it starts running its body.
+The arguments <code>val1</code>, ... go as the arguments to the body function.
+If the coroutine has yielded,
+<code>resume</code> restarts it;
+the arguments <code>val1</code>, ... go as the results from the yield.
+
+<p>If the coroutine runs without any errors,
+<code>resume</code> returns <B>true</B> plus any values passed to <code>yield</code>
+(if the coroutine yields) or any values returned by the body function
+(if the coroutine terminates).
+If there is any error,
+<code>resume</code> returns <B>false</B> plus the error message.
+
+<p><a name="pdf-coroutine.running"></a><hr><h3><code>coroutine.running ()</code></h3>
+
+<p>Returns the running coroutine,
+or <B>nil</B> when called by the main thread.
+
+<p><a name="pdf-coroutine.status"></a><hr><h3><code>coroutine.status (co)</code></h3>
+
+<p>Returns the status of coroutine <code>co</code>, as a string:
+<code>"running"</code>,
+if the coroutine is running (that is, it called <code>status</code>);
+<code>"suspended"</code>, if the coroutine is suspended in a call to <code>yield</code>,
+or if it has not started running yet;
+<code>"normal"</code> if the coroutine is active but not running
+(that is, it has resumed another coroutine);
+and <code>"dead"</code> if the coroutine has finished its body function,
+or if it has stopped with an error.
+
+<p><a name="pdf-coroutine.wrap"></a><hr><h3><code>coroutine.wrap (f)</code></h3>
+
+<p>Creates a new coroutine, with body <code>f</code>.
+<code>f</code> must be a Lua function.
+Returns a function that resumes the coroutine each time it is called.
+Any arguments passed to the function behave as the
+extra arguments to <code>resume</code>.
+Returns the same values returned by <code>resume</code>,
+except the first boolean.
+In case of error, propagates the error.
+
+<p><a name="pdf-coroutine.yield"></a><hr><h3><code>coroutine.yield (val1, ...)</code></h3>
+
+<p>Suspends the execution of the calling coroutine.
+The coroutine cannot be running neither a C function,
+nor a metamethod, nor an iterator.
+Any arguments to <code>yield</code> go as extra results to <code>resume</code>.
+
+<p><a name="5.3"></a><h2>5.3 - Packages and Modules</h2>
+
+<p>The package library provides basic
+facilities for packages and modules in Lua.
+It exports two of its functions directly in the global environment:
+<a href="#pdf-require"><code>require</code></a> and <a href="#pdf-module"><code>module</code></a>.
+Everything else is exported in a table <code>package</code>.
+
+<p><a name="pdf-module"></a><hr><h3><code>module (name [, ...])</code></h3>
+
+<p>Creates a module.
+If there is a table in <code>package.loaded[name]</code>,
+that table is the module.
+Otherwise, if there is a global table <code>t</code> with the given name,
+that table is the module.
+Otherwise creates a new table <code>t</code> and
+sets it as the value of the global <code>name</code> and
+the value of <code>package.loaded[name]</code>.
+This function also initializes <code>t._NAME</code> with the given name,
+<code>t._M</code> with the module (<code>t</code> itself),
+and <code>t._PACKAGE</code> with the package name
+(the full module name minus last component; see below).
+Finally, <code>module</code> sets <code>t</code> as the new environment
+of the current function and the new value of <code>package.loaded[name]</code>,
+so that <a href="#pdf-require"><code>require</code></a> returns <code>t</code>.
+
+<p>If <code>name</code> is a compound name
+(that is, one with components separated by dots)
+<code>module</code> creates (or reuses, if they already exists)
+tables for each component.
+For instance, if <code>name</code> is <code>a.b.c</code>,
+<code>module</code> stores the module table in field <code>c</code> of
+field <code>b</code> of global <code>a</code>.
+
+<p>This function may receive optional <em>options</em> after
+the module name,
+where each option is a function to be applied over the module.
+
+<p><a name="pdf-require"></a><hr><h3><code>require (modname)</code></h3>
+
+<p>Loads the given module.
+The function starts by looking into the table <code>package.loaded</code>
+to determine whether <code>modname</code> is already loaded.
+If it is, then <a href="#pdf-require"><code>require</code></a> returns the value stored
+at <code>package.loaded[modname]</code>.
+Otherwise, it tries to find a loader for that module.
+
+<p>To find a loader,
+first <a href="#pdf-require"><code>require</code></a> queries <code>package.preload[modname]</code>.
+If it is a true value,
+that value (which should be a function) is the loader.
+Otherwise <a href="#pdf-require"><code>require</code></a> searches for a Lua loader using the
+path stored in <code>package.path</code>.
+if that also fails, it searches for a C loader using the
+path stored in <code>package.cpath</code>.
+If that also fails,
+it tries an <em>all-in-one</em> loader.
+
+<p>When loading a C library,
+<a href="#pdf-require"><code>require</code></a> first uses a dynamic link facility to link the
+application with the library.
+Then it tries to find a C function inside that library to
+be used as the loader.
+The name of that C function is the string <code>"luaopen_"</code>
+concatenated with a copy of the module name wherein each dot
+is replaced by an underscore.
+Moreover, if the module name has a colon,
+its prefix up to (and including) the first colon is removed.
+For instance, if the module name is <code>a.v1:b.c</code>,
+the function name will be <code>luaopen_b_c</code>.
+
+<p>If <a href="#pdf-require"><code>require</code></a> finds neither a Lua library nor a
+C library for a module,
+it calls the <em>all-in-one loader</em>.
+That loader searches the C path for a library for
+the root name of the given module.
+For instance, when requiring <code>a.b.c</code>,
+it will search for a C library for <code>a</code>.
+If found, it looks into it for an open function for
+the submodule;
+in our example, that would be <code>luaopen_a_b_c</code>.
+With that facility, a package can pack several C submodules
+into one single library,
+with each submodule keeping its original open function.
+
+<p>Once a loader is found,
+<a href="#pdf-require"><code>require</code></a> calls the loader with a sinle argument, <code>modname</code>.
+If the loader returns any value,
+<a href="#pdf-require"><code>require</code></a> assigns it to <code>package.loaded[modname]</code>.
+If the loader returns no value and
+has not assigned any value to <code>package.loaded[modname]</code>,
+<a href="#pdf-require"><code>require</code></a> assigns <b>true</b> to that entry.
+In any case, require returns the
+final value of <code>package.loaded[modname]</code>.
+
+<p>If there is any error loading or running the module,
+or if it cannot find any loader for that module,
+then <a href="#pdf-require"><code>require</code></a> signals an error.
+
+<p><a name="pdf-package.cpath"></a><hr><h3><code>package.cpath</code></h3>
+
+<p>The path used by <a href="#pdf-require"><code>require</code></a> to search for a C loader.
+
+<p>Lua initializes the C path <code>package.cpath</code> in the same way
+it initializes the Lua path <a href="#pdf-package.path"><code>package.path</code></a>,
+using the environment variable <code>LUA_CPATH</code>
+(plus another compiled-defined default path).
+
+<p><a name="pdf-package.loaded"></a><hr><h3><code>package.loaded</code></h3>
+
+<p>A table used by <a href="#pdf-require"><code>require</code></a> to control which
+modules are already loaded.
+When you require a module <code>modname</code> and
+<code>package.loaded[modname]</code> is not false,
+<a href="#pdf-require"><code>require</code></a> simply returns the value stored there.
+
+<p><a name="pdf-package.loadlib"></a><hr><h3><code>package.loadlib (libname, funcname)</code></h3>
+
+<p>Links the program with the dynamic C library <code>libname</code>.
+Inside this library, looks for a function <code>funcname</code>
+and returns this function as a C function.
+
+<p><code>libname</code> must be the complete file name of the C library,
+including any eventual path and extension.
+
+<p>This function is not supported by ANSI C.
+As such, it is only available on some platforms
+(Windows, Linux, Solaris, BSD, plus other Unix systems that
+support the <code>dlfcn</code> standard).
+
+<p><a name="pdf-package.path"></a><hr><h3><code>package.path</code></h3>
+
+<p>The path used by <a href="#pdf-require"><code>require</code></a> to search for a Lua loader.
+
+<p>At start-up, Lua initializes this variable with
+the value of the environment variable <code>LUA_PATH</code> or
+with a compiled-defined default path,
+if the environment variable is not defined.
+Any <code>";;"</code> in the value of the environment variable
+is replaced by the default path.
+
+<p>A path is a sequence of <em>templates</em> separated by semicolons.
+For each template, <a href="#pdf-require"><code>require</code></a> will change each interrogation
+mark in the template by <code>filename</code>,
+which is <code>modname</code> with each dot replaced by a
+"directory separator" (such as <code>"/"</code> in Unix);
+then it will try to load the resulting file name.
+So, for instance, if the Lua path is
+<PRE>
+ "./?.lua;./?.lc;/usr/local/?/init.lua"
+</PRE>
+the search for a Lua loader for module <code>mod</code>
+will try to load the files
+<code>./mod.lua</code>, <code>./mod.lc</code>, and
+<code>/usr/local/mod/init.lua</code>, in that order.
+
+<p><a name="pdf-package.preload"></a><hr><h3><code>package.preload</code></h3>
+
+<p>A table to store loaders for specific modules
+(see <a href="#pdf-require"><code>require</code></a>).
+
+<p><a name="pdf-package.seeall"></a><hr><h3><code>package.seeall (module)</code></h3>
+
+<p>Sets a metatable for <code>module</code> with
+its <code>__index</code> field refering to the global environment,
+so that this module inherits undefined values
+from the global environment.
+To be used as an option to function <a href="#pdf-module"><code>module</code></a>.
+
+<p><a name="5.4"></a><h2>5.4 - String Manipulation</h2>
+
+<p>This library provides generic functions for string manipulation,
+such as finding and extracting substrings, and pattern matching.
+When indexing a string in Lua, the first character is at position 1
+(not at 0, as in C).
+Indices are allowed to be negative and are interpreted as indexing backwards,
+from the end of the string.
+Thus, the last character is at position <em>-1</em>, and so on.
+
+<p>The string library provides all its functions inside the table
+<code>string</code>.
+It also sets a metatable for strings
+wherein <code>__index</code> points to itself.
+Therefore, you can use the string function is object-oriented style.
+For instance, <code>string.byte(s, i)</code>
+can be written as <code>s:byte(i)</code>.
+
+<p><a name="pdf-string.byte"></a><hr><h3><code>string.byte (s [, i [, j]])</code></h3>
+Returns the internal numerical codes of the characters <code>s[i]</code>,
+<code>s[i+1]</code>, ..., <code>s[j]</code>.
+The default value for <code>i</code> is 1;
+the default value for <code>j</code> is <code>i</code>.
+
+<p>Note that numerical codes are not necessarily portable across platforms.
+
+<p><a name="pdf-string.char"></a><hr><h3><code>string.char (i1, i2, ...)</code></h3>
+Receives 0 or more integers.
+Returns a string with length equal to the number of arguments,
+in which each character has the internal numerical code equal
+to its correspondent argument.
+
+<p>Note that numerical codes are not necessarily portable across platforms.
+
+<p><a name="pdf-string.dump"></a><hr><h3><code>string.dump (function)</code></h3>
+
+<p>Returns a binary representation of the given function,
+so that a later <a href="#pdf-loadstring"><code>loadstring</code></a> on that string returns
+a copy of the function.
+<code>function</code> must be a Lua function.
+
+<p><a name="pdf-string.find"></a><hr><h3><code>string.find (s, pattern [, init [, plain]])</code></h3>
+Looks for the first <em>match</em> of
+<code>pattern</code> in the string <code>s</code>.
+If it finds one, then <code>find</code> returns the indices of <code>s</code>
+where this occurrence starts and ends;
+otherwise, it returns <B>nil</B>.
+A third, optional numerical argument <code>init</code> specifies
+where to start the search;
+its default value is 1 and may be negative.
+A value of <B>true</B> as a fourth, optional argument <code>plain</code>
+turns off the pattern matching facilities,
+so the function does a plain "find substring" operation,
+with no characters in <code>pattern</code> being considered "magic".
+Note that if <code>plain</code> is given, then <code>init</code> must be given too.
+
+<p><a name="format"></a><a name="pdf-string.format"></a><hr><h3><code>string.format (formatstring, e1, e2, ...)</code></h3>
+Returns a formatted version of its variable number of arguments
+following the description given in its first argument (which must be a string).
+The format string follows the same rules as the <code>printf</code> family of
+standard C functions.
+The only differences are that the options/modifiers
+<code>*</code>, <code>l</code>, <code>L</code>, <code>n</code>, <code>p</code>,
+and <code>h</code> are not supported,
+and there is an extra option, <code>q</code>.
+The <code>q</code> option formats a string in a form suitable to be safely read
+back by the Lua interpreter:
+The string is written between double quotes,
+and all double quotes, newlines, and backslashes in the string
+are correctly escaped when written.
+For instance, the call
+<PRE>
+ string.format('%q', 'a string with "quotes" and \n new line')
+</PRE>
+will produce the string:
+<PRE>
+"a string with \"quotes\" and \
+ new line"
+</PRE>
+
+<p>The options <code>c</code>, <code>d</code>, <code>E</code>, <code>e</code>, <code>f</code>,
+<code>g</code>, <code>G</code>, <code>i</code>, <code>o</code>, <code>u</code>, <code>X</code>, and <code>x</code> all
+expect a number as argument,
+whereas <code>q</code> and <code>s</code> expect a string.
+
+<p>This function does not accept string values
+containing embedded zeros.
+
+<p><a name="pdf-string.gmatch"></a><hr><h3><code>string.gmatch (s, pat)</code></h3>
+Returns an iterator function that,
+each time it is called,
+returns the next captures from pattern <code>pat</code> over string <code>s</code>.
+
+<p>If <code>pat</code> specifies no captures,
+then the whole match is produced in each call.
+
+<p>As an example, the following loop
+<PRE>
+ s = "hello world from Lua"
+ for w in string.gmatch(s, "%a+") do
+ print(w)
+ end
+</PRE>
+will iterate over all the words from string <code>s</code>,
+printing one per line.
+The next example collects all pairs <code>key=value</code> from the
+given string into a table:
+<PRE>
+ t = {}
+ s = "from=world, to=Lua"
+ for k, v in string.gmatch(s, "(%w+)=(%w+)") do
+ t[k] = v
+ end
+</PRE>
+
+<p><a name="pdf-string.gsub"></a><hr><h3><code>string.gsub (s, pat, repl [, n])</code></h3>
+Returns a copy of <code>s</code>
+in which all occurrences of the pattern <code>pat</code> have been
+replaced by a replacement string specified by <code>repl</code>.
+<code>gsub</code> also returns, as a second value,
+the total number of substitutions made.
+
+<p>If <code>repl</code> is a string, then its value is used for replacement.
+The character <code>%</code> works as an escape character:
+Any sequence in <code>repl</code> of the form <code>%</code><em>n</em>,
+with <em>n</em> between 1 and 9,
+stands for the value of the <em>n</em>-th captured substring (see below).
+The sequence <code>%0</code> stands for the whole match.
+The sequence <code>%%</code> stands for a single <code>%</code>.
+
+<p>If <code>repl</code> is a function, then this function is called every time a
+match occurs, with all captured substrings passed as arguments,
+in order;
+if the pattern specifies no captures,
+then the whole match is passed as a sole argument.
+If the value returned by this function is a string,
+then it is used as the replacement string;
+otherwise, the replacement string is the empty string.
+
+<p>The optional last parameter <code>n</code> limits
+the maximum number of substitutions to occur.
+For instance, when <code>n</code> is 1 only the first occurrence of
+<code>pat</code> is replaced.
+
+<p>Here are some examples:
+<PRE>
+ x = string.gsub("hello world", "(%w+)", "%1 %1")
+ --> x="hello hello world world"
+
+ x = string.gsub("hello world", "%w+", "%0 %0", 1)
+ --> x="hello hello world"
+
+ x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
+ --> x="world hello Lua from"
+
+ x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
+ --> x="home = /home/roberto, user = roberto"
+
+ x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
+ return loadstring(s)()
+ end)
+ --> x="4+5 = 9"
+
+ local t = {name="lua", version="5.0"}
+ x = string.gsub("$name_$version.tar.gz", "%$(%w+)", function (v)
+ return t[v]
+ end)
+ --> x="lua_5.0.tar.gz"
+</PRE>
+
+<p><a name="pdf-string.len"></a><hr><h3><code>string.len (s)</code></h3>
+Receives a string and returns its length.
+The empty string <code>""</code> has length 0.
+Embedded zeros are counted,
+so <code>"a\000bc\000"</code> has length 5.
+
+<p><a name="pdf-string.lower"></a><hr><h3><code>string.lower (s)</code></h3>
+Receives a string and returns a copy of that string with all
+uppercase letters changed to lowercase.
+All other characters are left unchanged.
+The definition of what is an uppercase letter depends on the current locale.
+
+<p><a name="pdf-string.match"></a><hr><h3><code>string.match (s, pattern [, init])</code></h3>
+Looks for the first <em>match</em> of
+<code>pattern</code> in the string <code>s</code>.
+If it finds one, then <code>match</code> returns
+the captures from the pattern;
+otherwise it returns <B>nil</B>.
+If <code>pattern</code> specifies no captures,
+then the whole match is returned.
+A third, optional numerical argument <code>init</code> specifies
+where to start the search;
+its default value is 1 and may be negative.
+
+<p><a name="pdf-string.rep"></a><hr><h3><code>string.rep (s, n)</code></h3>
+Returns a string that is the concatenation of <code>n</code> copies of
+the string <code>s</code>.
+
+<p><a name="pdf-string.reverse"></a><hr><h3><code>string.reverse (s)</code></h3>
+Returns a string that is the string <code>s</code> reversed.
+
+<p><a name="pdf-string.sub"></a><hr><h3><code>string.sub (s, i [, j])</code></h3>
+Returns the substring of <code>s</code> that
+starts at <code>i</code> and continues until <code>j</code>;
+<code>i</code> and <code>j</code> may be negative.
+If <code>j</code> is absent, then it is assumed to be equal to <em>-1</em>
+(which is the same as the string length).
+In particular,
+the call <code>string.sub(s,1,j)</code> returns a prefix of <code>s</code>
+with length <code>j</code>,
+and <code>string.sub(s, -i)</code> returns a suffix of <code>s</code>
+with length <code>i</code>.
+
+<p><a name="pdf-string.upper"></a><hr><h3><code>string.upper (s)</code></h3>
+Receives a string and returns a copy of that string with all
+lowercase letters changed to uppercase.
+All other characters are left unchanged.
+The definition of what is a lowercase letter depends on the current locale.
+
+<p><a name="pm"></a><h3>Patterns</h3>
+
+<p><p>
+A <em>character class</em> is used to represent a set of characters.
+The following combinations are allowed in describing a character class:
+<ul>
+<li><b><em>x</em></b> (where <em>x</em> is not one of the magic characters
+<code>^$()%.[]*+-?</code>)
+&mdash; represents the character <em>x</em> itself.
+<li><b><code>.</code></b> &mdash; (a dot) represents all characters.
+<li><b><code>%a</code></b> &mdash; represents all letters.
+<li><b><code>%c</code></b> &mdash; represents all control characters.
+<li><b><code>%d</code></b> &mdash; represents all digits.
+<li><b><code>%l</code></b> &mdash; represents all lowercase letters.
+<li><b><code>%p</code></b> &mdash; represents all punctuation characters.
+<li><b><code>%s</code></b> &mdash; represents all space characters.
+<li><b><code>%u</code></b> &mdash; represents all uppercase letters.
+<li><b><code>%w</code></b> &mdash; represents all alphanumeric characters.
+<li><b><code>%x</code></b> &mdash; represents all hexadecimal digits.
+<li><b><code>%z</code></b> &mdash; represents the character with representation 0.
+<li><b><code>%<em>x</em></code></b> (where <em>x</em> is any non-alphanumeric character) &mdash;
+represents the character <em>x</em>.
+This is the standard way to escape the magic characters.
+Any punctuation character (even the non magic)
+can be preceded by a `<code>%</code>&acute;
+when used to represent itself in a pattern.
+
+<p><li><b><code>[<em>set</em>]</code></b> &mdash;
+represents the class which is the union of all
+characters in <em>set</em>.
+A range of characters may be specified by
+separating the end characters of the range with a `<code>-</code>&acute;.
+All classes <code>%</code><em>x</em> described above may also be used as
+components in <em>set</em>.
+All other characters in <em>set</em> represent themselves.
+For example, <code>[%w_]</code> (or <code>[_%w]</code>)
+represents all alphanumeric characters plus the underscore,
+<code>[0-7]</code> represents the octal digits,
+and <code>[0-7%l%-]</code> represents the octal digits plus
+the lowercase letters plus the `<code>-</code>&acute; character.
+
+<p>The interaction between ranges and classes is not defined.
+Therefore, patterns like <code>[%a-z]</code> or <code>[a-%%]</code>
+have no meaning.
+
+<p><li><b><code>[^<em>set</em>]</code></b> &mdash;
+represents the complement of <em>set</em>,
+where <em>set</em> is interpreted as above.
+</ul>
+For all classes represented by single letters (<code>%a</code>, <code>%c</code>, etc.),
+the corresponding uppercase letter represents the complement of the class.
+For instance, <code>%S</code> represents all non-space characters.
+
+<p>The definitions of letter, space, and other character groups
+depend on the current locale.
+In particular, the class <code>[a-z]</code> may not be equivalent to <code>%l</code>.
+
+<p><p>
+A <em>pattern item</em> may be
+<ul>
+<li>
+a single character class,
+which matches any single character in the class;
+<li>
+a single character class followed by `<code>*</code>&acute;,
+which matches 0 or more repetitions of characters in the class.
+These repetition items will always match the longest possible sequence;
+<li>
+a single character class followed by `<code>+</code>&acute;,
+which matches 1 or more repetitions of characters in the class.
+These repetition items will always match the longest possible sequence;
+<li>
+a single character class followed by `<code>-</code>&acute;,
+which also matches 0 or more repetitions of characters in the class.
+Unlike `<code>*</code>&acute;,
+these repetition items will always match the <em>shortest</em> possible sequence;
+<li>
+a single character class followed by `<code>?</code>&acute;,
+which matches 0 or 1 occurrence of a character in the class;
+<li>
+<code>%<em>n</em></code>, for <em>n</em> between 1 and 9;
+such item matches a substring equal to the <em>n</em>-th captured string
+(see below);
+<li>
+<code>%b<em>xy</em></code>, where <em>x</em> and <em>y</em> are two distinct characters;
+such item matches strings that start with <em>x</em>, end with <em>y</em>,
+and where the <em>x</em> and <em>y</em> are <em>balanced</em>.
+This means that, if one reads the string from left to right,
+counting <em>+1</em> for an <em>x</em> and <em>-1</em> for a <em>y</em>,
+the ending <em>y</em> is the first <em>y</em> where the count reaches 0.
+For instance, the item <code>%b()</code> matches expressions with
+balanced parentheses.
+</ul>
+
+<p><p>
+A <em>pattern</em> is a sequence of pattern items.
+A `<code>^</code>&acute; at the beginning of a pattern anchors the match at the
+beginning of the subject string.
+A `<code>$</code>&acute; at the end of a pattern anchors the match at the
+end of the subject string.
+At other positions,
+`<code>^</code>&acute; and `<code>$</code>&acute; have no special meaning and represent themselves.
+
+<p><p>
+A pattern may contain sub-patterns enclosed in parentheses;
+they describe <em>captures</em>.
+When a match succeeds, the substrings of the subject string
+that match captures are stored (<em>captured</em>) for future use.
+Captures are numbered according to their left parentheses.
+For instance, in the pattern <code>"(a*(.)%w(%s*))"</code>,
+the part of the string matching <code>"a*(.)%w(%s*)"</code> is
+stored as the first capture (and therefore has number 1);
+the character matching <code>.</code> is captured with number 2,
+and the part matching <code>%s*</code> has number 3.
+
+<p>As a special case, the empty capture <code>()</code> captures
+the current string position (a number).
+For instance, if we apply the pattern <code>"()aa()"</code> on the
+string <code>"flaaap"</code>, there will be two captures: 3 and 5.
+
+<p>A pattern cannot contain embedded zeros. Use <code>%z</code> instead.
+
+<p><a name="5.5"></a><h2>5.5 - Table Manipulation</h2>
+This library provides generic functions for table manipulation.
+It provides all its functions inside the table <code>table</code>.
+
+<p>Most functions in the table library assume that the table
+represents an array or a list.
+For those functions, when we talk about "the length" of a table
+we mean the result of the length operator.
+
+<p><a name="pdf-table.concat"></a><hr><h3><code>table.concat (table [, sep [, i [, j]]])</code></h3>
+Returns <code>table[i]..sep..table[i+1] ... sep..table[j]</code>.
+The default value for <code>sep</code> is the empty string,
+the default for <code>i</code> is 1,
+and the default for <code>j</code> is the length of the table.
+If <code>i</code> is greater than <code>j</code>, returns the empty string.
+
+<p><a name="pdf-table.sort"></a><hr><h3><code>table.sort (table [, comp])</code></h3>
+Sorts table elements in a given order, <em>in-place</em>,
+from <code>table[1]</code> to <code>table[n]</code>,
+where <code>n</code> is the length of the table.
+If <code>comp</code> is given,
+then it must be a function that receives two table elements,
+and returns true
+when the first is less than the second
+(so that <code>not comp(a[i+1],a[i])</code> will be true after the sort).
+If <code>comp</code> is not given,
+then the standard Lua operator <code>&#060;</code> is used instead.
+
+<p>The sort algorithm is not stable,
+that is, elements considered equal by the given order
+may have their relative positions changed by the sort.
+
+<p><a name="pdf-table.insert"></a><hr><h3><code>table.insert (table, [pos,] value)</code></h3>
+
+<p>Inserts element <code>value</code> at position <code>pos</code> in <code>table</code>,
+shifting up other elements to open space, if necessary.
+The default value for <code>pos</code> is <code>n+1</code>,
+where <code>n</code> is the length of the table (see <a href="#len-op">2.5.5</a>),
+so that a call <code>table.insert(t,x)</code> inserts <code>x</code> at the end
+of table <code>t</code>.
+
+<p><a name="pdf-table.remove"></a><hr><h3><code>table.remove (table [, pos])</code></h3>
+
+<p>Removes from <code>table</code> the element at position <code>pos</code>,
+shifting down other elements to close the space, if necessary.
+Returns the value of the removed element.
+The default value for <code>pos</code> is <code>n</code>,
+where <code>n</code> is the length of the table,
+so that a call <code>table.remove(t)</code> removes the last element
+of table <code>t</code>.
+
+<p><a name="mathlib"></a><a name="5.6"></a><h2>5.6 - Mathematical Functions</h2>
+
+<p>This library is an interface to the standard C math library.
+It provides all its functions inside the table <code>math</code>.
+The library provides the following functions:
+
+
+
+
+
+
+
+<PRE>
+ math.abs math.acos math.asin math.atan math.atan2
+ math.ceil math.cosh math.cos math.deg math.exp
+ math.floor math.fmod math.frexp math.ldexp math.log
+ math.log10 math.max math.min math.modf math.pow
+ math.rad math.random math.randomseed math.sin
+ math.sinh math.sqrt math.tan math.tanh
+</PRE>
+plus a variable <code>math.pi</code> and
+a variable <code>math.huge</code>,
+with the value <code>HUGE_VAL</code>.
+Most of those functions
+are only interfaces to the corresponding functions in the C library.
+All trigonometric functions work in radians.
+The functions <code>math.deg</code> and <code>math.rad</code> convert
+between radians and degrees.
+
+<p>The function <code>math.max</code> returns the maximum
+value of its numeric arguments.
+Similarly, <code>math.min</code> computes the minimum.
+Both can be used with 1, 2, or more arguments.
+
+<p>The function <code>math.modf</code> corresponds to the <code>modf</code> C function.
+It returns two values:
+The integral part and the fractional part of its argument.
+The function <code>math.frexp</code> also returns 2 values:
+The normalized fraction and the exponent of its argument.
+
+<p>The functions <code>math.random</code> and <code>math.randomseed</code>
+are interfaces to the simple random generator functions
+<code>rand</code> and <code>srand</code> that are provided by ANSI C.
+(No guarantees can be given for their statistical properties.)
+When called without arguments,
+<code>math.random</code> returns a pseudo-random real number
+in the range <em>[0,1)</em>.
+When called with a number <em>n</em>,
+<code>math.random</code> returns
+a pseudo-random integer in the range <em>[1,n]</em>.
+When called with two arguments,
+<em>l</em> and <em>u</em>,
+<code>math.random</code> returns a pseudo-random
+integer in the range <em>[l,u]</em>.
+The <code>math.randomseed</code> function sets a "seed"
+for the pseudo-random generator:
+Equal seeds produce equal sequences of numbers.
+
+<p><a name="libio"></a><a name="5.7"></a><h2>5.7 - Input and Output Facilities</h2>
+
+<p>The I/O library provides two different styles for file manipulation.
+The first one uses implicit file descriptors,
+that is, there are operations to set a default input file and a
+default output file,
+and all input/output operations are over those default files.
+The second style uses explicit file descriptors.
+
+<p>When using implicit file descriptors,
+all operations are supplied by table <code>io</code>.
+When using explicit file descriptors,
+the operation <a href="#pdf-io.open"><code>io.open</code></a> returns a file descriptor
+and then all operations are supplied as methods of the file descriptor.
+
+<p>The table <code>io</code> also provides
+three predefined file descriptors with their usual meanings from C:
+<code>io.stdin</code>, <code>io.stdout</code>, and <code>io.stderr</code>.
+
+<p>Unless otherwise stated,
+all I/O functions return <B>nil</B> on failure
+(plus an error message as a second result)
+and some value different from <B>nil</B> on success.
+
+<p><a name="pdf-io.close"></a><hr><h3><code>io.close ([file])</code></h3>
+
+<p>Equivalent to <code>file:close()</code>.
+Without a <code>file</code>, closes the default output file.
+
+<p><a name="pdf-io.flush"></a><hr><h3><code>io.flush ()</code></h3>
+
+<p>Equivalent to <code>file:flush</code> over the default output file.
+
+<p><a name="pdf-io.input"></a><hr><h3><code>io.input ([file])</code></h3>
+
+<p>When called with a file name, it opens the named file (in text mode),
+and sets its handle as the default input file.
+When called with a file handle,
+it simply sets that file handle as the default input file.
+When called without parameters,
+it returns the current default input file.
+
+<p>In case of errors this function raises the error,
+instead of returning an error code.
+
+<p><a name="pdf-io.lines"></a><hr><h3><code>io.lines ([filename])</code></h3>
+
+<p>Opens the given file name in read mode
+and returns an iterator function that,
+each time it is called,
+returns a new line from the file.
+Therefore, the construction
+<PRE>
+ for line in io.lines(filename) do ... end
+</PRE>
+will iterate over all lines of the file.
+When the iterator function detects the end of file,
+it returns <B>nil</B> (to finish the loop) and automatically closes the file.
+
+<p>The call <code>io.lines()</code> (without a file name) is equivalent
+to <code>io.input():lines()</code>, that is, it iterates over the
+lines of the default input file.
+In that case it does not close the file when the loop ends.
+
+<p><a name="pdf-io.open"></a><hr><h3><code>io.open (filename [, mode])</code></h3>
+
+<p>This function opens a file,
+in the mode specified in the string <code>mode</code>.
+It returns a new file handle,
+or, in case of errors, <B>nil</B> plus an error message.
+
+<p>The <code>mode</code> string can be any of the following:
+<ul>
+<li><b>"r"</b> read mode (the default);
+<li><b>"w"</b> write mode;
+<li><b>"a"</b> append mode;
+<li><b>"r+"</b> update mode, all previous data is preserved;
+<li><b>"w+"</b> update mode, all previous data is erased;
+<li><b>"a+"</b> append update mode, previous data is preserved,
+ writing is only allowed at the end of file.
+</ul>
+The <code>mode</code> string may also have a <code>b</code> at the end,
+which is needed in some systems to open the file in binary mode.
+This string is exactly what is used in the
+standard C function <code>fopen</code>.
+
+<p><a name="pdf-io.output"></a><hr><h3><code>io.output ([file])</code></h3>
+
+<p>Similar to <a href="#pdf-io.input"><code>io.input</code></a>, but operates over the default output file.
+
+<p><a name="pdf-io.popen"></a><hr><h3><code>io.popen ([prog [, mode]])</code></h3>
+
+<p>Starts program <code>prog</code> in a separated process and returns
+a file handle that you can use to read data from that program
+(if <code>mode</code> is <code>"r"</code>, the default)
+or to write data to that program
+(if <code>mode</code> is <code>"w"</code>).
+
+<p>This function is system dependent and is not available
+in all platforms.
+
+<p><a name="pdf-io.read"></a><hr><h3><code>io.read (format1, ...)</code></h3>
+
+<p>Equivalent to <code>io.input():read</code>.
+
+<p><a name="pdf-io.tmpfile"></a><hr><h3><code>io.tmpfile ()</code></h3>
+
+<p>Returns a handle for a temporary file.
+This file is open in update mode
+and it is automatically removed when the program ends.
+
+<p><a name="pdf-io.type"></a><hr><h3><code>io.type (obj)</code></h3>
+
+<p>Checks whether <code>obj</code> is a valid file handle.
+Returns the string <code>"file"</code> if <code>obj</code> is an open file handle,
+<code>"closed file"</code> if <code>obj</code> is a closed file handle,
+and <B>nil</B> if <code>obj</code> is not a file handle.
+
+<p><a name="pdf-io.write"></a><hr><h3><code>io.write (value1, ...)</code></h3>
+
+<p>Equivalent to <code>io.output():write</code>.
+
+<p><a name="pdf-file:close"></a><hr><h3><code>file:close ()</code></h3>
+
+<p>Closes <code>file</code>.
+Note that files are automatically closed when garbage collected,
+but that takes an unpredictable time to happen.
+
+<p><a name="flush"></a><a name="pdf-file:flush"></a><hr><h3><code>file:flush ()</code></h3>
+
+<p>Saves any written data to <code>file</code>.
+
+<p><a name="pdf-file:lines"></a><hr><h3><code>file:lines ()</code></h3>
+
+<p>Returns an iterator function that,
+each time it is called,
+returns a new line from the file.
+Therefore, the construction
+<PRE>
+ for line in file:lines() do ... end
+</PRE>
+will iterate over all lines of the file.
+(Unlike <a href="#pdf-io.lines"><code>io.lines</code></a>, this function does not close the file
+when the loop ends.)
+
+<p><a name="pdf-file:read"></a><hr><h3><code>file:read (format1, ...)</code></h3>
+
+<p>Reads the file <code>file</code>,
+according to the given formats, which specify what to read.
+For each format,
+the function returns a string (or a number) with the characters read,
+or <B>nil</B> if it cannot read data with the specified format.
+When called without formats,
+it uses a default format that reads the entire next line
+(see below).
+
+<p>The available formats are
+<ul>
+<li><b>"*n"</b> reads a number;
+this is the only format that returns a number instead of a string.
+<li><b>"*a"</b> reads the whole file, starting at the current position.
+On end of file, it returns the empty string.
+<li><b>"*l"</b> reads the next line (skipping the end of line),
+returning <B>nil</B> on end of file.
+This is the default format.
+<li><b><em>number</em></b> reads a string with up to that number of characters,
+returning <B>nil</B> on end of file.
+If number is zero,
+it reads nothing and returns an empty string,
+or <B>nil</B> on end of file.
+</ul>
+
+<p><a name="pdf-file:seek"></a><hr><h3><code>file:seek ([whence] [, offset])</code></h3>
+
+<p>Sets and gets the file position,
+measured from the beginning of the file,
+to the position given by <code>offset</code> plus a base
+specified by the string <code>whence</code>, as follows:
+<ul>
+<li><b>"set"</b> base is position 0 (beginning of the file);
+<li><b>"cur"</b> base is current position;
+<li><b>"end"</b> base is end of file;
+</ul>
+In case of success, function <code>seek</code> returns the final file position,
+measured in bytes from the beginning of the file.
+If this function fails, it returns <B>nil</B>,
+plus a string describing the error.
+
+<p>The default value for <code>whence</code> is <code>"cur"</code>,
+and for <code>offset</code> is 0.
+Therefore, the call <code>file:seek()</code> returns the current
+file position, without changing it;
+the call <code>file:seek("set")</code> sets the position to the
+beginning of the file (and returns 0);
+and the call <code>file:seek("end")</code> sets the position to the
+end of the file, and returns its size.
+
+<p><a name="pdf-file:setvbuf"></a><hr><h3><code>file:setvbuf (mode [, size])</code></h3>
+
+<p>Sets the buffering mode for an output file.
+There are three available modes:
+<ul>
+<li><b>"no"</b> no buffering; any output operation appear immediately.
+<li><b>"full"</b> full buffering; output operation is performed only
+when the buffer is full (or when you <code>flush</code> the file (see <a href="#flush">5.7</a>)).
+<li><b>"line"</b> line buffering; output is buffered until a newline is
+output or there is any input from some special files
+(such as a terminal device).
+</ul>
+For the last two cases, <code>sizes</code>
+specifies the size of the buffer, in bytes.
+The default is an appropriate size.
+
+<p><a name="pdf-file:write"></a><hr><h3><code>file:write (value1, ...)</code></h3>
+
+<p>Writes the value of each of its arguments to
+the filehandle <code>file</code>.
+The arguments must be strings or numbers.
+To write other values,
+use <a href="#pdf-tostring"><code>tostring</code></a> or <a href="#pdf-string.format"><code>string.format</code></a> before <code>write</code>.
+
+<p><a name="libiosys"></a><a name="5.8"></a><h2>5.8 - Operating System Facilities</h2>
+
+<p>This library is implemented through table <code>os</code>.
+
+<p><a name="pdf-os.clock"></a><hr><h3><code>os.clock ()</code></h3>
+
+<p>Returns an approximation of the amount of CPU time
+used by the program, in seconds.
+
+<p><a name="pdf-os.date"></a><hr><h3><code>os.date ([format [, time]])</code></h3>
+
+<p>Returns a string or a table containing date and time,
+formatted according to the given string <code>format</code>.
+
+<p>If the <code>time</code> argument is present,
+this is the time to be formatted
+(see the <a href="#pdf-os.time"><code>os.time</code></a> function for a description of this value).
+Otherwise, <code>date</code> formats the current time.
+
+<p>If <code>format</code> starts with `<code>!</code>&acute;,
+then the date is formatted in Coordinated Universal Time.
+After that optional character,
+if <code>format</code> is <code>*t</code>,
+then <code>date</code> returns a table with the following fields:
+<code>year</code> (four digits), <code>month</code> (1--12), <code>day</code> (1--31),
+<code>hour</code> (0--23), <code>min</code> (0--59), <code>sec</code> (0--61),
+<code>wday</code> (weekday, Sunday is 1),
+<code>yday</code> (day of the year),
+and <code>isdst</code> (daylight saving flag, a boolean).
+
+<p>If <code>format</code> is not <code>*t</code>,
+then <code>date</code> returns the date as a string,
+formatted according to the same rules as the C function <code>strftime</code>.
+
+<p>When called without arguments,
+<code>date</code> returns a reasonable date and time representation that depends on
+the host system and on the current locale
+(that is, <code>os.date()</code> is equivalent to <code>os.date("%c")</code>).
+
+<p><a name="pdf-os.difftime"></a><hr><h3><code>os.difftime (t2, t1)</code></h3>
+
+<p>Returns the number of seconds from time <code>t1</code> to time <code>t2</code>.
+In Posix, Windows, and some other systems,
+this value is exactly <code>t2</code><em>-</em><code>t1</code>.
+
+<p><a name="pdf-os.execute"></a><hr><h3><code>os.execute (command)</code></h3>
+
+<p>This function is equivalent to the C function <code>system</code>.
+It passes <code>command</code> to be executed by an operating system shell.
+It returns a status code, which is system-dependent.
+
+<p><a name="pdf-os.exit"></a><hr><h3><code>os.exit ([code])</code></h3>
+
+<p>Calls the C function <code>exit</code>,
+with an optional <code>code</code>,
+to terminate the host program.
+The default value for <code>code</code> is the success code.
+
+<p><a name="pdf-os.getenv"></a><hr><h3><code>os.getenv (varname)</code></h3>
+
+<p>Returns the value of the process environment variable <code>varname</code>,
+or <B>nil</B> if the variable is not defined.
+
+<p><a name="pdf-os.remove"></a><hr><h3><code>os.remove (filename)</code></h3>
+
+<p>Deletes the file with the given name.
+If this function fails, it returns <B>nil</B>,
+plus a string describing the error.
+
+<p><a name="pdf-os.rename"></a><hr><h3><code>os.rename (oldname, newname)</code></h3>
+
+<p>Renames file named <code>oldname</code> to <code>newname</code>.
+If this function fails, it returns <B>nil</B>,
+plus a string describing the error.
+
+<p><a name="pdf-os.setlocale"></a><hr><h3><code>os.setlocale (locale [, category])</code></h3>
+
+<p>Sets the current locale of the program.
+<code>locale</code> is a string specifying a locale;
+<code>category</code> is an optional string describing which category to change:
+<code>"all"</code>, <code>"collate"</code>, <code>"ctype"</code>,
+<code>"monetary"</code>, <code>"numeric"</code>, or <code>"time"</code>;
+the default category is <code>"all"</code>.
+The function returns the name of the new locale,
+or <B>nil</B> if the request cannot be honored.
+
+<p><a name="pdf-os.time"></a><hr><h3><code>os.time ([table])</code></h3>
+
+<p>Returns the current time when called without arguments,
+or a time representing the date and time specified by the given table.
+This table must have fields <code>year</code>, <code>month</code>, and <code>day</code>,
+and may have fields <code>hour</code>, <code>min</code>, <code>sec</code>, and <code>isdst</code>
+(for a description of these fields, see the <a href="#pdf-os.date"><code>os.date</code></a> function).
+
+<p>The returned value is a number, whose meaning depends on your system.
+In Posix, Windows, and some other systems, this number counts the number
+of seconds since some given start time (the "epoch").
+In other systems, the meaning is not specified,
+and the number returned by <code>time</code> can be used only as an argument to
+<code>date</code> and <code>difftime</code>.
+
+<p><a name="pdf-os.tmpname"></a><hr><h3><code>os.tmpname ()</code></h3>
+
+<p>Returns a string with a file name that can
+be used for a temporary file.
+The file must be explicitly opened before its use
+and removed when no longer needed.
+
+<p><a name="libdebug"></a><a name="5.9"></a><h2>5.9 - The Reflexive Debug Interface</h2>
+
+<p>The <em>debug library</em> provides
+the functionality of the debug interface to Lua programs.
+You should exert care when using this library.
+The functions provided here should be used exclusively for debugging
+and similar tasks, such as profiling.
+Please resist the temptation to use them as a
+usual programming tool:
+They can be very slow.
+Moreover, several of its functions
+violate some assumptions about Lua code
+(e.g., that local variables cannot be accessed from outside or
+that userdata metatables cannot be changed by Lua code)
+and therefore can compromise some otherwise secure code.
+
+<p>All functions in this library are provided
+inside a <code>debug</code> table.
+
+<p><a name="pdf-debug.debug"></a><hr><h3><code>debug.debug ()</code></h3>
+
+<p>Enters an interactive mode with the user,
+running each string that the user enters.
+Using simple commands and other debug facilities,
+the user can inspect global and local variables,
+change their values, evaluate expressions, and so on.
+A line containing only the word <code>cont</code> finishes this function,
+so that the caller continues its execution.
+
+<p>Note that commands for <a href="#pdf-debug.debug"><code>debug.debug</code></a> are not lexically nested
+with any function, so they have no direct access to local variables.
+
+<p><a name="pdf-debug.getfenv"></a><hr><h3><code>debug.getfenv (o)</code></h3>
+Returns the environment of object <code>o</code>.
+
+<p><a name="pdf-debug.gethook"></a><hr><h3><code>debug.gethook ()</code></h3>
+
+<p>Returns the current hook settings, as three values:
+the current hook function, the current hook mask,
+and the current hook count
+(as set by the <a href="#pdf-debug.sethook"><code>debug.sethook</code></a> function).
+
+<p><a name="pdf-debug.getinfo"></a><hr><h3><code>debug.getinfo (function [, what])</code></h3>
+
+<p>This function returns a table with information about a function.
+You can give the function directly,
+or you can give a number as the value of <code>function</code>,
+which means the function running at level <code>function</code> of the call stack:
+Level 0 is the current function (<code>getinfo</code> itself);
+level 1 is the function that called <code>getinfo</code>;
+and so on.
+If <code>function</code> is a number larger than the number of active functions,
+then <code>getinfo</code> returns <B>nil</B>.
+
+<p>The returned table contains all the fields returned by <a href="#lua_getinfo"><code>lua_getinfo</code></a>,
+with the string <code>what</code> describing which fields to fill in.
+The default for <code>what</code> is to get all information available.
+If present,
+the option `<code>f</code>&acute;
+adds a field named <code>func</code> with the function itself.
+
+<p>For instance, the expression <code>debug.getinfo(1,"n").name</code> returns
+the name of the current function, if a reasonable name can be found,
+and <code>debug.getinfo(print)</code> returns a table with all available information
+about the <a href="#pdf-print"><code>print</code></a> function.
+
+<p><a name="pdf-debug.getlocal"></a><hr><h3><code>debug.getlocal (level, local)</code></h3>
+
+<p>This function returns the name and the value of the local variable
+with index <code>local</code> of the function at level <code>level</code> of the stack.
+(The first parameter or local variable has index 1, and so on,
+until the last active local variable.)
+The function returns <B>nil</B> if there is no local
+variable with the given index,
+and raises an error when called with a <code>level</code> out of range.
+(You can call <a href="#pdf-debug.getinfo"><code>debug.getinfo</code></a> to check whether the level is valid.)
+
+<p><a name="pdf-debug.getmetatable"></a><hr><h3><code>debug.getmetatable (object)</code></h3>
+
+<p>If <code>object</code> does not have a metatable, returns <B>nil</B>.
+Otherwise, returns the metatable of the given object.
+
+<p><a name="pdf-debug.getupvalue"></a><hr><h3><code>debug.getupvalue (func, up)</code></h3>
+
+<p>This function returns the name and the value of the upvalue
+with index <code>up</code> of the function <code>func</code>.
+The function returns <B>nil</B> if there is no upvalue with the given index.
+
+<p><a name="pdf-debug.setfenv"></a><hr><h3><code>debug.setfenv (o, table)</code></h3>
+
+<p>Sets the environment of the given object.
+
+<p><a name="pdf-debug.sethook"></a><hr><h3><code>debug.sethook (hook, mask [, count])</code></h3>
+
+<p>Sets the given function as a hook.
+The string <code>mask</code> and the number <code>count</code> describe
+when the hook will be called.
+The string mask may have the following characters,
+with the given meaning:
+<ul>
+<li><b><code>"c"</code></b> The hook is called every time Lua calls a function;
+<li><b><code>"r"</code></b> The hook is called every time Lua returns from a function;
+<li><b><code>"l"</code></b> The hook is called every time Lua enters a new line of code.
+</ul>
+With a <code>count</code> different from zero,
+the hook is called after every <code>count</code> instructions.
+
+<p>When called without arguments,
+the <a href="#pdf-debug.sethook"><code>debug.sethook</code></a> function turns off the hook.
+
+<p>When the hook is called, its first parameter is always a string
+describing the event that triggered its call:
+<code>"call"</code>, <code>"return"</code> (or <code>"tail return"</code>),
+<code>"line"</code>, and <code>"count"</code>.
+Moreover, for line events,
+it also gets as its second parameter the new line number.
+Inside a hook,
+you can call <code>getinfo</code> with level 2 to get more information about
+the running function
+(level 0 is the <code>getinfo</code> function,
+and level 1 is the hook function),
+unless the event is <code>"tail return"</code>.
+In this case, Lua is only simulating the return,
+and a call to <code>getinfo</code> will return invalid data.
+
+<p><a name="pdf-debug.setlocal"></a><hr><h3><code>debug.setlocal (level, local, value)</code></h3>
+
+<p>This function assigns the value <code>value</code> to the local variable
+with index <code>local</code> of the function at level <code>level</code> of the stack.
+The function returns <B>nil</B> if there is no local
+variable with the given index,
+and raises an error when called with a <code>level</code> out of range.
+(You can call <code>getinfo</code> to check whether the level is valid.)
+Otherwise, it returns the name of the local variable.
+
+<p><a name="pdf-debug.setmetatable"></a><hr><h3><code>debug.setmetatable (o, metatable)</code></h3>
+
+<p>Sets the metatable for the given object.
+
+<p><a name="pdf-debug.setupvalue"></a><hr><h3><code>debug.setupvalue (func, up, value)</code></h3>
+
+<p>This function assigns the value <code>value</code> to the upvalue
+with index <code>up</code> of the function <code>func</code>.
+The function returns <B>nil</B> if there is no upvalue
+with the given index.
+Otherwise, it returns the name of the upvalue.
+
+<p><a name="pdf-debug.traceback"></a><hr><h3><code>debug.traceback ([message])</code></h3>
+
+<p>Returns a string with a traceback of the call stack.
+An optional <code>message</code> string is appended
+at the beginning of the traceback.
+This function is typically used with <a href="#pdf-xpcall"><code>xpcall</code></a> to produce
+better error messages.
+
+<p>
+<a name="lua-sa"></a><a name="6"></a><h1>6 - Lua Stand-alone</h1>
+
+<p>Although Lua has been designed as an extension language,
+to be embedded in a host C program,
+it is also frequently used as a stand-alone language.
+An interpreter for Lua as a stand-alone language,
+called simply <code>lua</code>,
+is provided with the standard distribution.
+The stand-alone interpreter includes
+all standard libraries plus the reflexive debug interface.
+Its usage is:
+<PRE>
+ lua [options] [script [args]]
+</PRE>
+The options are:
+<ul>
+<li><b><code>-</code> </b> executes <code>stdin</code> as a file;
+<li><b><code>-e</code> <em>stat</em></b> executes string <em>stat</em>;
+<li><b><code>-l</code> <em>mod</em></b> "requires" <em>mod</em>;
+<li><b><code>-i</code></b> enters interactive mode after running <em>script</em>;
+<li><b><code>-v</code></b> prints version information;
+<li><b><code>--</code></b> stop handling options.
+</ul>
+After handling its options, <code>lua</code> runs the given <em>script</em>,
+passing to it the given <em>args</em>.
+When called without arguments,
+<code>lua</code> behaves as <code>lua -v -i</code> when <code>stdin</code> is a terminal,
+and as <code>lua -</code> otherwise.
+
+<p>Before running any argument,
+the interpreter checks for an environment variable <code>LUA_INIT</code>.
+If its format is @<em>filename</em>,
+then lua executes the file.
+Otherwise, lua executes the string itself.
+
+<p>All options are handled in order, except <code>-i</code>.
+For instance, an invocation like
+<PRE>
+ $ lua -e'a=1' -e 'print(a)' script.lua
+</PRE>
+will first set <code>a</code> to 1, then print <code>a</code>,
+and finally run the file <code>script.lua</code>.
+(Here <code>$</code> is the shell prompt. Your prompt may be different.)
+
+<p>Before starting to run the script,
+<code>lua</code> collects all arguments in the command line
+in a global table called <code>arg</code>.
+The script name is stored in index 0,
+the first argument after the script name goes to index 1,
+and so on.
+Any arguments before the script name
+(that is, the interpreter name plus the options)
+go to negative indices.
+For instance, in the call
+<PRE>
+ $ lua -la.lua b.lua t1 t2
+</PRE>
+the interpreter first runs the file <code>a.lua</code>,
+then creates a table
+<PRE>
+ arg = { [-2] = "lua", [-1] = "-la.lua", [0] = "b.lua",
+ [1] = "t1", [2] = "t2" }
+</PRE>
+and finally runs the file <code>b.lua</code>.
+The script is called with <code>arg[1]</code>, <code>arg[2]</code>, ...
+as arguments;
+it can access those arguments with the vararg expression <code>...</code>.
+
+<p>In interactive mode,
+if you write an incomplete statement,
+the interpreter waits for its completion.
+
+<p>If the global variable <code>_PROMPT</code> is defined as a string,
+then its value is used as the prompt.
+Therefore, the prompt can be changed directly on the command line:
+<PRE>
+ $ lua -e"_PROMPT='myprompt> '" -i
+</PRE>
+(the outer pair of quotes is for the shell,
+the inner is for Lua),
+or in any Lua programs by assigning to <code>_PROMPT</code>.
+Note the use of <code>-i</code> to enter interactive mode; otherwise,
+the program would end just after the assignment to <code>_PROMPT</code>.
+
+<p>To allow the use of Lua as a
+script interpreter in Unix systems,
+the stand-alone interpreter skips
+the first line of a chunk if it starts with <code>#</code>.
+Therefore, Lua scripts can be made into executable programs
+by using <code>chmod +x</code> and the <code>#!</code> form,
+as in
+<PRE>
+#!/usr/local/bin/lua
+</PRE>
+(Of course,
+the location of the Lua interpreter may be different in your machine.
+If <code>lua</code> is in your <code>PATH</code>,
+then
+<PRE>
+#!/usr/bin/env lua
+</PRE>
+is a more portable solution.)
+
+<p><hr>
+
+<p><h1>Incompatibilities with Previous Version</h1>
+
+
+<p>Here we list the incompatibilities when moving a program
+from Lua 5.0 to Lua 5.1.
+You can avoid most of the incompatibilities compiling Lua with
+appropriate options.
+However,
+all those compatibility options will be removed in the next version.
+
+<p><h2>Incompatibilities with version 5.0</h2>
+
+<p><h3>Changes in the Language</h3>
+<ul>
+<li>
+The vararg system changed from the pseudo-argument <code>arg</code> with a
+table with the extra arguments to the vararg expression.
+(Option <code>LUA_COMPAT_VARARG</code>)
+
+<p><li>
+There was a subtle change in the scope of the implicit
+variables of the <b>for</b> constructor.
+
+<p><li>
+The long string/long comment syntax (<code>[[...]]</code>) does not allow nesting.
+You can use the new syntax (<code>[=[...]=]</code>) in those cases.
+(Option <code>LUA_COMPAT_LSTR</code>)
+
+<p></ul>
+
+<p><h3>Changes in the Libraries</h3>
+<ul>
+<li>
+Function <a href="#pdf-string.find"><code>string.find</code></a> does not return its captures.
+Use <a href="#pdf-string.match"><code>string.match</code></a> for that.
+(Option <code>LUA_COMPAT_FIND</code>)
+
+<p><li>
+Function <code>string.gfind</code> was renamed <a href="#pdf-string.gmatch"><code>string.gmatch</code></a>.
+(Option <code>LUA_COMPAT_GFIND</code>)
+
+<p><li>
+Function <code>table.setn</code> was deprecated.
+Function <code>table.getn</code> corresponds
+to the new length operator (<code>#</code>);
+use the operator instead of the function.
+(Option <code>LUA_COMPAT_GETN</code>)
+
+<p><li>
+Function <code>loadlib</code> was renamed <a href="#pdf-package.loadlib"><code>package.loadlib</code></a>.
+(Option <code>LUA_COMPAT_LOADLIB</code>)
+
+<p><li>
+Function <code>math.mod</code> was renamed <a href="#pdf-math.fmod"><code>math.fmod</code></a>.
+(Option <code>LUA_COMPAT_MOD</code>)
+
+<p><li>
+There was substantial changes in function <a href="#pdf-require"><code>require</code></a> due to
+the new module system.
+However, the new behavior is mostly compatible with the old,
+but it gets the path from <a href="#pdf-package.path"><code>package.path</code></a> instead
+of from <code>LUA_PATH</code>.
+
+<p><li>
+Function <a href="#pdf-collectgarbage"><code>collectgarbage</code></a> has different arguments.
+Function <code>gcinfo</code> is deprecated;
+use <code>collectgarbage("count")</code> instead.
+
+<p></ul>
+
+<p><h3>Changes in the API</h3>
+<ul>
+<li>
+Function <code>lua_open</code> was replaced by <a href="#lua_newstate"><code>lua_newstate</code></a> to
+allow the user to set an allocation function.
+You can use <a href="#luaL_newstate"><code>luaL_newstate</code></a> from the standard library to
+create a state with a standard allocation function
+(based on <code>realloc</code>).
+
+<p><li>
+Functions <code>luaL_getn</code> and <code>luaL_setn</code>
+(from the auxiliary library) are deprecated.
+Use <a href="#lua_objlen"><code>lua_objlen</code></a> instead of <code>luaL_getn</code>
+and nothing instead of <code>luaL_setn</code>.
+
+<p><li>
+Function <code>luaL_openlib</code> was replaced by <a href="#luaL_register"><code>luaL_register</code></a>.
+
+<p></ul>
+
+<p>
+
+<a name="BNF"></a><h1>The Complete Syntax of Lua</h1>
+
+
+<p>
+
+<p><pre>
+
+<p> chunk ::= {stat [`<b>;</b>&acute;]}
+
+<p> block ::= chunk
+
+<p> stat ::= varlist1 `<b>=</b>&acute; explist1 | functioncall | <b>do</b> block <b>end</b> | <b>while</b> exp <b>do</b> block <b>end</b> | <b>repeat</b> block <b>until</b> exp | <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b> | <b>return</b> [explist1] | <b>break</b> | <b>for</b> Name `<b>=</b>&acute; exp `<b>,</b>&acute; exp [`<b>,</b>&acute; exp] <b>do</b> block <b>end</b> | <b>for</b> namelist <b>in</b> explist1 <b>do</b> block <b>end</b> | <b>function</b> funcname funcbody | <b>local</b> <b>function</b> Name funcbody | <b>local</b> namelist [init]
+
+<p> funcname ::= Name {`<b>.</b>&acute; Name} [`<b>:</b>&acute; Name]
+
+<p> varlist1 ::= var {`<b>,</b>&acute; var}
+
+<p> var ::= Name | prefixexp `<b>[</b>&acute; exp `<b>]</b>&acute; | prefixexp `<b>.</b>&acute; Name
+
+<p> namelist ::= Name {`<b>,</b>&acute; Name}
+
+<p> init ::= `<b>=</b>&acute; explist1
+
+<p> explist1 ::= {exp `<b>,</b>&acute;} exp
+
+<p> exp ::= <b>nil</b> | <b>false</b> | <b>true</b> | Number | Literal | `<b>...</b>&acute; | function | prefixexp | tableconstructor | exp binop exp | unop exp
+
+<p> prefixexp ::= var | functioncall | `<b>(</b>&acute; exp `<b>)</b>&acute;
+
+<p> functioncall ::= prefixexp args | prefixexp `<b>:</b>&acute; Name args
+
+<p> args ::= `<b>(</b>&acute; [explist1] `<b>)</b>&acute; | tableconstructor | Literal
+
+<p> function ::= <b>function</b> funcbody
+
+<p> funcbody ::= `<b>(</b>&acute; [parlist1] `<b>)</b>&acute; block <b>end</b>
+
+<p> parlist1 ::= namelist [`<b>,</b>&acute; `<b>...</b>&acute;] | `<b>...</b>&acute;
+
+<p> tableconstructor ::= `<b>{</b>&acute; [fieldlist] `<b>}</b>&acute;
+ fieldlist ::= field {fieldsep field} [fieldsep]
+ field ::= `<b>[</b>&acute; exp `<b>]</b>&acute; `<b>=</b>&acute; exp | name `<b>=</b>&acute; exp | exp
+ fieldsep ::= `<b>,</b>&acute; | `<b>;</b>&acute;
+
+<p> binop ::= `<b>+</b>&acute; | `<b>-</b>&acute; | `<b>*</b>&acute; | `<b>/</b>&acute; | `<b>^</b>&acute; | `<b>%</b>&acute; | `<b>..</b>&acute; | `<b>&#060;</b>&acute; | `<b>&#060;=</b>&acute; | `<b>></b>&acute; | `<b>>=</b>&acute; | `<b>==</b>&acute; | `<b>~=</b>&acute; | <b>and</b> | <b>or</b>
+
+<p> unop ::= `<b>-</b>&acute; | <b>not</b> | `<b>#</b>&acute;
+
+<p></pre>
+
+<p>
+
+<p>
+
+<HR>
+<SMALL>
+Last update:
+Wed Sep 7 13:53:49 BRT 2005
+</SMALL>
+
+</body></html>
diff --git a/doc/readme.html b/doc/readme.html
index 2eab9202..db20a69a 100644
--- a/doc/readme.html
+++ b/doc/readme.html
@@ -1,6 +1,7 @@
<HTML>
<HEAD>
<TITLE>Lua documentation</TITLE>
+<LINK REL="stylesheet" TYPE="text/css" HREF="lua.css">
</HEAD>
<BODY BGCOLOR="#FFFFFF">
@@ -24,7 +25,7 @@ Documentation
<HR>
<SMALL>
Last update:
-Wed Dec 22 13:55:42 BRST 2004
+Wed Sep 7 12:57:50 BRST 2005
</SMALL>
</BODY>
diff --git a/etc/Makefile b/etc/Makefile
index fc3d1468..2dfc937c 100644
--- a/etc/Makefile
+++ b/etc/Makefile
@@ -14,13 +14,12 @@ MYLDFLAGS= -Wl,-E
MYLIBS= -lm -ldl
RM= rm -f
-ALL= min noparser.o 1
-
all:
- @echo 'choose a target:' $(ALL)
+ @echo 'choose a target: min noparser one clean'
min: min.c
- $(CC) $(CFLAGS) -o $@ $@.c -L$(LIB) -llua $(MYLIBS)
+ $(CC) $(CFLAGS) $@.c -L$(LIB) -llua $(MYLIBS)
+ echo 'print"Hello there!"' | ./a.out
noparser: noparser.o
$(CC) noparser.o $(SRC)/lua.o -L$(LIB) -llua $(MYLIBS)
@@ -28,9 +27,9 @@ noparser: noparser.o
-./a.out luac.out
-./a.out -e'a=1'
-1:
+one:
$(CC) $(CFLAGS) all.c $(MYLIBS)
./a.out $(TST)/hello.lua
clean:
- $(RM) $(ALL) a.out core core.* *.o luac.out
+ $(RM) noparser.o a.out core core.* *.o luac.out
diff --git a/etc/README b/etc/README
index 47626769..5e42ec56 100644
--- a/etc/README
+++ b/etc/README
@@ -3,19 +3,21 @@ Unlike the code in ../src, everything here is in the public domain.
all.c
Full Lua interpreter in a single file.
- Do "make 1".
+ Do "make one".
lua.hpp
- Lua header files for C++.
- This keeps the C interface to Lua. But Lua also compiles as clean C++.
+ Lua header files for C++ using 'extern "C"'.
lua.ico
- A Lua icon for Windows (and web sites, as favicon.ico).
+ A Lua icon for Windows (and web sites: save as favicon.ico).
Drawn by hand by Markus Gritsch <gritsch@iue.tuwien.ac.at>.
lua.pc
pkg-config data for Lua
+luavs.bat
+ Script to build Lua under "Visual Studio .NET Command Prompt".
+
min.c
A minimal Lua interpreter.
Good for learning and for starting your own.
@@ -23,3 +25,7 @@ min.c
noparser.c
Linking with noparser.o avoids loading the parsing modules in lualib.a.
Do "make noparser" to see a demo.
+
+strict.lua
+ Traps uses of undeclared global variables.
+
diff --git a/etc/luavs.bat b/etc/luavs.bat
new file mode 100644
index 00000000..eea175e3
--- /dev/null
+++ b/etc/luavs.bat
@@ -0,0 +1,7 @@
+cd src
+cl /O2 /W3 /c /DLUA_BUILD_AS_DLL l*.c
+del lua.obj luac.obj
+link /DLL /out:lua51.dll l*.obj
+cl /O2 /W3 /c /DLUA_BUILD_AS_DLL lua.c
+link /out:lua.exe lua.obj lua51.lib
+cd ..
diff --git a/etc/noparser.c b/etc/noparser.c
index 9396ad60..13ba5462 100644
--- a/etc/noparser.c
+++ b/etc/noparser.c
@@ -18,13 +18,14 @@
#include "lparser.h"
#include "lzio.h"
-void luaX_init (lua_State *L) {
+LUAI_FUNC void luaX_init (lua_State *L) {
UNUSED(L);
}
-Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, const char *name) {
+LUAI_FUNC Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, const char *name) {
UNUSED(z);
UNUSED(buff);
+ UNUSED(name);
lua_pushliteral(L,"parser not loaded");
lua_error(L);
return NULL;
@@ -33,10 +34,17 @@ Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, const char *name) {
#ifdef NODUMP
#include "lundump.h"
-int luaU_dump (lua_State* L, const Proto* Main, lua_Chunkwriter w, void* data, int strip)
-{
- return 0;
- lua_pushliteral(L,"dumper not loaded");
- lua_error(L);
+LUAI_FUNC int luaU_dump (lua_State* L, const Proto* f, lua_Writer w, void* data, int strip) {
+ UNUSED(f);
+ UNUSED(w);
+ UNUSED(data);
+ UNUSED(strip);
+#if 1
+ UNUSED(L);
+ return 0;
+#else
+ lua_pushliteral(L,"dumper not loaded");
+ lua_error(L);
+#endif
}
#endif
diff --git a/etc/strict.lua b/etc/strict.lua
new file mode 100644
index 00000000..7c9fa159
--- /dev/null
+++ b/etc/strict.lua
@@ -0,0 +1,34 @@
+--
+-- strict.lua
+-- checks uses of undeclared global variables
+-- All global variables must be 'declared' through a regular assignment
+-- (even assigning nil will do) in a main chunk before being used
+-- anywhere or assigned to inside a function.
+--
+
+local mt = getmetatable(_G)
+if mt == nil then
+ mt = {}
+ setmetatable(_G, mt)
+end
+
+mt.__declared = {}
+
+mt.__newindex = function (t, n, v)
+ if not mt.__declared[n] then
+ local w = debug.getinfo(2, "S").what
+ if w ~= "main" and w ~= "C" then
+ error("assign to undeclared variable '"..n.."'", 2)
+ end
+ mt.__declared[n] = true
+ end
+ rawset(t, n, v)
+end
+
+mt.__index = function (t, n)
+ if not mt.__declared[n] and debug.getinfo(2, "S").what ~= "C" then
+ error("variable '"..n.."' is not declared", 2)
+ end
+ return rawget(t, n)
+end
+
diff --git a/src/lapi.c b/src/lapi.c
index 1fe7916a..b85e1dc5 100644
--- a/src/lapi.c
+++ b/src/lapi.c
@@ -1,5 +1,5 @@
/*
-** $Id: lapi.c,v 2.41 2005/05/17 19:49:15 roberto Exp $
+** $Id: lapi.c,v 2.48 2005/09/01 17:42:22 roberto Exp $
** Lua API
** See Copyright Notice in lua.h
*/
@@ -113,11 +113,11 @@ LUA_API void lua_xmove (lua_State *from, lua_State *to, int n) {
if (from == to) return;
lua_lock(to);
api_checknelems(from, n);
- api_check(L, G(from) == G(to));
+ api_check(from, G(from) == G(to));
+ api_check(from, to->ci->top - to->top >= n);
from->top -= n;
for (i = 0; i < n; i++) {
- setobj2s(to, to->top, from->top + i);
- api_incr_top(to);
+ setobj2s(to, to->top++, from->top + i);
}
lua_unlock(to);
}
@@ -153,7 +153,7 @@ LUA_API lua_State *lua_newthread (lua_State *L) {
LUA_API int lua_gettop (lua_State *L) {
- return (L->top - L->base);
+ return cast(int, L->top - L->base);
}
@@ -344,6 +344,7 @@ LUA_API const char *lua_tolstring (lua_State *L, int idx, size_t *len) {
return NULL;
}
luaC_checkGC(L);
+ o = index2adr(L, idx); /* previous call may reallocate the stack */
lua_unlock(L);
}
if (len != NULL) *len = tsvalue(o)->len;
@@ -351,7 +352,7 @@ LUA_API const char *lua_tolstring (lua_State *L, int idx, size_t *len) {
}
-LUA_API size_t lua_objsize (lua_State *L, int idx) {
+LUA_API size_t lua_objlen (lua_State *L, int idx) {
StkId o = index2adr(L, idx);
switch (ttype(o)) {
case LUA_TSTRING: return tsvalue(o)->len;
@@ -618,6 +619,9 @@ LUA_API void lua_getfenv (lua_State *L, int idx) {
case LUA_TUSERDATA:
sethvalue(L, L->top, uvalue(o)->env);
break;
+ case LUA_TTHREAD:
+ setobj2s(L, L->top, gt(thvalue(o)));
+ break;
default:
setnilvalue(L->top);
break;
@@ -736,6 +740,9 @@ LUA_API int lua_setfenv (lua_State *L, int idx) {
case LUA_TUSERDATA:
uvalue(o)->env = hvalue(L->top - 1);
break;
+ case LUA_TTHREAD:
+ sethvalue(L, gt(thvalue(o)), hvalue(L->top - 1));
+ break;
default:
res = 0;
break;
@@ -868,7 +875,7 @@ LUA_API int lua_dump (lua_State *L, lua_Writer writer, void *data) {
if (isLfunction(o))
status = luaU_dump(L, clvalue(o)->l.p, writer, data, 0);
else
- status = 0;
+ status = 1;
lua_unlock(L);
return status;
}
@@ -969,10 +976,10 @@ LUA_API int lua_next (lua_State *L, int idx) {
LUA_API void lua_concat (lua_State *L, int n) {
lua_lock(L);
- luaC_checkGC(L);
api_checknelems(L, n);
if (n >= 2) {
- luaV_concat(L, n, L->top - L->base - 1);
+ luaC_checkGC(L);
+ luaV_concat(L, n, cast(int, L->top - L->base) - 1);
L->top -= (n-1);
}
else if (n == 0) { /* push empty string */
@@ -985,7 +992,7 @@ LUA_API void lua_concat (lua_State *L, int n) {
LUA_API lua_Alloc lua_getallocf (lua_State *L, void **ud) {
- *ud = G(L)->ud;
+ if (ud) *ud = G(L)->ud;
return G(L)->frealloc;
}
diff --git a/src/lauxlib.c b/src/lauxlib.c
index 964f5eb0..b643d6c3 100644
--- a/src/lauxlib.c
+++ b/src/lauxlib.c
@@ -1,5 +1,5 @@
/*
-** $Id: lauxlib.c,v 1.133 2005/05/17 19:49:15 roberto Exp $
+** $Id: lauxlib.c,v 1.152 2005/09/06 17:20:11 roberto Exp $
** Auxiliary functions for building Lua libraries
** See Copyright Notice in lua.h
*/
@@ -42,7 +42,8 @@
LUALIB_API int luaL_argerror (lua_State *L, int narg, const char *extramsg) {
lua_Debug ar;
- lua_getstack(L, 0, &ar);
+ if (!lua_getstack(L, 0, &ar)) /* no stack frame? */
+ return luaL_error(L, "bad argument #%d (%s)", narg, extramsg);
lua_getinfo(L, "n", &ar);
if (strcmp(ar.namewhat, "method") == 0) {
narg--; /* do not count `self' */
@@ -65,7 +66,7 @@ LUALIB_API int luaL_typerror (lua_State *L, int narg, const char *tname) {
static void tag_error (lua_State *L, int narg, int tag) {
- luaL_typerror(L, narg, lua_typename(L, tag));
+ luaL_typerror(L, narg, lua_typename(L, tag));
}
@@ -95,12 +96,16 @@ LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) {
/* }====================================================== */
-LUALIB_API int luaL_findstring (const char *name, const char *const list[]) {
+LUALIB_API int luaL_checkoption (lua_State *L, int narg, const char *def,
+ const char *const lst[]) {
+ const char *name = (def) ? luaL_optstring(L, narg, def) :
+ luaL_checkstring(L, narg);
int i;
- for (i=0; list[i]; i++)
- if (strcmp(list[i], name) == 0)
+ for (i=0; lst[i]; i++)
+ if (strcmp(lst[i], name) == 0)
return i;
- return -1; /* name not found */
+ return luaL_argerror(L, narg,
+ lua_pushfstring(L, "invalid option " LUA_QS, name));
}
@@ -112,31 +117,17 @@ LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) {
lua_newtable(L); /* create metatable */
lua_pushvalue(L, -1);
lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */
- lua_pushvalue(L, -1);
- lua_pushstring(L, tname);
- lua_rawset(L, LUA_REGISTRYINDEX); /* registry[metatable] = name */
return 1;
}
-LUALIB_API void luaL_getmetatable (lua_State *L, const char *tname) {
- lua_getfield(L, LUA_REGISTRYINDEX, tname);
-}
-
-
LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) {
- const char *tn;
- if (!lua_getmetatable(L, ud)) return NULL; /* no metatable? */
- lua_rawget(L, LUA_REGISTRYINDEX); /* get registry[metatable] */
- tn = lua_tostring(L, -1);
- if (tn && (strcmp(tn, tname) == 0)) {
- lua_pop(L, 1);
- return lua_touserdata(L, ud);
- }
- else {
- lua_pop(L, 1);
- return NULL;
- }
+ void *p = lua_touserdata(L, ud);
+ lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get correct metatable */
+ if (p == NULL || !lua_getmetatable(L, ud) || !lua_rawequal(L, -1, -2))
+ luaL_typerror(L, ud, tname);
+ lua_pop(L, 2); /* remove both metatables */
+ return p;
}
@@ -230,26 +221,27 @@ LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {
}
-LUALIB_API void luaL_openlib (lua_State *L, const char *libname,
- const luaL_reg *l, int nup) {
+LUALIB_API void (luaL_register) (lua_State *L, const char *libname,
+ const luaL_Reg *l) {
+ luaI_openlib(L, libname, l, 0);
+}
+
+
+LUALIB_API void luaI_openlib (lua_State *L, const char *libname,
+ const luaL_Reg *l, int nup) {
if (libname) {
/* check whether lib already exists */
- luaL_getfield(L, LUA_GLOBALSINDEX, libname);
- if (lua_isnil(L, -1)) { /* not found? */
+ lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
+ lua_getfield(L, -1, libname); /* get _LOADED[libname] */
+ if (!lua_istable(L, -1)) { /* not found? */
lua_pop(L, 1); /* remove previous result */
- lua_newtable(L); /* create it */
- if (lua_getmetatable(L, LUA_GLOBALSINDEX))
- lua_setmetatable(L, -2); /* share metatable with global table */
- /* register it with given name */
+ /* try global variable (and create one if it does not exist) */
+ if (luaL_findtable(L, LUA_GLOBALSINDEX, libname) != NULL)
+ luaL_error(L, "name conflict for module " LUA_QS, libname);
lua_pushvalue(L, -1);
- luaL_setfield(L, LUA_GLOBALSINDEX, libname);
+ lua_setfield(L, -3, libname); /* _LOADED[libname] = new table */
}
- else if (!lua_istable(L, -1))
- luaL_error(L, "name conflict for library " LUA_QS, libname);
- lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
- lua_pushvalue(L, -2);
- lua_setfield(L, -2, libname); /* _LOADED[modname] = new table */
- lua_pop(L, 1); /* remove _LOADED table */
+ lua_remove(L, -2); /* remove _LOADED table */
lua_insert(L, -(nup+1)); /* move library table to below upvalues */
}
for (; l->name; l++) {
@@ -270,7 +262,7 @@ LUALIB_API void luaL_openlib (lua_State *L, const char *libname,
** =======================================================
*/
-#ifndef luaL_getn
+#if defined(LUA_COMPAT_GETN)
static int checkint (lua_State *L, int topop) {
int n = (lua_type(L, -1) == LUA_TNUMBER) ? lua_tointeger(L, -1) : -1;
@@ -313,7 +305,7 @@ LUALIB_API int luaL_getn (lua_State *L, int t) {
if ((n = checkint(L, 2)) >= 0) return n;
lua_getfield(L, t, "n"); /* else try t.n */
if ((n = checkint(L, 1)) >= 0) return n;
- return lua_objsize(L, t);
+ return lua_objlen(L, t);
}
#endif
@@ -321,21 +313,11 @@ LUALIB_API int luaL_getn (lua_State *L, int t) {
/* }====================================================== */
-static const char *pushnexttemplate (lua_State *L, const char *path) {
- const char *l;
- if (*path == '\0') return NULL; /* no more templates */
- if (*path == LUA_PATHSEP) path++; /* skip separator */
- l = strchr(path, LUA_PATHSEP); /* find next separator */
- if (l == NULL) l = path+strlen(path);
- lua_pushlstring(L, path, l - path); /* template */
- return l;
-}
-
LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p,
const char *r) {
const char *wild;
- int l = strlen(p);
+ size_t l = strlen(p);
luaL_Buffer b;
luaL_buffinit(L, &b);
while ((wild = strstr(s, p)) != NULL) {
@@ -343,65 +325,19 @@ LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p,
luaL_addstring(&b, r); /* push replacement in place of pattern */
s = wild + l; /* continue after `p' */
}
- luaL_addstring(&b, s); /* push last suffix (`n' already includes this) */
+ luaL_addstring(&b, s); /* push last suffix */
luaL_pushresult(&b);
return lua_tostring(L, -1);
}
-static int readable (const char *fname) {
- int err;
- FILE *f = fopen(fname, "r"); /* try to open file */
- if (f == NULL) return 0; /* open failed */
- getc(f); /* try to read it */
- err = ferror(f);
- fclose(f);
- return (err == 0);
-}
-
-
-LUALIB_API const char *luaL_searchpath (lua_State *L, const char *name,
- const char *path) {
- const char *p = path;
- for (;;) {
- const char *fname;
- if ((p = pushnexttemplate(L, p)) == NULL) {
- lua_pushfstring(L, "no readable " LUA_QS " in path " LUA_QS "",
- name, path);
- return NULL;
- }
- fname = luaL_gsub(L, lua_tostring(L, -1), LUA_PATH_MARK, name);
- lua_remove(L, -2); /* remove path template */
- if (readable(fname)) /* does file exist and is readable? */
- return fname; /* return that file name */
- lua_pop(L, 1); /* remove file name */
- }
-}
-
-
-LUALIB_API const char *luaL_getfield (lua_State *L, int idx,
- const char *fname) {
+LUALIB_API const char *luaL_findtable (lua_State *L, int idx,
+ const char *fname) {
const char *e;
lua_pushvalue(L, idx);
- while ((e = strchr(fname, '.')) != NULL) {
- lua_pushlstring(L, fname, e - fname);
- lua_rawget(L, -2);
- lua_remove(L, -2); /* remove previous table */
- fname = e + 1;
- if (!lua_istable(L, -1)) return fname;
- }
- lua_pushstring(L, fname);
- lua_rawget(L, -2); /* get last field */
- lua_remove(L, -2); /* remove previous table */
- return NULL;
-}
-
-
-LUALIB_API const char *luaL_setfield (lua_State *L, int idx,
- const char *fname) {
- const char *e;
- lua_pushvalue(L, idx);
- while ((e = strchr(fname, '.')) != NULL) {
+ do {
+ e = strchr(fname, '.');
+ if (e == NULL) e = fname + strlen(fname);
lua_pushlstring(L, fname, e - fname);
lua_rawget(L, -2);
if (lua_isnil(L, -1)) { /* no such field? */
@@ -411,17 +347,13 @@ LUALIB_API const char *luaL_setfield (lua_State *L, int idx,
lua_pushvalue(L, -2);
lua_settable(L, -4); /* set new table into field */
}
- lua_remove(L, -2); /* remove previous table */
- fname = e + 1;
- if (!lua_istable(L, -1)) {
+ else if (!lua_istable(L, -1)) { /* field has a non-table value? */
lua_pop(L, 2); /* remove table and value */
- return fname;
+ return fname; /* return problematic part of the name */
}
- }
- lua_pushstring(L, fname);
- lua_pushvalue(L, -3); /* move value to the top */
- lua_rawset(L, -3); /* set last field */
- lua_pop(L, 2); /* remove value and table */
+ lua_remove(L, -2); /* remove previous table */
+ fname = e + 1;
+ } while (*e == '.');
return NULL;
}
@@ -480,7 +412,7 @@ LUALIB_API char *luaL_prepbuffer (luaL_Buffer *B) {
LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
while (l--)
- luaL_putchar(B, *s++);
+ luaL_addchar(B, *s++);
}
@@ -538,7 +470,7 @@ LUALIB_API int luaL_ref (lua_State *L, int t) {
lua_rawseti(L, t, FREELIST_REF); /* (t[FREELIST_REF] = t[ref]) */
}
else { /* no free elements */
- ref = lua_objsize(L, t);
+ ref = lua_objlen(L, t);
ref++; /* create new reference */
}
lua_rawseti(L, t, ref);
@@ -661,6 +593,12 @@ LUALIB_API int luaL_loadbuffer (lua_State *L, const char *buff, size_t size,
}
+LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s) {
+ return luaL_loadbuffer(L, s, strlen(s), s);
+}
+
+
+
/* }====================================================== */
@@ -671,21 +609,22 @@ static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
free(ptr);
return NULL;
}
- else
+ else
return realloc(ptr, nsize);
}
static int panic (lua_State *L) {
(void)L; /* to avoid warnings */
- fprintf(stderr, "PANIC: unprotected error during Lua-API call\n");
+ fprintf(stderr, "PANIC: unprotected error in call to Lua API (%s)\n",
+ lua_tostring(L, -1));
return 0;
}
LUALIB_API lua_State *luaL_newstate (void) {
lua_State *L = lua_newstate(l_alloc, NULL);
- lua_atpanic(L, &panic);
+ if (L) lua_atpanic(L, &panic);
return L;
}
diff --git a/src/lauxlib.h b/src/lauxlib.h
index 83c807e9..aa07cb2b 100644
--- a/src/lauxlib.h
+++ b/src/lauxlib.h
@@ -1,5 +1,5 @@
/*
-** $Id: lauxlib.h,v 1.75 2005/03/29 16:20:48 roberto Exp $
+** $Id: lauxlib.h,v 1.85 2005/09/06 17:19:51 roberto Exp $
** Auxiliary functions for building Lua libraries
** See Copyright Notice in lua.h
*/
@@ -15,24 +15,34 @@
#include "lua.h"
-#if !LUA_COMPAT_GETN
-#define luaL_getn(L,i) lua_objsize(L, i)
+#if defined(LUA_COMPAT_GETN)
+LUALIB_API int (luaL_getn) (lua_State *L, int t);
+LUALIB_API void (luaL_setn) (lua_State *L, int t, int n);
+#else
+#define luaL_getn(L,i) ((int)lua_objlen(L, i))
#define luaL_setn(L,i,j) ((void)0) /* no op! */
#endif
+#if defined(LUA_COMPAT_OPENLIB)
+#define luaI_openlib luaL_openlib
+#endif
+
/* extra error code for `luaL_load' */
#define LUA_ERRFILE (LUA_ERRERR+1)
-typedef struct luaL_reg {
+typedef struct luaL_Reg {
const char *name;
lua_CFunction func;
-} luaL_reg;
+} luaL_Reg;
+
-LUALIB_API void (luaL_openlib) (lua_State *L, const char *libname,
- const luaL_reg *l, int nup);
+LUALIB_API void (luaI_openlib) (lua_State *L, const char *libname,
+ const luaL_Reg *l, int nup);
+LUALIB_API void (luaL_register) (lua_State *L, const char *libname,
+ const luaL_Reg *l);
LUALIB_API int (luaL_getmetafield) (lua_State *L, int obj, const char *e);
LUALIB_API int (luaL_callmeta) (lua_State *L, int obj, const char *e);
LUALIB_API int (luaL_typerror) (lua_State *L, int narg, const char *tname);
@@ -53,36 +63,31 @@ LUALIB_API void (luaL_checktype) (lua_State *L, int narg, int t);
LUALIB_API void (luaL_checkany) (lua_State *L, int narg);
LUALIB_API int (luaL_newmetatable) (lua_State *L, const char *tname);
-LUALIB_API void (luaL_getmetatable) (lua_State *L, const char *tname);
LUALIB_API void *(luaL_checkudata) (lua_State *L, int ud, const char *tname);
LUALIB_API void (luaL_where) (lua_State *L, int lvl);
LUALIB_API int (luaL_error) (lua_State *L, const char *fmt, ...);
-LUALIB_API int (luaL_findstring) (const char *st, const char *const lst[]);
-
-LUALIB_API const char *(luaL_searchpath) (lua_State *L, const char *name,
- const char *path);
+LUALIB_API int (luaL_checkoption) (lua_State *L, int narg, const char *def,
+ const char *const lst[]);
LUALIB_API int (luaL_ref) (lua_State *L, int t);
LUALIB_API void (luaL_unref) (lua_State *L, int t, int ref);
-LUALIB_API int (luaL_getn) (lua_State *L, int t);
-LUALIB_API void (luaL_setn) (lua_State *L, int t, int n);
-
LUALIB_API int (luaL_loadfile) (lua_State *L, const char *filename);
LUALIB_API int (luaL_loadbuffer) (lua_State *L, const char *buff, size_t sz,
const char *name);
+LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s);
LUALIB_API lua_State *(luaL_newstate) (void);
LUALIB_API const char *(luaL_gsub) (lua_State *L, const char *s, const char *p,
const char *r);
-LUALIB_API const char *(luaL_getfield) (lua_State *L, int idx,
- const char *fname);
-LUALIB_API const char *(luaL_setfield) (lua_State *L, int idx,
- const char *fname);
+
+LUALIB_API const char *(luaL_findtable) (lua_State *L, int idx,
+ const char *fname);
+
@@ -103,6 +108,13 @@ LUALIB_API const char *(luaL_setfield) (lua_State *L, int idx,
#define luaL_typename(L,i) lua_typename(L, lua_type(L,(i)))
+#define luaL_dofile(L, fn) (luaL_loadfile(L, fn) || lua_pcall(L, 0, 0, 0))
+
+#define luaL_dostring(L, s) (luaL_loadstring(L, s) || lua_pcall(L, 0, 0, 0))
+
+#define luaL_getmetatable(L,n) (lua_getfield(L, LUA_REGISTRYINDEX, (n)))
+
+
/*
** {======================================================
** Generic Buffer manipulation
@@ -118,10 +130,13 @@ typedef struct luaL_Buffer {
char buffer[LUAL_BUFFERSIZE];
} luaL_Buffer;
-#define luaL_putchar(B,c) \
+#define luaL_addchar(B,c) \
((void)((B)->p < ((B)->buffer+LUAL_BUFFERSIZE) || luaL_prepbuffer(B)), \
(*(B)->p++ = (char)(c)))
+/* compatibility only */
+#define luaL_putchar(B,c) luaL_addchar(B,c)
+
#define luaL_addsize(B,n) ((B)->p += (n))
LUALIB_API void (luaL_buffinit) (lua_State *L, luaL_Buffer *B);
@@ -149,6 +164,8 @@ LUALIB_API void (luaL_pushresult) (luaL_Buffer *B);
#define lua_getref(L,ref) lua_rawgeti(L, LUA_REGISTRYINDEX, (ref))
+#define luaL_reg luaL_Reg
+
#endif
diff --git a/src/lbaselib.c b/src/lbaselib.c
index d69d83ff..fb21da4b 100644
--- a/src/lbaselib.c
+++ b/src/lbaselib.c
@@ -1,5 +1,5 @@
/*
-** $Id: lbaselib.c,v 1.176 2005/05/17 19:49:15 roberto Exp $
+** $Id: lbaselib.c,v 1.182 2005/08/26 17:36:32 roberto Exp $
** Basic library
** See Copyright Notice in lua.h
*/
@@ -133,7 +133,7 @@ static void getfunc (lua_State *L) {
static int luaB_getfenv (lua_State *L) {
getfunc(L);
if (lua_iscfunction(L, -1)) /* is a C function? */
- lua_pushvalue(L, LUA_GLOBALSINDEX); /* return the global env. */
+ lua_pushvalue(L, LUA_GLOBALSINDEX); /* return the thread's global env. */
else
lua_getfenv(L, -1);
return 1;
@@ -145,7 +145,10 @@ static int luaB_setfenv (lua_State *L) {
getfunc(L);
lua_pushvalue(L, 2);
if (lua_isnumber(L, 1) && lua_tonumber(L, 1) == 0) {
- lua_replace(L, LUA_GLOBALSINDEX);
+ /* change environment of current thread */
+ lua_pushthread(L);
+ lua_insert(L, -2);
+ lua_setfenv(L, -2);
return 0;
}
else if (lua_iscfunction(L, -2) || lua_setfenv(L, -2) == 0)
@@ -192,9 +195,8 @@ static int luaB_collectgarbage (lua_State *L) {
"count", "step", "setpause", "setstepmul", NULL};
static const int optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT,
LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL};
- int o = luaL_findstring(luaL_optstring(L, 1, "collect"), opts);
+ int o = luaL_checkoption(L, 1, "collect", opts);
int ex = luaL_optinteger(L, 2, 0);
- luaL_argcheck(L, o >= 0, 1, "invalid option");
lua_pushinteger(L, lua_gc(L, optsnum[o], ex));
return 1;
}
@@ -268,15 +270,7 @@ static int luaB_loadstring (lua_State *L) {
static int luaB_loadfile (lua_State *L) {
const char *fname = luaL_optstring(L, 1, NULL);
- const char *path = luaL_optstring(L, 2, NULL);
- int status;
- if (path == NULL)
- status = luaL_loadfile(L, fname);
- else {
- fname = luaL_searchpath(L, fname, path);
- status = (fname) ? luaL_loadfile(L, fname) : 1;
- }
- return load_aux(L, status);
+ return load_aux(L, luaL_loadfile(L, fname));
}
@@ -331,13 +325,6 @@ static int luaB_assert (lua_State *L) {
}
-static int luaB_getn (lua_State *L) {
- luaL_checktype(L, 1, LUA_TTABLE);
- lua_pushinteger(L, lua_objsize(L, 1));
- return 1;
-}
-
-
static int luaB_unpack (lua_State *L) {
int i = luaL_optint(L, 2, 1);
int e = luaL_optint(L, 3, -1);
@@ -442,32 +429,31 @@ static int luaB_newproxy (lua_State *L) {
}
-static const luaL_reg base_funcs[] = {
+static const luaL_Reg base_funcs[] = {
+ {"assert", luaB_assert},
+ {"collectgarbage", luaB_collectgarbage},
+ {"dofile", luaB_dofile},
{"error", luaB_error},
- {"getmetatable", luaB_getmetatable},
- {"setmetatable", luaB_setmetatable},
+ {"gcinfo", luaB_gcinfo},
{"getfenv", luaB_getfenv},
- {"setfenv", luaB_setfenv},
+ {"getmetatable", luaB_getmetatable},
+ {"loadfile", luaB_loadfile},
+ {"load", luaB_load},
+ {"loadstring", luaB_loadstring},
{"next", luaB_next},
+ {"pcall", luaB_pcall},
{"print", luaB_print},
+ {"rawequal", luaB_rawequal},
+ {"rawget", luaB_rawget},
+ {"rawset", luaB_rawset},
+ {"select", luaB_select},
+ {"setfenv", luaB_setfenv},
+ {"setmetatable", luaB_setmetatable},
{"tonumber", luaB_tonumber},
{"tostring", luaB_tostring},
{"type", luaB_type},
- {"assert", luaB_assert},
- {"getn", luaB_getn},
{"unpack", luaB_unpack},
- {"select", luaB_select},
- {"rawequal", luaB_rawequal},
- {"rawget", luaB_rawget},
- {"rawset", luaB_rawset},
- {"pcall", luaB_pcall},
{"xpcall", luaB_xpcall},
- {"collectgarbage", luaB_collectgarbage},
- {"gcinfo", luaB_gcinfo},
- {"loadfile", luaB_loadfile},
- {"dofile", luaB_dofile},
- {"loadstring", luaB_loadstring},
- {"load", luaB_load},
{NULL, NULL}
};
@@ -593,13 +579,13 @@ static int luaB_corunning (lua_State *L) {
}
-static const luaL_reg co_funcs[] = {
+static const luaL_Reg co_funcs[] = {
{"create", luaB_cocreate},
- {"wrap", luaB_cowrap},
{"resume", luaB_coresume},
- {"yield", luaB_yield},
- {"status", luaB_costatus},
{"running", luaB_corunning},
+ {"status", luaB_costatus},
+ {"wrap", luaB_cowrap},
+ {"yield", luaB_yield},
{NULL, NULL}
};
@@ -616,7 +602,7 @@ static void auxopen (lua_State *L, const char *name,
static void base_open (lua_State *L) {
lua_pushvalue(L, LUA_GLOBALSINDEX);
- luaL_openlib(L, NULL, base_funcs, 0); /* open lib into global table */
+ luaL_register(L, NULL, base_funcs); /* open lib into global table */
lua_pushliteral(L, LUA_VERSION);
lua_setglobal(L, "_VERSION"); /* set global _VERSION */
/* `ipairs' and `pairs' need auxliliary functions as upvalues */
@@ -641,7 +627,7 @@ static void base_open (lua_State *L) {
LUALIB_API int luaopen_base (lua_State *L) {
base_open(L);
- luaL_openlib(L, LUA_COLIBNAME, co_funcs, 0);
+ luaL_register(L, LUA_COLIBNAME, co_funcs);
return 2;
}
diff --git a/src/lcode.c b/src/lcode.c
index 1e8d80fb..04838f33 100644
--- a/src/lcode.c
+++ b/src/lcode.c
@@ -1,5 +1,5 @@
/*
-** $Id: lcode.c,v 2.12 2005/03/16 16:59:21 roberto Exp $
+** $Id: lcode.c,v 2.16 2005/08/29 20:49:21 roberto Exp $
** Code generator for Lua
** See Copyright Notice in lua.h
*/
@@ -53,6 +53,11 @@ int luaK_jump (FuncState *fs) {
}
+void luaK_ret (FuncState *fs, int first, int nret) {
+ luaK_codeABC(fs, OP_RETURN, first, nret+1, 0);
+}
+
+
static int condjump (FuncState *fs, OpCode op, int A, int B, int C) {
luaK_codeABC(fs, op, A, B, C);
return luaK_jump(fs);
@@ -101,49 +106,50 @@ static Instruction *getjumpcontrol (FuncState *fs, int pc) {
** check whether list has any jump that do not produce a value
** (or produce an inverted value)
*/
-static int need_value (FuncState *fs, int list, int cond) {
+static int need_value (FuncState *fs, int list) {
for (; list != NO_JUMP; list = getjump(fs, list)) {
Instruction i = *getjumpcontrol(fs, list);
- if (GET_OPCODE(i) != OP_TEST || GETARG_C(i) != cond) return 1;
+ if (GET_OPCODE(i) != OP_TESTSET) return 1;
}
return 0; /* not found */
}
static void patchtestreg (Instruction *i, int reg) {
- if (reg == NO_REG) reg = GETARG_B(*i);
- SETARG_A(*i, reg);
+ if (reg != NO_REG)
+ SETARG_A(*i, reg);
+ else /* no register to put value; change TESTSET to TEST */
+ *i = CREATE_ABC(OP_TEST, GETARG_B(*i), 0, GETARG_C(*i));
}
-static void patchlistaux (FuncState *fs, int list,
- int ttarget, int treg, int ftarget, int freg, int dtarget) {
+static void removevalues (FuncState *fs, int list) {
+ for (; list != NO_JUMP; list = getjump(fs, list)) {
+ Instruction *i = getjumpcontrol(fs, list);
+ if (GET_OPCODE(*i) == OP_TESTSET)
+ patchtestreg(i, NO_REG);
+ }
+}
+
+
+static void patchlistaux (FuncState *fs, int list, int vtarget, int reg,
+ int dtarget) {
while (list != NO_JUMP) {
int next = getjump(fs, list);
Instruction *i = getjumpcontrol(fs, list);
- if (GET_OPCODE(*i) != OP_TEST) {
- lua_assert(dtarget != NO_JUMP);
- fixjump(fs, list, dtarget); /* jump to default target */
- }
- else {
- if (GETARG_C(*i)) {
- lua_assert(ttarget != NO_JUMP);
- patchtestreg(i, treg);
- fixjump(fs, list, ttarget);
- }
- else {
- lua_assert(ftarget != NO_JUMP);
- patchtestreg(i, freg);
- fixjump(fs, list, ftarget);
- }
+ if (GET_OPCODE(*i) == OP_TESTSET) {
+ patchtestreg(i, reg);
+ fixjump(fs, list, vtarget);
}
+ else
+ fixjump(fs, list, dtarget); /* jump to default target */
list = next;
}
}
static void dischargejpc (FuncState *fs) {
- patchlistaux(fs, fs->jpc, fs->pc, NO_REG, fs->pc, NO_REG, fs->pc);
+ patchlistaux(fs, fs->jpc, fs->pc, NO_REG, fs->pc);
fs->jpc = NO_JUMP;
}
@@ -153,7 +159,7 @@ void luaK_patchlist (FuncState *fs, int list, int target) {
luaK_patchtohere(fs, list);
else {
lua_assert(target < fs->pc);
- patchlistaux(fs, list, target, NO_REG, target, NO_REG, target);
+ patchlistaux(fs, list, target, NO_REG, target);
}
}
@@ -223,7 +229,7 @@ static int addk (FuncState *fs, TValue *k, TValue *v) {
MAXARG_Bx, "constant table overflow");
while (oldsize < f->sizek) setnilvalue(&f->k[oldsize++]);
setobj(L, &f->k[fs->nk], v);
- luaC_barriert(L, f, v);
+ luaC_barrier(L, f, v);
return fs->nk++;
}
}
@@ -373,7 +379,7 @@ static void exp2reg (FuncState *fs, expdesc *e, int reg) {
int final; /* position after whole expression */
int p_f = NO_JUMP; /* position of an eventual LOAD false */
int p_t = NO_JUMP; /* position of an eventual LOAD true */
- if (need_value(fs, e->t, 1) || need_value(fs, e->f, 0)) {
+ if (need_value(fs, e->t) || need_value(fs, e->f)) {
int fj = NO_JUMP; /* first jump (over LOAD ops.) */
if (e->k != VJMP)
fj = luaK_jump(fs);
@@ -382,8 +388,8 @@ static void exp2reg (FuncState *fs, expdesc *e, int reg) {
luaK_patchtohere(fs, fj);
}
final = luaK_getlabel(fs);
- patchlistaux(fs, e->f, p_f, NO_REG, final, reg, p_f);
- patchlistaux(fs, e->t, final, reg, p_t, NO_REG, p_t);
+ patchlistaux(fs, e->f, final, reg, p_f);
+ patchlistaux(fs, e->t, final, reg, p_t);
}
e->f = e->t = NO_JUMP;
e->info = reg;
@@ -492,7 +498,8 @@ void luaK_self (FuncState *fs, expdesc *e, expdesc *key) {
static void invertjump (FuncState *fs, expdesc *e) {
Instruction *pc = getjumpcontrol(fs, e->info);
- lua_assert(testTMode(GET_OPCODE(*pc)) && GET_OPCODE(*pc) != OP_TEST);
+ lua_assert(testTMode(GET_OPCODE(*pc)) && GET_OPCODE(*pc) != OP_TESTSET &&
+ GET_OPCODE(*pc) != OP_TEST);
SETARG_A(*pc, !(GETARG_A(*pc)));
}
@@ -502,13 +509,13 @@ static int jumponcond (FuncState *fs, expdesc *e, int cond) {
Instruction ie = getcode(fs, e);
if (GET_OPCODE(ie) == OP_NOT) {
fs->pc--; /* remove previous OP_NOT */
- return condjump(fs, OP_TEST, NO_REG, GETARG_B(ie), !cond);
+ return condjump(fs, OP_TEST, GETARG_B(ie), 0, !cond);
}
/* else go through */
}
discharge2anyreg(fs, e);
freeexp(fs, e);
- return condjump(fs, OP_TEST, NO_REG, e->info, cond);
+ return condjump(fs, OP_TESTSET, NO_REG, e->info, cond);
}
@@ -535,6 +542,8 @@ void luaK_goiftrue (FuncState *fs, expdesc *e) {
}
}
luaK_concat(fs, &e->f, pc); /* insert last jump in `f' list */
+ luaK_patchtohere(fs, e->t);
+ e->t = NO_JUMP;
}
@@ -560,6 +569,8 @@ void luaK_goiffalse (FuncState *fs, expdesc *e) {
}
}
luaK_concat(fs, &e->t, pc); /* insert last jump in `t' list */
+ luaK_patchtohere(fs, e->f);
+ e->f = NO_JUMP;
}
@@ -593,6 +604,8 @@ static void codenot (FuncState *fs, expdesc *e) {
}
/* interchange true and false lists */
{ int temp = e->f; e->f = e->t; e->t = temp; }
+ removevalues(fs, e->f);
+ removevalues(fs, e->t);
}
@@ -607,7 +620,7 @@ void luaK_prefix (FuncState *fs, UnOpr op, expdesc *e) {
case OPR_MINUS: {
luaK_exp2val(fs, e);
if (e->k == VK && ttisnumber(&fs->f->k[e->info]))
- e->info = luaK_numberK(fs, luai_numunm(nvalue(&fs->f->k[e->info])));
+ e->info = luaK_numberK(fs, luai_numunm(L, nvalue(&fs->f->k[e->info])));
else {
luaK_exp2anyreg(fs, e);
freeexp(fs, e);
@@ -620,10 +633,10 @@ void luaK_prefix (FuncState *fs, UnOpr op, expdesc *e) {
codenot(fs, e);
break;
}
- case OPR_SIZE: {
+ case OPR_LEN: {
luaK_exp2anyreg(fs, e);
freeexp(fs, e);
- e->info = luaK_codeABC(fs, OP_SIZ, 0, e->info, 0);
+ e->info = luaK_codeABC(fs, OP_LEN, 0, e->info, 0);
e->k = VRELOCABLE;
break;
}
@@ -636,14 +649,10 @@ void luaK_infix (FuncState *fs, BinOpr op, expdesc *v) {
switch (op) {
case OPR_AND: {
luaK_goiftrue(fs, v);
- luaK_patchtohere(fs, v->t);
- v->t = NO_JUMP;
break;
}
case OPR_OR: {
luaK_goiffalse(fs, v);
- luaK_patchtohere(fs, v->f);
- v->f = NO_JUMP;
break;
}
case OPR_CONCAT: {
diff --git a/src/lcode.h b/src/lcode.h
index 19a3284e..ed1a95bc 100644
--- a/src/lcode.h
+++ b/src/lcode.h
@@ -1,5 +1,5 @@
/*
-** $Id: lcode.h,v 1.43 2005/04/25 19:24:10 roberto Exp $
+** $Id: lcode.h,v 1.45 2005/08/29 20:49:21 roberto Exp $
** Code generator for Lua
** See Copyright Notice in lua.h
*/
@@ -34,7 +34,7 @@ typedef enum BinOpr {
#define binopistest(op) ((op) >= OPR_NE)
-typedef enum UnOpr { OPR_MINUS, OPR_NOT, OPR_SIZE, OPR_NOUNOPR } UnOpr;
+typedef enum UnOpr { OPR_MINUS, OPR_NOT, OPR_LEN, OPR_NOUNOPR } UnOpr;
#define getcode(fs,e) ((fs)->f->code[(e)->info])
@@ -65,6 +65,7 @@ LUAI_FUNC void luaK_storevar (FuncState *fs, expdesc *var, expdesc *e);
LUAI_FUNC void luaK_setreturns (FuncState *fs, expdesc *e, int nresults);
LUAI_FUNC void luaK_setoneret (FuncState *fs, expdesc *e);
LUAI_FUNC int luaK_jump (FuncState *fs);
+LUAI_FUNC void luaK_ret (FuncState *fs, int first, int nret);
LUAI_FUNC void luaK_patchlist (FuncState *fs, int list, int target);
LUAI_FUNC void luaK_patchtohere (FuncState *fs, int list);
LUAI_FUNC void luaK_concat (FuncState *fs, int *l1, int l2);
diff --git a/src/ldblib.c b/src/ldblib.c
index 6c1a1776..e7458634 100644
--- a/src/ldblib.c
+++ b/src/ldblib.c
@@ -1,5 +1,5 @@
/*
-** $Id: ldblib.c,v 1.98 2005/05/17 19:49:15 roberto Exp $
+** $Id: ldblib.c,v 1.101 2005/08/26 17:36:32 roberto Exp $
** Interface from Lua to its debug API
** See Copyright Notice in lua.h
*/
@@ -365,26 +365,26 @@ static int db_errorfb (lua_State *L) {
}
-static const luaL_reg dblib[] = {
- {"getmetatable", db_getmetatable},
- {"setmetatable", db_setmetatable},
+static const luaL_Reg dblib[] = {
+ {"debug", db_debug},
{"getfenv", db_getfenv},
- {"setfenv", db_setfenv},
- {"getlocal", db_getlocal},
- {"getinfo", db_getinfo},
{"gethook", db_gethook},
+ {"getinfo", db_getinfo},
+ {"getlocal", db_getlocal},
+ {"getmetatable", db_getmetatable},
{"getupvalue", db_getupvalue},
+ {"setfenv", db_setfenv},
{"sethook", db_sethook},
{"setlocal", db_setlocal},
+ {"setmetatable", db_setmetatable},
{"setupvalue", db_setupvalue},
- {"debug", db_debug},
{"traceback", db_errorfb},
{NULL, NULL}
};
LUALIB_API int luaopen_debug (lua_State *L) {
- luaL_openlib(L, LUA_DBLIBNAME, dblib, 0);
+ luaL_register(L, LUA_DBLIBNAME, dblib);
return 1;
}
diff --git a/src/ldebug.c b/src/ldebug.c
index 73a604ff..11166c0a 100644
--- a/src/ldebug.c
+++ b/src/ldebug.c
@@ -1,5 +1,5 @@
/*
-** $Id: ldebug.c,v 2.20 2005/05/17 19:49:15 roberto Exp $
+** $Id: ldebug.c,v 2.26 2005/08/04 13:37:38 roberto Exp $
** Debug Interface
** See Copyright Notice in lua.h
*/
@@ -92,7 +92,7 @@ LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar) {
}
if (level == 0 && ci > L->base_ci) { /* level found? */
status = 1;
- ar->i_ci = ci - L->base_ci;
+ ar->i_ci = cast(int, ci - L->base_ci);
}
else if (level < 0) { /* level is of a lost tail call? */
status = 1;
@@ -152,6 +152,7 @@ static void funcinfo (lua_Debug *ar, Closure *cl) {
if (cl->c.isC) {
ar->source = "=[C]";
ar->linedefined = -1;
+ ar->lastlinedefined = -1;
ar->what = "C";
}
else {
@@ -164,7 +165,7 @@ static void funcinfo (lua_Debug *ar, Closure *cl) {
}
-static void info_tailcall (lua_State *L, lua_Debug *ar) {
+static void info_tailcall (lua_Debug *ar) {
ar->name = ar->namewhat = "";
ar->what = "tail";
ar->lastlinedefined = ar->linedefined = ar->currentline = -1;
@@ -194,7 +195,7 @@ static int auxgetinfo (lua_State *L, const char *what, lua_Debug *ar,
Closure *f, CallInfo *ci) {
int status = 1;
if (f == NULL) {
- info_tailcall(L, ar);
+ info_tailcall(ar);
return status;
}
for (; *what; what++) {
@@ -275,8 +276,11 @@ LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) {
static int precheck (const Proto *pt) {
check(pt->maxstacksize <= MAXSTACK);
+ lua_assert(pt->numparams+(pt->is_vararg & VARARG_HASARG) <= pt->maxstacksize);
+ lua_assert(!(pt->is_vararg & VARARG_NEEDSARG) ||
+ (pt->is_vararg & VARARG_HASARG));
+ check(pt->sizeupvalues <= pt->nups);
check(pt->sizelineinfo == pt->sizecode || pt->sizelineinfo == 0);
- lua_assert(pt->numparams+pt->is_vararg <= pt->maxstacksize);
check(GET_OPCODE(pt->code[pt->sizecode-1]) == OP_RETURN);
return 1;
}
@@ -389,8 +393,8 @@ static Instruction symbexec (const Proto *pt, int lastpc, int reg) {
}
case OP_TFORLOOP: {
check(c >= 1); /* at least one result (control variable) */
- checkreg(pt, a+3+c); /* space for results */
- if (reg >= a+3) last = pc; /* affect all regs above its call base */
+ checkreg(pt, a+2+c); /* space for results */
+ if (reg >= a+2) last = pc; /* affect all regs above its base */
break;
}
case OP_FORLOOP:
@@ -440,7 +444,8 @@ static Instruction symbexec (const Proto *pt, int lastpc, int reg) {
break;
}
case OP_VARARG: {
- check(pt->is_vararg & NEWSTYLEVARARG);
+ check((pt->is_vararg & VARARG_ISVARARG) &&
+ !(pt->is_vararg & VARARG_NEEDSARG));
b--;
if (b == LUA_MULTRET) check(checkopenop(pt, pc));
checkreg(pt, a+b-1);
@@ -546,7 +551,8 @@ void luaG_typeerror (lua_State *L, const TValue *o, const char *op) {
const char *name = NULL;
const char *t = luaT_typenames[ttype(o)];
const char *kind = (isinstack(L->ci, o)) ?
- getobjname(L, L->ci, o - L->base, &name) : NULL;
+ getobjname(L, L->ci, cast(int, o - L->base), &name) :
+ NULL;
if (kind)
luaG_runerror(L, "attempt to %s %s " LUA_QS " (a %s value)",
op, kind, name, t);
diff --git a/src/ldo.c b/src/ldo.c
index 09e0a44d..d7645835 100644
--- a/src/ldo.c
+++ b/src/ldo.c
@@ -1,5 +1,5 @@
/*
-** $Id: ldo.c,v 2.23 2005/05/03 19:01:17 roberto Exp $
+** $Id: ldo.c,v 2.33 2005/09/09 18:16:28 roberto Exp $
** Stack and Call structure of Lua
** See Copyright Notice in lua.h
*/
@@ -48,7 +48,7 @@ struct lua_longjmp {
};
-static void seterrorobj (lua_State *L, int errcode, StkId oldtop) {
+void luaD_seterrorobj (lua_State *L, int errcode, StkId oldtop) {
switch (errcode) {
case LUA_ERRMEM: {
setsvalue2s(L, oldtop, luaS_newliteral(L, MEMERRMSG));
@@ -68,14 +68,41 @@ static void seterrorobj (lua_State *L, int errcode, StkId oldtop) {
}
+static void restore_stack_limit (lua_State *L) {
+ lua_assert(L->stack_last - L->stack == L->stacksize - EXTRA_STACK - 1);
+ if (L->size_ci > LUAI_MAXCALLS) { /* there was an overflow? */
+ int inuse = cast(int, L->ci - L->base_ci);
+ if (inuse + 1 < LUAI_MAXCALLS) /* can `undo' overflow? */
+ luaD_reallocCI(L, LUAI_MAXCALLS);
+ }
+}
+
+
+static void resetstack (lua_State *L, int status) {
+ L->ci = L->base_ci;
+ L->base = L->ci->base;
+ luaF_close(L, L->base); /* close eventual pending closures */
+ luaD_seterrorobj(L, status, L->base);
+ L->nCcalls = 0;
+ L->allowhook = 1;
+ restore_stack_limit(L);
+ L->errfunc = 0;
+ L->errorJmp = NULL;
+}
+
+
void luaD_throw (lua_State *L, int errcode) {
if (L->errorJmp) {
L->errorJmp->status = errcode;
LUAI_THROW(L, L->errorJmp);
}
else {
- L->status = errcode;
- if (G(L)->panic) G(L)->panic(L);
+ L->status = cast(lu_byte, errcode);
+ if (G(L)->panic) {
+ resetstack(L, errcode);
+ lua_unlock(L);
+ G(L)->panic(L);
+ }
exit(EXIT_FAILURE);
}
}
@@ -93,16 +120,6 @@ int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) {
return lj.status;
}
-
-static void restore_stack_limit (lua_State *L) {
- lua_assert(L->stack_last - L->stack == L->stacksize - EXTRA_STACK - 1);
- if (L->size_ci > LUAI_MAXCALLS) { /* there was an overflow? */
- int inuse = (L->ci - L->base_ci);
- if (inuse + 1 < LUAI_MAXCALLS) /* can `undo' overflow? */
- luaD_reallocCI(L, LUAI_MAXCALLS);
- }
-}
-
/* }====================================================== */
@@ -116,9 +133,8 @@ static void correctstack (lua_State *L, TValue *oldstack) {
ci->top = (ci->top - oldstack) + L->stack;
ci->base = (ci->base - oldstack) + L->stack;
ci->func = (ci->func - oldstack) + L->stack;
- lua_assert(lua_checkpc(L, ci));
}
- L->base = L->ci->base;
+ L->base = (L->base - oldstack) + L->stack;
}
@@ -173,7 +189,7 @@ void luaD_callhook (lua_State *L, int event, int line) {
if (event == LUA_HOOKTAILRET)
ar.i_ci = 0; /* tail call; no debug information about it */
else
- ar.i_ci = L->ci - L->base_ci;
+ ar.i_ci = cast(int, L->ci - L->base_ci);
luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */
L->ci->top = L->top + LUA_MINSTACK;
lua_assert(L->ci->top <= L->stack_last);
@@ -189,18 +205,17 @@ void luaD_callhook (lua_State *L, int event, int line) {
}
-static StkId adjust_varargs (lua_State *L, int nfixargs, int actual,
- int style) {
+static StkId adjust_varargs (lua_State *L, Proto *p, int actual) {
int i;
+ int nfixargs = p->numparams;
Table *htab = NULL;
StkId base, fixed;
- if (actual < nfixargs) {
- for (; actual < nfixargs; ++actual)
- setnilvalue(L->top++);
- }
-#if LUA_COMPAT_VARARG
- if (style != NEWSTYLEVARARG) { /* compatibility with old-style vararg */
+ for (; actual < nfixargs; ++actual)
+ setnilvalue(L->top++);
+#if defined(LUA_COMPAT_VARARG)
+ if (p->is_vararg & VARARG_NEEDSARG) { /* compat. with old-style vararg? */
int nvar = actual - nfixargs; /* number of extra arguments */
+ lua_assert(p->is_vararg & VARARG_HASARG);
luaC_checkGC(L);
htab = luaH_new(L, nvar, 1); /* create `arg' table */
for (i=0; i<nvar; i++) /* put extra arguments into `arg' table */
@@ -259,16 +274,14 @@ int luaD_precall (lua_State *L, StkId func, int nresults) {
CallInfo *ci;
StkId st, base;
Proto *p = cl->p;
- if (p->is_vararg) { /* varargs? */
- int nargs = L->top - restorestack(L, funcr) - 1;
- luaD_checkstack(L, p->maxstacksize + nargs);
- base = adjust_varargs(L, p->numparams, nargs, p->is_vararg);
- func = restorestack(L, funcr);
- }
- else {
- luaD_checkstack(L, p->maxstacksize);
- func = restorestack(L, funcr);
+ luaD_checkstack(L, p->maxstacksize);
+ func = restorestack(L, funcr);
+ if (!p->is_vararg) /* no varargs? */
base = func + 1;
+ else { /* vararg function */
+ int nargs = cast(int, L->top - func) - 1;
+ base = adjust_varargs(L, p, nargs);
+ func = restorestack(L, funcr); /* previous call may change the stack */
}
ci = inc_ci(L); /* now `enter' new function */
ci->func = func;
@@ -281,6 +294,11 @@ int luaD_precall (lua_State *L, StkId func, int nresults) {
for (st = L->top; st < ci->top; st++)
setnilvalue(st);
L->top = ci->top;
+ if (L->hookmask & LUA_MASKCALL) {
+ L->savedpc++; /* hooks assume 'pc' is already incremented */
+ luaD_callhook(L, LUA_HOOKCALL, -1);
+ L->savedpc--; /* correct 'pc' */
+ }
return PCRLUA;
}
else { /* if is a C function, call it */
@@ -292,13 +310,14 @@ int luaD_precall (lua_State *L, StkId func, int nresults) {
L->base = ci->base = ci->func + 1;
ci->top = L->top + LUA_MINSTACK;
lua_assert(ci->top <= L->stack_last);
+ ci->nresults = nresults;
if (L->hookmask & LUA_MASKCALL)
luaD_callhook(L, LUA_HOOKCALL, -1);
lua_unlock(L);
n = (*curr_func(L)->c.f)(L); /* do the actual call */
lua_lock(L);
if (n >= 0) { /* no yielding? */
- luaD_poscall(L, nresults, L->top - n);
+ luaD_poscall(L, L->top - n);
return PCRC;
}
else {
@@ -320,22 +339,24 @@ static StkId callrethooks (lua_State *L, StkId firstResult) {
}
-void luaD_poscall (lua_State *L, int wanted, StkId firstResult) {
+int luaD_poscall (lua_State *L, StkId firstResult) {
StkId res;
+ int wanted, i;
+ CallInfo *ci;
if (L->hookmask & LUA_MASKRET)
firstResult = callrethooks(L, firstResult);
- res = L->ci->func; /* res == final position of 1st result */
- L->ci--;
- L->base = L->ci->base; /* restore base */
- L->savedpc = L->ci->savedpc; /* restore savedpc */
+ ci = L->ci--;
+ res = ci->func; /* res == final position of 1st result */
+ wanted = ci->nresults;
+ L->base = (ci - 1)->base; /* restore base */
+ L->savedpc = (ci - 1)->savedpc; /* restore savedpc */
/* move results to correct place */
- while (wanted != 0 && firstResult < L->top) {
+ for (i = wanted; i != 0 && firstResult < L->top; i--)
setobjs2s(L, res++, firstResult++);
- wanted--;
- }
- while (wanted-- > 0)
+ while (i-- > 0)
setnilvalue(res++);
L->top = res;
+ return (wanted - LUA_MULTRET); /* 0 iff wanted == LUA_MULTRET */
}
@@ -352,38 +373,34 @@ void luaD_call (lua_State *L, StkId func, int nResults) {
else if (L->nCcalls >= (LUAI_MAXCCALLS + (LUAI_MAXCCALLS>>3)))
luaD_throw(L, LUA_ERRERR); /* error while handing stack error */
}
- if (luaD_precall(L, func, nResults) == PCRLUA) { /* is a Lua function? */
- StkId firstResult = luaV_execute(L, 1); /* call it */
- luaD_poscall(L, nResults, firstResult);
- }
+ if (luaD_precall(L, func, nResults) == PCRLUA) /* is a Lua function? */
+ luaV_execute(L, 1); /* call it */
L->nCcalls--;
luaC_checkGC(L);
}
static void resume (lua_State *L, void *ud) {
- StkId firstResult;
- int nargs = *cast(int *, ud);
+ StkId firstArg = cast(StkId, ud);
CallInfo *ci = L->ci;
- if (L->status != LUA_YIELD) {
- lua_assert(ci == L->base_ci && nargs < L->top - L->base);
- luaD_precall(L, L->top - (nargs + 1), LUA_MULTRET); /* start coroutine */
+ if (L->status != LUA_YIELD) { /* start coroutine */
+ lua_assert(ci == L->base_ci && firstArg > L->base);
+ if (luaD_precall(L, firstArg - 1, LUA_MULTRET) != PCRLUA)
+ return;
}
else { /* resuming from previous yield */
if (!f_isLua(ci)) { /* `common' yield? */
/* finish interrupted execution of `OP_CALL' */
- int nresults = ci->nresults;
lua_assert(GET_OPCODE(*((ci-1)->savedpc - 1)) == OP_CALL ||
GET_OPCODE(*((ci-1)->savedpc - 1)) == OP_TAILCALL);
- luaD_poscall(L, nresults, L->top - nargs); /* complete it */
- if (nresults >= 0) L->top = L->ci->top;
- } /* else yielded inside a hook: just continue its execution */
+ if (luaD_poscall(L, firstArg)) /* complete it... */
+ L->top = L->ci->top; /* and correct top if not multiple results */
+ }
+ else /* yielded inside a hook: just continue its execution */
+ L->base = L->ci->base;
}
L->status = 0;
- firstResult = luaV_execute(L, L->ci - L->base_ci);
- if (firstResult != NULL) { /* return? */
- luaD_poscall(L, LUA_MULTRET, firstResult); /* finalize this coroutine */
- }
+ luaV_execute(L, cast(int, L->ci - L->base_ci));
}
@@ -399,17 +416,18 @@ static int resume_error (lua_State *L, const char *msg) {
LUA_API int lua_resume (lua_State *L, int nargs) {
int status;
lua_lock(L);
- lua_assert(L->errfunc == 0 && L->nCcalls == 0);
if (L->status != LUA_YIELD) {
if (L->status != 0)
return resume_error(L, "cannot resume dead coroutine");
else if (L->ci != L->base_ci)
return resume_error(L, "cannot resume non-suspended coroutine");
}
- status = luaD_rawrunprotected(L, resume, &nargs);
+ luai_userstateresume(L, nargs);
+ lua_assert(L->errfunc == 0 && L->nCcalls == 0);
+ status = luaD_rawrunprotected(L, resume, L->top - nargs);
if (status != 0) { /* error? */
- L->status = status; /* mark thread as `dead' */
- seterrorobj(L, status, L->top);
+ L->status = cast(lu_byte, status); /* mark thread as `dead' */
+ luaD_seterrorobj(L, status, L->top);
}
else
status = L->status;
@@ -419,19 +437,11 @@ LUA_API int lua_resume (lua_State *L, int nargs) {
LUA_API int lua_yield (lua_State *L, int nresults) {
- CallInfo *ci;
+ luai_userstateyield(L, nresults);
lua_lock(L);
- ci = L->ci;
if (L->nCcalls > 0)
luaG_runerror(L, "attempt to yield across metamethod/C-call boundary");
- if (!f_isLua(ci)) { /* usual yield */
- if (L->top - nresults > L->base) { /* is there garbage in the stack? */
- int i;
- for (i=0; i<nresults; i++) /* move down results */
- setobjs2s(L, L->base + i, L->top - nresults + i);
- L->top = L->base + nresults;
- }
- } /* else it's an yield inside a hook: nothing to do */
+ L->base = L->top - nresults; /* protect stack slots below */
L->status = LUA_YIELD;
lua_unlock(L);
return -1;
@@ -441,7 +451,7 @@ LUA_API int lua_yield (lua_State *L, int nresults) {
int luaD_pcall (lua_State *L, Pfunc func, void *u,
ptrdiff_t old_top, ptrdiff_t ef) {
int status;
- int oldnCcalls = L->nCcalls;
+ unsigned short oldnCcalls = L->nCcalls;
ptrdiff_t old_ci = saveci(L, L->ci);
lu_byte old_allowhooks = L->allowhook;
ptrdiff_t old_errfunc = L->errfunc;
@@ -450,7 +460,7 @@ int luaD_pcall (lua_State *L, Pfunc func, void *u,
if (status != 0) { /* an error occurred? */
StkId oldtop = restorestack(L, old_top);
luaF_close(L, oldtop); /* close eventual pending closures */
- seterrorobj(L, status, oldtop);
+ luaD_seterrorobj(L, status, oldtop);
L->nCcalls = oldnCcalls;
L->ci = restoreci(L, old_ci);
L->base = L->ci->base;
diff --git a/src/ldo.h b/src/ldo.h
index b355b7e8..b2de92bb 100644
--- a/src/ldo.h
+++ b/src/ldo.h
@@ -1,5 +1,5 @@
/*
-** $Id: ldo.h,v 2.4 2005/04/25 19:24:10 roberto Exp $
+** $Id: ldo.h,v 2.7 2005/08/24 16:15:49 roberto Exp $
** Stack and Call structure of Lua
** See Copyright Notice in lua.h
*/
@@ -13,16 +13,6 @@
#include "lzio.h"
-/*
-** macro to control inclusion of some hard tests on stack reallocation
-*/
-#ifndef HARDSTACKTESTS
-#define condhardstacktests(x) ((void)0)
-#else
-#define condhardstacktests(x) x
-#endif
-
-
#define luaD_checkstack(L,n) \
if ((char *)L->stack_last - (char *)L->top <= (n)*(int)sizeof(TValue)) \
luaD_growstack(L, n); \
@@ -53,7 +43,7 @@ LUAI_FUNC int luaD_precall (lua_State *L, StkId func, int nresults);
LUAI_FUNC void luaD_call (lua_State *L, StkId func, int nResults);
LUAI_FUNC int luaD_pcall (lua_State *L, Pfunc func, void *u,
ptrdiff_t oldtop, ptrdiff_t ef);
-LUAI_FUNC void luaD_poscall (lua_State *L, int wanted, StkId firstResult);
+LUAI_FUNC int luaD_poscall (lua_State *L, StkId firstResult);
LUAI_FUNC void luaD_reallocCI (lua_State *L, int newsize);
LUAI_FUNC void luaD_reallocstack (lua_State *L, int newsize);
LUAI_FUNC void luaD_growstack (lua_State *L, int n);
@@ -61,6 +51,7 @@ LUAI_FUNC void luaD_growstack (lua_State *L, int n);
LUAI_FUNC void luaD_throw (lua_State *L, int errcode);
LUAI_FUNC int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud);
+LUAI_FUNC void luaD_seterrorobj (lua_State *L, int errcode, StkId oldtop);
#endif
diff --git a/src/ldump.c b/src/ldump.c
index 0c9f00d1..e580047b 100644
--- a/src/ldump.c
+++ b/src/ldump.c
@@ -1,5 +1,5 @@
/*
-** $Id: ldump.c,v 1.10 2005/05/12 00:26:50 lhf Exp $
+** $Id: ldump.c,v 1.12 2005/06/08 14:40:44 lhf Exp $
** save pre-compiled Lua chunks
** See Copyright Notice in lua.h
*/
@@ -16,17 +16,20 @@
#include "lstate.h"
#include "lundump.h"
-#define DumpVector(b,n,size,D) DumpBlock(b,(n)*(size),D)
-#define DumpLiteral(s,D) DumpBlock("" s,(sizeof(s))-1,D)
-
typedef struct {
lua_State* L;
- lua_Chunkwriter writer;
+ lua_Writer writer;
void* data;
int strip;
int status;
} DumpState;
+#define DumpCode(f,D) DumpVector(f->code,f->sizecode,sizeof(Instruction),D)
+#define DumpLines(f,D) DumpVector(f->lineinfo,f->sizelineinfo,sizeof(int),D)
+#define DumpLiteral(s,D) DumpBlock("" s,(sizeof(s))-1,D)
+#define DumpVar(x,D) DumpMem(&x,1,sizeof(x),D)
+#define DumpMem(b,n,size,D) DumpBlock(b,(n)*(size),D)
+
static void DumpBlock(const void* b, size_t size, DumpState* D)
{
if (D->status==0)
@@ -37,45 +40,43 @@ static void DumpBlock(const void* b, size_t size, DumpState* D)
}
}
-static void DumpByte(int y, DumpState* D)
+static void DumpChar(int y, DumpState* D)
{
char x=(char)y;
- DumpBlock(&x,sizeof(x),D);
+ DumpVar(x,D);
}
static void DumpInt(int x, DumpState* D)
{
- DumpBlock(&x,sizeof(x),D);
+ DumpVar(x,D);
}
-static void DumpSize(size_t x, DumpState* D)
+static void DumpNumber(lua_Number x, DumpState* D)
{
- DumpBlock(&x,sizeof(x),D);
+ DumpVar(x,D);
}
-static void DumpNumber(lua_Number x, DumpState* D)
+static void DumpVector(const void* b, int n, size_t size, DumpState* D)
{
- DumpBlock(&x,sizeof(x),D);
+ DumpInt(n,D);
+ DumpMem(b,n,size,D);
}
static void DumpString(const TString* s, DumpState* D)
{
if (s==NULL || getstr(s)==NULL)
- DumpSize(0,D);
+ {
+ size_t size=0;
+ DumpVar(size,D);
+ }
else
{
size_t size=s->tsv.len+1; /* include trailing '\0' */
- DumpSize(size,D);
+ DumpVar(size,D);
DumpBlock(getstr(s),size,D);
}
}
-static void DumpCode(const Proto* f, DumpState* D)
-{
- DumpInt(f->sizecode,D);
- DumpVector(f->code,f->sizecode,sizeof(*f->code),D);
-}
-
static void DumpLocals(const Proto* f, DumpState* D)
{
int i,n=f->sizelocvars;
@@ -88,12 +89,6 @@ static void DumpLocals(const Proto* f, DumpState* D)
}
}
-static void DumpLines(const Proto* f, DumpState* D)
-{
- DumpInt(f->sizelineinfo,D);
- DumpVector(f->lineinfo,f->sizelineinfo,sizeof(*f->lineinfo),D);
-}
-
static void DumpUpvalues(const Proto* f, DumpState* D)
{
int i,n=f->sizeupvalues;
@@ -105,18 +100,18 @@ static void DumpFunction(const Proto* f, const TString* p, DumpState* D);
static void DumpConstants(const Proto* f, DumpState* D)
{
- int i,n;
- DumpInt(n=f->sizek,D);
+ int i,n=f->sizek;
+ DumpInt(n,D);
for (i=0; i<n; i++)
{
const TValue* o=&f->k[i];
- DumpByte(ttype(o),D);
+ DumpChar(ttype(o),D);
switch (ttype(o))
{
case LUA_TNIL:
break;
case LUA_TBOOLEAN:
- DumpByte(bvalue(o),D);
+ DumpChar(bvalue(o),D);
break;
case LUA_TNUMBER:
DumpNumber(nvalue(o),D);
@@ -129,7 +124,8 @@ static void DumpConstants(const Proto* f, DumpState* D)
break;
}
}
- DumpInt(n=f->sizep,D);
+ n=f->sizep;
+ DumpInt(n,D);
for (i=0; i<n; i++) DumpFunction(f->p[i],f->source,D);
}
@@ -138,10 +134,10 @@ static void DumpFunction(const Proto* f, const TString* p, DumpState* D)
DumpString((f->source==p) ? NULL : f->source,D);
DumpInt(f->linedefined,D);
DumpInt(f->lastlinedefined,D);
- DumpByte(f->nups,D);
- DumpByte(f->numparams,D);
- DumpByte(f->is_vararg,D);
- DumpByte(f->maxstacksize,D);
+ DumpChar(f->nups,D);
+ DumpChar(f->numparams,D);
+ DumpChar(f->is_vararg,D);
+ DumpChar(f->maxstacksize,D);
if (D->strip) DumpInt(0,D); else DumpLines(f,D);
if (D->strip) DumpInt(0,D); else DumpLocals(f,D);
if (D->strip) DumpInt(0,D); else DumpUpvalues(f,D);
@@ -151,20 +147,15 @@ static void DumpFunction(const Proto* f, const TString* p, DumpState* D)
static void DumpHeader(DumpState* D)
{
- DumpLiteral(LUA_SIGNATURE,D);
- DumpByte(VERSION,D);
- DumpByte(luaU_endianness(),D);
- DumpByte(sizeof(int),D);
- DumpByte(sizeof(size_t),D);
- DumpByte(sizeof(Instruction),D);
- DumpByte(sizeof(lua_Number),D);
- DumpNumber(TEST_NUMBER,D);
+ char h[LUAC_HEADERSIZE];
+ luaU_header(h);
+ DumpBlock(h,LUAC_HEADERSIZE,D);
}
/*
** dump Lua function as precompiled chunk
*/
-int luaU_dump (lua_State* L, const Proto* f, lua_Chunkwriter w, void* data, int strip)
+int luaU_dump (lua_State* L, const Proto* f, lua_Writer w, void* data, int strip)
{
DumpState D;
D.L=L;
diff --git a/src/lgc.c b/src/lgc.c
index 9257d2bc..0f30104f 100644
--- a/src/lgc.c
+++ b/src/lgc.c
@@ -1,5 +1,5 @@
/*
-** $Id: lgc.c,v 2.32 2005/05/05 15:34:03 roberto Exp $
+** $Id: lgc.c,v 2.36 2005/08/24 17:06:36 roberto Exp $
** Garbage Collector
** See Copyright Notice in lua.h
*/
@@ -240,8 +240,8 @@ static void traverseclosure (global_State *g, Closure *cl) {
static void checkstacksizes (lua_State *L, StkId max) {
- int ci_used = L->ci - L->base_ci; /* number of `ci' in use */
- int s_used = max - L->stack; /* part of stack in use */
+ int ci_used = cast(int, L->ci - L->base_ci); /* number of `ci' in use */
+ int s_used = cast(int, max - L->stack); /* part of stack in use */
if (L->size_ci > LUAI_MAXCALLS) /* handling overflow? */
return; /* do not touch the stacks */
if (4*ci_used < L->size_ci && 2*BASIC_CI_SIZE < L->size_ci)
@@ -287,7 +287,6 @@ static l_mem propagatemark (global_State *g) {
black2gray(o); /* keep it gray */
return sizeof(Table) + sizeof(TValue) * h->sizearray +
sizeof(Node) * sizenode(h);
- break;
}
case LUA_TFUNCTION: {
Closure *cl = gco2cl(o);
@@ -295,7 +294,6 @@ static l_mem propagatemark (global_State *g) {
traverseclosure(g, cl);
return (cl->c.isC) ? sizeCclosure(cl->c.nupvalues) :
sizeLclosure(cl->l.nupvalues);
- break;
}
case LUA_TTHREAD: {
lua_State *th = gco2th(o);
@@ -306,7 +304,6 @@ static l_mem propagatemark (global_State *g) {
traversestack(g, th);
return sizeof(lua_State) + sizeof(TValue) * th->stacksize +
sizeof(CallInfo) * th->size_ci;
- break;
}
case LUA_TPROTO: {
Proto *p = gco2p(o);
@@ -318,7 +315,6 @@ static l_mem propagatemark (global_State *g) {
sizeof(int) * p->sizelineinfo +
sizeof(LocVar) * p->sizelocvars +
sizeof(TString *) * p->sizeupvalues;
- break;
}
default: lua_assert(0); return 0;
}
@@ -528,10 +524,10 @@ static void remarkupvals (global_State *g) {
static void atomic (lua_State *L) {
global_State *g = G(L);
size_t udsize; /* total size of userdata to be finalized */
- /* remark objects cautch by write barrier */
- propagateall(g);
/* remark occasional upvalues of (maybe) dead threads */
remarkupvals(g);
+ /* traverse objects cautch by write barrier and by 'remarkupvals' */
+ propagateall(g);
/* remark weak tables */
g->gray = g->weak;
g->weak = NULL;
@@ -673,12 +669,13 @@ void luaC_barrierf (lua_State *L, GCObject *o, GCObject *v) {
}
-void luaC_barrierback (lua_State *L, GCObject *o) {
+void luaC_barrierback (lua_State *L, Table *t) {
global_State *g = G(L);
+ GCObject *o = obj2gco(t);
lua_assert(isblack(o) && !isdead(g, o));
lua_assert(g->gcstate != GCSfinalize && g->gcstate != GCSpause);
black2gray(o); /* make table gray (again) */
- gco2h(o)->gclist = g->grayagain;
+ t->gclist = g->grayagain;
g->grayagain = o;
}
diff --git a/src/lgc.h b/src/lgc.h
index 4fc4a81e..5f69acb1 100644
--- a/src/lgc.h
+++ b/src/lgc.h
@@ -1,5 +1,5 @@
/*
-** $Id: lgc.h,v 2.13 2005/04/25 19:24:10 roberto Exp $
+** $Id: lgc.h,v 2.15 2005/08/24 16:15:49 roberto Exp $
** Garbage Collector
** See Copyright Notice in lua.h
*/
@@ -77,23 +77,24 @@
#define luaC_white(g) cast(lu_byte, (g)->currentwhite & WHITEBITS)
-#define luaC_checkGC(L) { if (G(L)->totalbytes >= G(L)->GCthreshold) \
+#define luaC_checkGC(L) { \
+ condhardstacktests(luaD_reallocstack(L, L->stacksize - EXTRA_STACK - 1)); \
+ if (G(L)->totalbytes >= G(L)->GCthreshold) \
luaC_step(L); }
#define luaC_barrier(L,p,v) { if (valiswhite(v) && isblack(obj2gco(p))) \
luaC_barrierf(L,obj2gco(p),gcvalue(v)); }
-#define luaC_barriert(L,p,v) { if (valiswhite(v) && isblack(obj2gco(p))) \
- luaC_barrierback(L,obj2gco(p)); }
+#define luaC_barriert(L,t,v) { if (valiswhite(v) && isblack(obj2gco(t))) \
+ luaC_barrierback(L,t); }
#define luaC_objbarrier(L,p,o) \
{ if (iswhite(obj2gco(o)) && isblack(obj2gco(p))) \
luaC_barrierf(L,obj2gco(p),obj2gco(o)); }
-#define luaC_objbarriert(L,p,o) \
- { if (iswhite(obj2gco(o)) && isblack(obj2gco(p))) \
- luaC_barrierback(L,obj2gco(p)); }
+#define luaC_objbarriert(L,t,o) \
+ { if (iswhite(obj2gco(o)) && isblack(obj2gco(t))) luaC_barrierback(L,t); }
LUAI_FUNC size_t luaC_separateudata (lua_State *L, int all);
LUAI_FUNC void luaC_callGCTM (lua_State *L);
@@ -103,7 +104,7 @@ LUAI_FUNC void luaC_fullgc (lua_State *L);
LUAI_FUNC void luaC_link (lua_State *L, GCObject *o, lu_byte tt);
LUAI_FUNC void luaC_linkupval (lua_State *L, UpVal *uv);
LUAI_FUNC void luaC_barrierf (lua_State *L, GCObject *o, GCObject *v);
-LUAI_FUNC void luaC_barrierback (lua_State *L, GCObject *o);
+LUAI_FUNC void luaC_barrierback (lua_State *L, Table *t);
#endif
diff --git a/src/linit.c b/src/linit.c
index afcd338b..d30ff1e3 100644
--- a/src/linit.c
+++ b/src/linit.c
@@ -1,5 +1,5 @@
/*
-** $Id: linit.c,v 1.11 2005/04/13 17:24:20 roberto Exp $
+** $Id: linit.c,v 1.13 2005/08/26 17:36:32 roberto Exp $
** Initialization of libraries for lua.c
** See Copyright Notice in lua.h
*/
@@ -14,7 +14,7 @@
#include "lauxlib.h"
-static const luaL_reg lualibs[] = {
+static const luaL_Reg lualibs[] = {
{"", luaopen_base},
{LUA_TABLIBNAME, luaopen_table},
{LUA_IOLIBNAME, luaopen_io},
@@ -22,13 +22,13 @@ static const luaL_reg lualibs[] = {
{LUA_STRLIBNAME, luaopen_string},
{LUA_MATHLIBNAME, luaopen_math},
{LUA_DBLIBNAME, luaopen_debug},
- {LUA_LOADLIBNAME, luaopen_loadlib},
+ {LUA_LOADLIBNAME, luaopen_package},
{NULL, NULL}
};
LUALIB_API void luaL_openlibs (lua_State *L) {
- const luaL_reg *lib = lualibs;
+ const luaL_Reg *lib = lualibs;
for (; lib->func; lib++) {
lua_pushcfunction(L, lib->func);
lua_pushstring(L, lib->name);
diff --git a/src/liolib.c b/src/liolib.c
index 1dba7eff..a7f8743f 100644
--- a/src/liolib.c
+++ b/src/liolib.c
@@ -1,5 +1,5 @@
/*
-** $Id: liolib.c,v 2.60 2005/05/16 21:19:00 roberto Exp $
+** $Id: liolib.c,v 2.67 2005/08/26 17:36:32 roberto Exp $
** Standard I/O (and system) library
** See Copyright Notice in lua.h
*/
@@ -20,8 +20,8 @@
-#define IO_INPUT 1
-#define IO_OUTPUT 2
+#define IO_INPUT 1
+#define IO_OUTPUT 2
static const char *const fnames[] = {"input", "output"};
@@ -50,17 +50,17 @@ static void fileerror (lua_State *L, int arg, const char *filename) {
}
-static FILE **topfile (lua_State *L) {
- FILE **f = (FILE **)luaL_checkudata(L, 1, LUA_FILEHANDLE);
- if (f == NULL) luaL_argerror(L, 1, "bad file");
- return f;
-}
+#define topfile(L) ((FILE **)luaL_checkudata(L, 1, LUA_FILEHANDLE))
static int io_type (lua_State *L) {
- FILE **f = (FILE **)luaL_checkudata(L, 1, LUA_FILEHANDLE);
- if (f == NULL) lua_pushnil(L);
- else if (*f == NULL)
+ void *ud;
+ luaL_checkany(L, 1);
+ ud = lua_touserdata(L, 1);
+ lua_getfield(L, LUA_REGISTRYINDEX, LUA_FILEHANDLE);
+ if (ud == NULL || !lua_getmetatable(L, 1) || !lua_rawequal(L, -2, -1))
+ lua_pushnil(L); /* not a file */
+ else if (*((FILE **)ud) == NULL)
lua_pushliteral(L, "closed file");
else
lua_pushliteral(L, "file");
@@ -91,29 +91,45 @@ static FILE **newfile (lua_State *L) {
}
+/*
+** this function has a separated environment, which defines the
+** correct __close for 'popen' files
+*/
+static int io_pclose (lua_State *L) {
+ FILE **p = topfile(L);
+ int ok = lua_pclose(L, *p);
+ if (ok) *p = NULL;
+ return pushresult(L, ok, NULL);
+}
+
+
+static int io_fclose (lua_State *L) {
+ FILE **p = topfile(L);
+ int ok = (fclose(*p) == 0);
+ if (ok) *p = NULL;
+ return pushresult(L, ok, NULL);
+}
+
+
static int aux_close (lua_State *L) {
- FILE *f = tofile(L);
- if (f == stdin || f == stdout || f == stderr)
- return 0; /* file cannot be closed */
- else {
- int ok = (fclose(f) == 0);
- if (ok)
- *(FILE **)lua_touserdata(L, 1) = NULL; /* mark file as closed */
- return ok;
- }
+ lua_getfenv(L, 1);
+ lua_getfield(L, -1, "__close");
+ return (lua_tocfunction(L, -1))(L);
}
static int io_close (lua_State *L) {
if (lua_isnone(L, 1))
lua_rawgeti(L, LUA_ENVIRONINDEX, IO_OUTPUT);
- return pushresult(L, aux_close(L), NULL);
+ tofile(L); /* make sure argument is a file */
+ return aux_close(L);
}
static int io_gc (lua_State *L) {
- FILE **f = topfile(L);
- if (*f != NULL) /* ignore closed files */
+ FILE *f = *topfile(L);
+ /* ignore closed files and standard files */
+ if (f != NULL && f != stdin && f != stdout && f != stderr)
aux_close(L);
return 0;
}
@@ -138,6 +154,15 @@ static int io_open (lua_State *L) {
}
+static int io_popen (lua_State *L) {
+ const char *filename = luaL_checkstring(L, 1);
+ const char *mode = luaL_optstring(L, 2, "r");
+ FILE **pf = newfile(L);
+ *pf = lua_popen(L, filename, mode);
+ return (*pf == NULL) ? pushresult(L, 0, filename) : 1;
+}
+
+
static int io_tmpfile (lua_State *L) {
FILE **pf = newfile(L);
*pf = tmpfile();
@@ -148,7 +173,6 @@ static int io_tmpfile (lua_State *L) {
static FILE *getiofile (lua_State *L, int findex) {
FILE *f;
lua_rawgeti(L, LUA_ENVIRONINDEX, findex);
- lua_assert(luaL_checkudata(L, -1, LUA_FILEHANDLE));
f = *(FILE **)lua_touserdata(L, -1);
if (f == NULL)
luaL_error(L, "standard %s file is closed", fnames[findex - 1]);
@@ -169,7 +193,6 @@ static int g_iofile (lua_State *L, int f, const char *mode) {
tofile(L); /* check that it's a valid file handle */
lua_pushvalue(L, 1);
}
- lua_assert(luaL_checkudata(L, -1, LUA_FILEHANDLE));
lua_rawseti(L, LUA_ENVIRONINDEX, f);
}
/* return current value */
@@ -352,7 +375,7 @@ static int io_readline (lua_State *L) {
luaL_error(L, "file is already closed");
sucess = read_line(L, f);
if (ferror(f))
- luaL_error(L, "%s", strerror(errno));
+ return luaL_error(L, "%s", strerror(errno));
if (sucess) return 1;
else { /* EOF */
if (lua_toboolean(L, lua_upvalueindex(2))) { /* generator created file? */
@@ -400,9 +423,8 @@ static int f_seek (lua_State *L) {
static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
static const char *const modenames[] = {"set", "cur", "end", NULL};
FILE *f = tofile(L);
- int op = luaL_findstring(luaL_optstring(L, 2, "cur"), modenames);
+ int op = luaL_checkoption(L, 2, "cur", modenames);
lua_Integer offset = luaL_optinteger(L, 3, 0);
- luaL_argcheck(L, op != -1, 2, "invalid mode");
op = fseek(f, offset, mode[op]);
if (op)
return pushresult(L, 0, NULL); /* error */
@@ -417,9 +439,10 @@ static int f_setvbuf (lua_State *L) {
static const int mode[] = {_IONBF, _IOFBF, _IOLBF};
static const char *const modenames[] = {"no", "full", "line", NULL};
FILE *f = tofile(L);
- int op = luaL_findstring(luaL_checkstring(L, 2), modenames);
- luaL_argcheck(L, op != -1, 2, "invalid mode");
- return pushresult(L, setvbuf(f, NULL, mode[op], 0) == 0, NULL);
+ int op = luaL_checkoption(L, 2, NULL, modenames);
+ lua_Integer sz = luaL_optinteger(L, 3, BUFSIZ);
+ int res = setvbuf(f, NULL, mode[op], sz);
+ return pushresult(L, res == 0, NULL);
}
@@ -434,13 +457,14 @@ static int f_flush (lua_State *L) {
}
-static const luaL_reg iolib[] = {
- {"input", io_input},
- {"output", io_output},
- {"lines", io_lines},
+static const luaL_Reg iolib[] = {
{"close", io_close},
{"flush", io_flush},
+ {"input", io_input},
+ {"lines", io_lines},
{"open", io_open},
+ {"output", io_output},
+ {"popen", io_popen},
{"read", io_read},
{"tmpfile", io_tmpfile},
{"type", io_type},
@@ -449,14 +473,14 @@ static const luaL_reg iolib[] = {
};
-static const luaL_reg flib[] = {
+static const luaL_Reg flib[] = {
+ {"close", io_close},
{"flush", f_flush},
- {"read", f_read},
{"lines", f_lines},
+ {"read", f_read},
{"seek", f_seek},
{"setvbuf", f_setvbuf},
{"write", f_write},
- {"close", io_close},
{"__gc", io_gc},
{"__tostring", io_tostring},
{NULL, NULL}
@@ -467,34 +491,41 @@ static void createmeta (lua_State *L) {
luaL_newmetatable(L, LUA_FILEHANDLE); /* create metatable for file handles */
lua_pushvalue(L, -1); /* push metatable */
lua_setfield(L, -2, "__index"); /* metatable.__index = metatable */
- luaL_openlib(L, NULL, flib, 0); /* file methods */
+ luaL_register(L, NULL, flib); /* file methods */
}
-static void createupval (lua_State *L) {
- lua_newtable(L);
- /* create (and set) default files */
- *newfile(L) = stdin;
- lua_rawseti(L, -2, IO_INPUT);
- *newfile(L) = stdout;
- lua_rawseti(L, -2, IO_OUTPUT);
+static void createstdfile (lua_State *L, FILE *f, int k, const char *fname) {
+ *newfile(L) = f;
+ if (k > 0) {
+ lua_pushvalue(L, -1);
+ lua_rawseti(L, LUA_ENVIRONINDEX, k);
+ }
+ lua_setfield(L, -2, fname);
}
-
LUALIB_API int luaopen_io (lua_State *L) {
createmeta(L);
- createupval(L);
- lua_pushvalue(L, -1);
+ /* create new (private) environment */
+ lua_newtable(L);
lua_replace(L, LUA_ENVIRONINDEX);
- luaL_openlib(L, LUA_IOLIBNAME, iolib, 0);
- /* put predefined file handles into `io' table */
- lua_rawgeti(L, -2, IO_INPUT); /* get current input from upval */
- lua_setfield(L, -2, "stdin"); /* io.stdin = upval[IO_INPUT] */
- lua_rawgeti(L, -2, IO_OUTPUT); /* get current output from upval */
- lua_setfield(L, -2, "stdout"); /* io.stdout = upval[IO_OUTPUT] */
- *newfile(L) = stderr;
- lua_setfield(L, -2, "stderr"); /* io.stderr = newfile(stderr) */
+ /* open library */
+ luaL_register(L, LUA_IOLIBNAME, iolib);
+ /* create (and set) default files */
+ createstdfile(L, stdin, IO_INPUT, "stdin");
+ createstdfile(L, stdout, IO_OUTPUT, "stdout");
+ createstdfile(L, stderr, 0, "stderr");
+ /* create environment for 'popen' */
+ lua_getfield(L, -1, "popen");
+ lua_newtable(L);
+ lua_pushcfunction(L, io_pclose);
+ lua_setfield(L, -2, "__close");
+ lua_setfenv(L, -2);
+ lua_pop(L, 1); /* pop 'popen' */
+ /* set default close function */
+ lua_pushcfunction(L, io_fclose);
+ lua_setfield(L, LUA_ENVIRONINDEX, "__close");
return 1;
}
diff --git a/src/llex.h b/src/llex.h
index 8bff8f43..08a0b254 100644
--- a/src/llex.h
+++ b/src/llex.h
@@ -1,5 +1,5 @@
/*
-** $Id: llex.h,v 1.54 2005/04/25 19:24:10 roberto Exp $
+** $Id: llex.h,v 1.55 2005/06/06 13:30:25 roberto Exp $
** Lexical Analyzer
** See Copyright Notice in lua.h
*/
@@ -37,7 +37,7 @@ enum RESERVED {
/* array with token `names' */
-extern const char *const luaX_tokens [];
+LUAI_DATA const char *const luaX_tokens [];
typedef union {
diff --git a/src/llimits.h b/src/llimits.h
index 7a536a16..68c28c8c 100644
--- a/src/llimits.h
+++ b/src/llimits.h
@@ -1,5 +1,5 @@
/*
-** $Id: llimits.h,v 1.65 2005/03/09 16:28:07 roberto Exp $
+** $Id: llimits.h,v 1.67 2005/08/24 16:15:49 roberto Exp $
** Limits, basic types, and some other `installation-dependent' definitions
** See Copyright Notice in lua.h
*/
@@ -93,4 +93,23 @@ typedef lu_int32 Instruction;
#endif
+#ifndef lua_lock
+#define lua_lock(L) ((void) 0)
+#define lua_unlock(L) ((void) 0)
+#endif
+
+#ifndef luai_threadyield
+#define luai_threadyield(L) {lua_unlock(L); lua_lock(L);}
+#endif
+
+
+/*
+** macro to control inclusion of some hard tests on stack reallocation
+*/
+#ifndef HARDSTACKTESTS
+#define condhardstacktests(x) ((void)0)
+#else
+#define condhardstacktests(x) x
+#endif
+
#endif
diff --git a/src/lmathlib.c b/src/lmathlib.c
index bba99b0d..d181a731 100644
--- a/src/lmathlib.c
+++ b/src/lmathlib.c
@@ -1,5 +1,5 @@
/*
-** $Id: lmathlib.c,v 1.63 2005/03/04 18:57:03 roberto Exp $
+** $Id: lmathlib.c,v 1.67 2005/08/26 17:36:32 roberto Exp $
** Standard mathematical library
** See Copyright Notice in lua.h
*/
@@ -88,7 +88,7 @@ static int math_floor (lua_State *L) {
return 1;
}
-static int math_mod (lua_State *L) {
+static int math_fmod (lua_State *L) {
lua_pushnumber(L, fmod(luaL_checknumber(L, 1), luaL_checknumber(L, 2)));
return 1;
}
@@ -212,35 +212,35 @@ static int math_randomseed (lua_State *L) {
}
-static const luaL_reg mathlib[] = {
+static const luaL_Reg mathlib[] = {
{"abs", math_abs},
- {"sin", math_sin},
- {"sinh", math_sinh},
- {"cos", math_cos},
- {"cosh", math_cosh},
- {"tan", math_tan},
- {"tanh", math_tanh},
- {"asin", math_asin},
{"acos", math_acos},
- {"atan", math_atan},
+ {"asin", math_asin},
{"atan2", math_atan2},
+ {"atan", math_atan},
{"ceil", math_ceil},
+ {"cosh", math_cosh},
+ {"cos", math_cos},
+ {"deg", math_deg},
+ {"exp", math_exp},
{"floor", math_floor},
- {"mod", math_mod},
- {"modf", math_modf},
+ {"fmod", math_fmod},
{"frexp", math_frexp},
{"ldexp", math_ldexp},
- {"sqrt", math_sqrt},
- {"min", math_min},
- {"max", math_max},
- {"log", math_log},
{"log10", math_log10},
- {"exp", math_exp},
- {"deg", math_deg},
+ {"log", math_log},
+ {"max", math_max},
+ {"min", math_min},
+ {"modf", math_modf},
{"pow", math_pow},
{"rad", math_rad},
{"random", math_random},
{"randomseed", math_randomseed},
+ {"sinh", math_sinh},
+ {"sin", math_sin},
+ {"sqrt", math_sqrt},
+ {"tanh", math_tanh},
+ {"tan", math_tan},
{NULL, NULL}
};
@@ -249,11 +249,15 @@ static const luaL_reg mathlib[] = {
** Open math library
*/
LUALIB_API int luaopen_math (lua_State *L) {
- luaL_openlib(L, LUA_MATHLIBNAME, mathlib, 0);
+ luaL_register(L, LUA_MATHLIBNAME, mathlib);
lua_pushnumber(L, PI);
lua_setfield(L, -2, "pi");
lua_pushnumber(L, HUGE_VAL);
lua_setfield(L, -2, "huge");
+#if defined(LUA_COMPAT_MOD)
+ lua_getfield(L, -1, "fmod");
+ lua_setfield(L, -2, "mod");
+#endif
return 1;
}
diff --git a/src/loadlib.c b/src/loadlib.c
index 1ae9ab57..767fdb8e 100644
--- a/src/loadlib.c
+++ b/src/loadlib.c
@@ -1,5 +1,5 @@
/*
-** $Id: loadlib.c,v 1.28 2005/05/17 19:49:15 roberto Exp $
+** $Id: loadlib.c,v 1.44 2005/09/06 17:20:25 roberto Exp $
** Dynamic library loader for Lua
** See Copyright Notice in lua.h
**
@@ -38,6 +38,13 @@
#define LIB_FAIL "open"
+/* error codes for ll_loadfunc */
+#define ERRLIB 1
+#define ERRFUNC 2
+
+#define setprogdir(L) ((void)0)
+
+
static void ll_unloadlib (void *lib);
static void *ll_load (lua_State *L, const char *path);
static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym);
@@ -88,6 +95,21 @@ static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
#include <windows.h>
+#undef setprogdir
+
+void setprogdir (lua_State *L) {
+ char buff[MAX_PATH + 1];
+ char *lb;
+ DWORD nsize = sizeof(buff)/sizeof(char);
+ DWORD n = GetModuleFileName(NULL, buff, nsize);
+ if (n == 0 || n == nsize || (lb = strrchr(buff, '\\')) == NULL)
+ luaL_error(L, "unable to get ModuleFileName");
+ *lb = '\0';
+ luaL_gsub(L, lua_tostring(L, -1), LUA_EXECDIR, buff);
+ lua_remove(L, -2); /* remove original string */
+}
+
+
static void pusherror (lua_State *L) {
int error = GetLastError();
char buffer[128];
@@ -267,96 +289,148 @@ static void **ll_register (lua_State *L, const char *path) {
*/
static int gctm (lua_State *L) {
void **lib = (void **)luaL_checkudata(L, 1, "_LOADLIB");
- if (lib) {
- if (*lib) ll_unloadlib(*lib);
- *lib = NULL; /* mark library as closed */
- }
+ if (*lib) ll_unloadlib(*lib);
+ *lib = NULL; /* mark library as closed */
return 0;
}
static int ll_loadfunc (lua_State *L, const char *path, const char *sym) {
- const char *reason;
void **reg = ll_register(L, path);
if (*reg == NULL) *reg = ll_load(L, path);
if (*reg == NULL)
- reason = LIB_FAIL;
+ return ERRLIB; /* unable to load library */
else {
lua_CFunction f = ll_sym(L, *reg, sym);
- if (f) {
- lua_pushcfunction(L, f);
- return 1; /* return function */
- }
- reason = "init";
+ if (f == NULL)
+ return ERRFUNC; /* unable to find function */
+ lua_pushcfunction(L, f);
+ return 0; /* return function */
}
- lua_pushnil(L);
- lua_insert(L, -2);
- lua_pushstring(L, reason);
- return 3; /* return nil, ll_error, reason */
}
static int ll_loadlib (lua_State *L) {
const char *path = luaL_checkstring(L, 1);
const char *init = luaL_checkstring(L, 2);
- return ll_loadfunc(L, path, init);
+ int stat = ll_loadfunc(L, path, init);
+ if (stat == 0) /* no errors? */
+ return 1; /* return the loaded function */
+ else { /* error; error message is on stack top */
+ lua_pushnil(L);
+ lua_insert(L, -2);
+ lua_pushstring(L, (stat == ERRLIB) ? LIB_FAIL : "init");
+ return 3; /* return nil, error message, and where */
+ }
}
/*
** {======================================================
-** `require' and `module' functions
+** 'require' function
** =======================================================
*/
-static int loader_Lua (lua_State *L) {
- const char *name = luaL_checkstring(L, 1);
- const char *fname = luaL_gsub(L, name, ".", LUA_DIRSEP);
- const char *path = NULL;
-#if LUA_COMPAT_PATH
- /* try first `LUA_PATH' for compatibility */
- lua_pushstring(L, "LUA_PATH");
- lua_rawget(L, LUA_GLOBALSINDEX);
+static int readable (const char *filename) {
+ FILE *f = fopen(filename, "r"); /* try to open file */
+ if (f == NULL) return 0; /* open failed */
+ fclose(f);
+ return 1;
+}
+
+
+static const char *pushnexttemplate (lua_State *L, const char *path) {
+ const char *l;
+ while (*path == *LUA_PATHSEP) path++; /* skip separators */
+ if (*path == '\0') return NULL; /* no more templates */
+ l = strchr(path, *LUA_PATHSEP); /* find next separator */
+ if (l == NULL) l = path + strlen(path);
+ lua_pushlstring(L, path, l - path); /* template */
+ return l;
+}
+
+
+static const char *findfile (lua_State *L, const char *name,
+ const char *pname) {
+ const char *path;
+ name = luaL_gsub(L, name, ".", LUA_DIRSEP);
+ lua_getfield(L, LUA_ENVIRONINDEX, pname);
path = lua_tostring(L, -1);
-#endif
- if (!path) {
- lua_pop(L, 1);
- lua_getfield(L, LUA_ENVIRONINDEX, "path");
- path = lua_tostring(L, -1);
- }
if (path == NULL)
- luaL_error(L, LUA_QL("package.path") " must be a string");
- fname = luaL_searchpath(L, fname, path);
- if (fname == NULL) return 0; /* library not found in this path */
- if (luaL_loadfile(L, fname) != 0)
- luaL_error(L, "error loading package " LUA_QS " (%s)",
- name, lua_tostring(L, -1));
+ luaL_error(L, LUA_QL("package.%s") " must be a string", pname);
+ while ((path = pushnexttemplate(L, path)) != NULL) {
+ const char *filename;
+ filename = luaL_gsub(L, lua_tostring(L, -1), LUA_PATH_MARK, name);
+ if (readable(filename)) /* does file exist and is readable? */
+ return filename; /* return that file name */
+ lua_pop(L, 2); /* remove path template and file name */
+ }
+ return NULL; /* not found */
+}
+
+
+static void loaderror (lua_State *L) {
+ luaL_error(L, "error loading module " LUA_QS " (%s)",
+ lua_tostring(L, 1), lua_tostring(L, -1));
+}
+
+
+static int loader_Lua (lua_State *L) {
+ const char *filename;
+ const char *name = luaL_checkstring(L, 1);
+ filename = findfile(L, name, "path");
+ if (filename == NULL) return 0; /* library not found in this path */
+ if (luaL_loadfile(L, filename) != 0)
+ loaderror(L);
return 1; /* library loaded successfully */
}
+static const char *mkfuncname (lua_State *L, const char *modname) {
+ const char *funcname;
+ const char *mark = strchr(modname, *LUA_IGMARK);
+ if (mark) modname = mark + 1;
+ funcname = luaL_gsub(L, modname, ".", LUA_OFSEP);
+ funcname = lua_pushfstring(L, POF"%s", funcname);
+ lua_remove(L, -2); /* remove 'gsub' result */
+ return funcname;
+}
+
+
static int loader_C (lua_State *L) {
- const char *name = luaL_checkstring(L, 1);
- const char *fname = luaL_gsub(L, name, ".", LUA_DIRSEP);
- const char *path;
const char *funcname;
- lua_getfield(L, LUA_ENVIRONINDEX, "cpath");
- path = lua_tostring(L, -1);
- if (path == NULL)
- luaL_error(L, LUA_QL("package.cpath") " must be a string");
- fname = luaL_searchpath(L, fname, path);
- if (fname == NULL) return 0; /* library not found in this path */
- funcname = luaL_gsub(L, name, ".", LUA_OFSEP);
- funcname = lua_pushfstring(L, "%s%s", POF, funcname);
- if (ll_loadfunc(L, fname, funcname) != 1)
- luaL_error(L, "error loading package " LUA_QS " (%s)",
- name, lua_tostring(L, -2));
+ const char *name = luaL_checkstring(L, 1);
+ const char *filename = findfile(L, name, "cpath");
+ if (filename == NULL) return 0; /* library not found in this path */
+ funcname = mkfuncname(L, name);
+ if (ll_loadfunc(L, filename, funcname) != 0)
+ loaderror(L);
return 1; /* library loaded successfully */
}
+static int loader_Croot (lua_State *L) {
+ const char *funcname;
+ const char *filename;
+ const char *name = luaL_checkstring(L, 1);
+ const char *p = strchr(name, '.');
+ int stat;
+ if (p == NULL) return 0; /* is root */
+ lua_pushlstring(L, name, p - name);
+ filename = findfile(L, lua_tostring(L, -1), "cpath");
+ if (filename == NULL) return 0; /* root not found */
+ funcname = mkfuncname(L, name);
+ if ((stat = ll_loadfunc(L, filename, funcname)) != 0) {
+ if (stat == ERRFUNC) return 0; /* function not found */
+ else
+ loaderror(L); /* real error */
+ }
+ return 1;
+}
+
+
static int loader_preload (lua_State *L) {
lua_getfield(L, LUA_ENVIRONINDEX, "preload");
if (!lua_istable(L, -1))
@@ -366,38 +440,58 @@ static int loader_preload (lua_State *L) {
}
+static const int sentinel = 0;
+
+
static int ll_require (lua_State *L) {
const char *name = luaL_checkstring(L, 1);
int i;
- lua_settop(L, 1);
+ lua_settop(L, 1); /* _LOADED table will be at index 2 */
lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
lua_getfield(L, 2, name);
- if (lua_toboolean(L, -1)) /* is it there? */
- return 1; /* package is already loaded; return its result */
- /* else must load it; first mark it as loaded */
- lua_pushboolean(L, 1);
- lua_setfield(L, 2, name); /* _LOADED[name] = true */
- /* iterate over available loaders */
+ if (lua_toboolean(L, -1)) { /* is it there? */
+ if (lua_touserdata(L, -1) == &sentinel) /* check loops */
+ luaL_error(L, "loop or previous error loading module " LUA_QS, name);
+ return 1; /* package is already loaded */
+ }
+ /* else must load it; iterate over available loaders */
lua_getfield(L, LUA_ENVIRONINDEX, "loaders");
if (!lua_istable(L, -1))
luaL_error(L, LUA_QL("package.loaders") " must be a table");
- for (i=1;; i++) {
+ for (i=1; ; i++) {
lua_rawgeti(L, -1, i); /* get a loader */
if (lua_isnil(L, -1))
- return luaL_error(L, "package " LUA_QS " not found", name);
+ luaL_error(L, "module " LUA_QS " not found", name);
lua_pushstring(L, name);
lua_call(L, 1, 1); /* call it */
- if (lua_isnil(L, -1)) lua_pop(L, 1);
+ if (lua_isnil(L, -1)) lua_pop(L, 1); /* did not found module */
else break; /* module loaded successfully */
}
- lua_pushvalue(L, 1); /* pass name as argument to module */
+ lua_pushlightuserdata(L, (void *)&sentinel);
+ lua_setfield(L, 2, name); /* _LOADED[name] = sentinel */
+ lua_pushstring(L, name); /* pass name as argument to module */
lua_call(L, 1, 1); /* run loaded module */
if (!lua_isnil(L, -1)) /* non-nil return? */
- lua_setfield(L, 2, name); /* update _LOADED[name] with returned value */
- lua_getfield(L, 2, name); /* return _LOADED[name] */
+ lua_setfield(L, 2, name); /* _LOADED[name] = returned value */
+ lua_getfield(L, 2, name);
+ if (lua_touserdata(L, -1) == &sentinel) { /* module did not set a value? */
+ lua_pushboolean(L, 1); /* use true as result */
+ lua_pushvalue(L, -1); /* extra copy to be returned */
+ lua_setfield(L, 2, name); /* _LOADED[name] = true */
+ }
return 1;
}
+/* }====================================================== */
+
+
+
+/*
+** {======================================================
+** 'module' function
+** =======================================================
+*/
+
static void setfenv (lua_State *L) {
lua_Debug ar;
@@ -405,49 +499,72 @@ static void setfenv (lua_State *L) {
lua_getinfo(L, "f", &ar);
lua_pushvalue(L, -2);
lua_setfenv(L, -2);
+ lua_pop(L, 1);
+}
+
+
+static void dooptions (lua_State *L, int n) {
+ int i;
+ for (i = 2; i <= n; i++) {
+ lua_pushvalue(L, i); /* get option (a function) */
+ lua_pushvalue(L, -2); /* module */
+ lua_call(L, 1, 0);
+ }
+}
+
+
+static void modinit (lua_State *L, const char *modname) {
+ const char *dot;
+ lua_pushvalue(L, -1);
+ lua_setfield(L, -2, "_M"); /* module._M = module */
+ lua_pushstring(L, modname);
+ lua_setfield(L, -2, "_NAME");
+ dot = strrchr(modname, '.'); /* look for last dot in module name */
+ if (dot == NULL) dot = modname;
+ else dot++;
+ /* set _PACKAGE as package name (full module name minus last part) */
+ lua_pushlstring(L, modname, dot - modname);
+ lua_setfield(L, -2, "_PACKAGE");
}
static int ll_module (lua_State *L) {
const char *modname = luaL_checkstring(L, 1);
- const char *dot;
- lua_settop(L, 1);
+ int loaded = lua_gettop(L) + 1; /* index of _LOADED table */
lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
- /* try to find given table */
- luaL_getfield(L, LUA_GLOBALSINDEX, modname);
- if (lua_isnil(L, -1)) { /* not found? */
+ lua_getfield(L, loaded, modname); /* get _LOADED[modname] */
+ if (!lua_istable(L, -1)) { /* not found? */
lua_pop(L, 1); /* remove previous result */
- lua_newtable(L); /* create it */
- /* register it with given name */
+ /* try global variable (and create one if it does not exist) */
+ if (luaL_findtable(L, LUA_GLOBALSINDEX, modname) != NULL)
+ return luaL_error(L, "name conflict for module " LUA_QS, modname);
lua_pushvalue(L, -1);
- luaL_setfield(L, LUA_GLOBALSINDEX, modname);
+ lua_setfield(L, loaded, modname); /* _LOADED[modname] = new table */
}
- else if (!lua_istable(L, -1))
- return luaL_error(L, "name conflict for module " LUA_QS, modname);
/* check whether table already has a _NAME field */
lua_getfield(L, -1, "_NAME");
if (!lua_isnil(L, -1)) /* is table an initialized module? */
lua_pop(L, 1);
else { /* no; initialize it */
lua_pop(L, 1);
- lua_newtable(L); /* create new metatable */
- lua_pushvalue(L, LUA_GLOBALSINDEX);
- lua_setfield(L, -2, "__index"); /* mt.__index = _G */
- lua_setmetatable(L, -2);
- lua_pushvalue(L, -1);
- lua_setfield(L, -2, "_M"); /* module._M = module */
- lua_pushstring(L, modname);
- lua_setfield(L, -2, "_NAME");
- dot = strrchr(modname, '.'); /* look for last dot in module name */
- if (dot == NULL) dot = modname;
- else dot++;
- /* set _PACKAGE as package name (full module name minus last part) */
- lua_pushlstring(L, modname, dot - modname);
- lua_setfield(L, -2, "_PACKAGE");
+ modinit(L, modname);
}
lua_pushvalue(L, -1);
- lua_setfield(L, 2, modname); /* _LOADED[modname] = new table */
setfenv(L);
+ dooptions(L, loaded - 1);
+ return 0;
+}
+
+
+static int ll_seeall (lua_State *L) {
+ luaL_checktype(L, 1, LUA_TTABLE);
+ if (!lua_getmetatable(L, 1)) {
+ lua_newtable(L); /* create new metatable */
+ lua_pushvalue(L, -1);
+ lua_setmetatable(L, 1);
+ }
+ lua_pushvalue(L, LUA_GLOBALSINDEX);
+ lua_setfield(L, -2, "__index"); /* mt.__index = _G */
return 0;
}
@@ -455,28 +572,57 @@ static int ll_module (lua_State *L) {
/* }====================================================== */
-static const luaL_reg ll_funcs[] = {
- {"require", ll_require},
+
+/* auxiliary mark (for internal use) */
+#define AUXMARK "\1"
+
+static void setpath (lua_State *L, const char *fieldname, const char *envname,
+ const char *def) {
+ const char *path = getenv(envname);
+ if (path == NULL) /* no environment variable? */
+ lua_pushstring(L, def); /* use default */
+ else {
+ /* replace ";;" by ";AUXMARK;" and then AUXMARK by default path */
+ path = luaL_gsub(L, path, LUA_PATHSEP LUA_PATHSEP,
+ LUA_PATHSEP AUXMARK LUA_PATHSEP);
+ luaL_gsub(L, path, AUXMARK, def);
+ lua_remove(L, -2);
+ }
+ setprogdir(L);
+ lua_setfield(L, -2, fieldname);
+}
+
+
+static const luaL_Reg pk_funcs[] = {
+ {"loadlib", ll_loadlib},
+ {"seeall", ll_seeall},
+ {NULL, NULL}
+};
+
+
+static const luaL_Reg ll_funcs[] = {
{"module", ll_module},
+ {"require", ll_require},
{NULL, NULL}
};
static const lua_CFunction loaders[] =
- {loader_preload, loader_C, loader_Lua, NULL};
+ {loader_preload, loader_Lua, loader_C, loader_Croot, NULL};
-LUALIB_API int luaopen_loadlib (lua_State *L) {
- const char *path;
+LUALIB_API int luaopen_package (lua_State *L) {
int i;
/* create new type _LOADLIB */
luaL_newmetatable(L, "_LOADLIB");
lua_pushcfunction(L, gctm);
lua_setfield(L, -2, "__gc");
/* create `package' table */
- lua_newtable(L);
- lua_pushvalue(L, -1);
- lua_setglobal(L, LUA_LOADLIBNAME);
+ luaL_register(L, LUA_LOADLIBNAME, pk_funcs);
+#if defined(LUA_COMPAT_LOADLIB)
+ lua_getfield(L, -1, "loadlib");
+ lua_setfield(L, LUA_GLOBALSINDEX, "loadlib");
+#endif
lua_pushvalue(L, -1);
lua_setfield(L, LUA_REGISTRYINDEX, "_PACKAGE");
lua_pushvalue(L, -1);
@@ -488,33 +634,22 @@ LUALIB_API int luaopen_loadlib (lua_State *L) {
lua_pushcfunction(L, loaders[i]);
lua_rawseti(L, -2, i+1);
}
- /* put it in field `loaders' */
- lua_setfield(L, -2, "loaders");
- /* set field `path' */
- path = getenv(LUA_PATH);
- if (path == NULL) path = LUA_PATH_DEFAULT;
- lua_pushstring(L, path);
- lua_setfield(L, -2, "path");
- /* set field `cpath' */
- path = getenv(LUA_CPATH);
- if (path == NULL) path = LUA_CPATH_DEFAULT;
- lua_pushstring(L, path);
- lua_setfield(L, -2, "cpath");
+ lua_setfield(L, -2, "loaders"); /* put it in field `loaders' */
+ setpath(L, "path", LUA_PATH, LUA_PATH_DEFAULT); /* set field `path' */
+ setpath(L, "cpath", LUA_CPATH, LUA_CPATH_DEFAULT); /* set field `cpath' */
+ /* store config information */
+ lua_pushstring(L, LUA_DIRSEP "\n" LUA_PATHSEP "\n" LUA_PATH_MARK "\n"
+ LUA_EXECDIR "\n" LUA_IGMARK);
+ lua_setfield(L, -2, "config");
/* set field `loaded' */
lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
lua_setfield(L, -2, "loaded");
/* set field `preload' */
lua_newtable(L);
lua_setfield(L, -2, "preload");
- /* create `loadlib' function */
- lua_pushcfunction(L, ll_loadlib);
-#if LUA_COMPAT_LOADLIB
- lua_pushvalue(L, -1);
- lua_setfield(L, LUA_GLOBALSINDEX, "loadlib");
-#endif
- lua_setfield(L, -2, "loadlib");
lua_pushvalue(L, LUA_GLOBALSINDEX);
- luaL_openlib(L, NULL, ll_funcs, 0); /* open lib into global table */
- return 1;
+ luaL_register(L, NULL, ll_funcs); /* open lib into global table */
+ lua_pop(L, 1);
+ return 1; /* return 'package' table */
}
diff --git a/src/lobject.c b/src/lobject.c
index 98b08351..9aa9760f 100644
--- a/src/lobject.c
+++ b/src/lobject.c
@@ -1,5 +1,5 @@
/*
-** $Id: lobject.c,v 2.13 2005/05/16 21:19:00 roberto Exp $
+** $Id: lobject.c,v 2.18 2005/08/01 04:22:23 roberto Exp $
** Some generic functions over Lua objects
** See Copyright Notice in lua.h
*/
@@ -75,7 +75,7 @@ int luaO_rawequalObj (const TValue *t1, const TValue *t2) {
case LUA_TNIL:
return 1;
case LUA_TNUMBER:
- return luai_numeq(nvalue(t1), nvalue(t2));
+ return luai_numeq(L, nvalue(t1), nvalue(t2));
case LUA_TBOOLEAN:
return bvalue(t1) == bvalue(t2); /* boolean true must be 1 !! */
case LUA_TLIGHTUSERDATA:
@@ -89,11 +89,11 @@ int luaO_rawequalObj (const TValue *t1, const TValue *t2) {
int luaO_str2d (const char *s, lua_Number *result) {
char *endptr;
- lua_Number res = lua_str2number(s, &endptr);
- if (endptr == s) return 0; /* no conversion */
+ *result = lua_str2number(s, &endptr);
+ if (endptr == s) return 0; /* conversion failed */
+ if (*endptr == '\0') return 1; /* most common case */
while (isspace(cast(unsigned char, *endptr))) endptr++;
if (*endptr != '\0') return 0; /* invalid trailing characters? */
- *result = res;
return 1;
}
@@ -116,7 +116,9 @@ const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) {
incr_top(L);
switch (*(e+1)) {
case 's': {
- pushstr(L, va_arg(argp, char *));
+ const char *s = va_arg(argp, char *);
+ if (s == NULL) s = "(null)";
+ pushstr(L, s);
break;
}
case 'c': {
@@ -159,7 +161,7 @@ const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) {
fmt = e+2;
}
pushstr(L, fmt);
- luaV_concat(L, n+1, L->top - L->base - 1);
+ luaV_concat(L, n+1, cast(int, L->top - L->base) - 1);
L->top -= n;
return svalue(L->top - 1);
}
@@ -175,26 +177,26 @@ const char *luaO_pushfstring (lua_State *L, const char *fmt, ...) {
}
-void luaO_chunkid (char *out, const char *source, int bufflen) {
+void luaO_chunkid (char *out, const char *source, size_t bufflen) {
if (*source == '=') {
strncpy(out, source+1, bufflen); /* remove first char */
out[bufflen-1] = '\0'; /* ensures null termination */
}
else { /* out = "source", or "...source" */
if (*source == '@') {
- int l;
+ size_t l;
source++; /* skip the `@' */
bufflen -= sizeof(" '...' ");
l = strlen(source);
strcpy(out, "");
- if (l>bufflen) {
+ if (l > bufflen) {
source += (l-bufflen); /* get last part of file name */
strcat(out, "...");
}
strcat(out, source);
}
else { /* out = [string "string"] */
- int len = strcspn(source, "\n\r"); /* stop at first newline */
+ size_t len = strcspn(source, "\n\r"); /* stop at first newline */
bufflen -= sizeof(" [string \"...\"] ");
if (len > bufflen) len = bufflen;
strcpy(out, "[string \"");
diff --git a/src/lobject.h b/src/lobject.h
index 4a77a539..1709fa3c 100644
--- a/src/lobject.h
+++ b/src/lobject.h
@@ -1,5 +1,5 @@
/*
-** $Id: lobject.h,v 2.13 2005/05/05 20:47:02 roberto Exp $
+** $Id: lobject.h,v 2.17 2005/06/13 14:19:00 roberto Exp $
** Type definitions for Lua objects
** See Copyright Notice in lua.h
*/
@@ -17,15 +17,17 @@
/* tags for values visible from Lua */
-#define NUM_TAGS LUA_TTHREAD
+#define LAST_TAG LUA_TTHREAD
+
+#define NUM_TAGS (LAST_TAG+1)
/*
** Extra tags for non-values
*/
-#define LUA_TPROTO (NUM_TAGS+1)
-#define LUA_TUPVAL (NUM_TAGS+2)
-#define LUA_TDEADKEY (NUM_TAGS+3)
+#define LUA_TPROTO (LAST_TAG+1)
+#define LUA_TUPVAL (LAST_TAG+2)
+#define LUA_TDEADKEY (LAST_TAG+3)
/*
@@ -254,8 +256,10 @@ typedef struct Proto {
} Proto;
-/* mask for new-style vararg */
-#define NEWSTYLEVARARG 2
+/* masks for new-style vararg */
+#define VARARG_HASARG 1
+#define VARARG_ISVARARG 2
+#define VARARG_NEEDSARG 4
typedef struct LocVar {
@@ -357,7 +361,7 @@ typedef struct Table {
-extern const TValue luaO_nilobject;
+LUAI_DATA const TValue luaO_nilobject;
#define ceillog2(x) (luaO_log2((x)-1) + 1)
@@ -369,7 +373,8 @@ LUAI_FUNC int luaO_str2d (const char *s, lua_Number *result);
LUAI_FUNC const char *luaO_pushvfstring (lua_State *L, const char *fmt,
va_list argp);
LUAI_FUNC const char *luaO_pushfstring (lua_State *L, const char *fmt, ...);
-LUAI_FUNC void luaO_chunkid (char *out, const char *source, int len);
+LUAI_FUNC void luaO_chunkid (char *out, const char *source, size_t len);
#endif
+
diff --git a/src/lopcodes.c b/src/lopcodes.c
index 46b30ba9..5e3bc5f7 100644
--- a/src/lopcodes.c
+++ b/src/lopcodes.c
@@ -1,5 +1,5 @@
/*
-** $Id: lopcodes.c,v 1.33 2005/05/04 20:42:28 roberto Exp $
+** $Id: lopcodes.c,v 1.35 2005/08/29 20:49:21 roberto Exp $
** See Copyright Notice in lua.h
*/
@@ -36,13 +36,14 @@ const char *const luaP_opnames[NUM_OPCODES+1] = {
"POW",
"UNM",
"NOT",
- "SIZ",
+ "LEN",
"CONCAT",
"JMP",
"EQ",
"LT",
"LE",
"TEST",
+ "TESTSET",
"CALL",
"TAILCALL",
"RETURN",
@@ -81,13 +82,14 @@ const lu_byte luaP_opmodes[NUM_OPCODES] = {
,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_POW */
,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_UNM */
,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_NOT */
- ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_SIZ */
+ ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_LEN */
,opmode(0, 1, OpArgR, OpArgR, iABC) /* OP_CONCAT */
,opmode(0, 0, OpArgR, OpArgN, iAsBx) /* OP_JMP */
,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_EQ */
,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_LT */
,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_LE */
- ,opmode(1, 1, OpArgR, OpArgU, iABC) /* OP_TEST */
+ ,opmode(1, 0, OpArgR, OpArgU, iABC) /* OP_TEST */
+ ,opmode(1, 1, OpArgR, OpArgU, iABC) /* OP_TESTSET */
,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_CALL */
,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_TAILCALL */
,opmode(0, 0, OpArgU, OpArgN, iABC) /* OP_RETURN */
diff --git a/src/lopcodes.h b/src/lopcodes.h
index 77f60c00..b08b6798 100644
--- a/src/lopcodes.h
+++ b/src/lopcodes.h
@@ -1,5 +1,5 @@
/*
-** $Id: lopcodes.h,v 1.119 2005/05/04 20:42:28 roberto Exp $
+** $Id: lopcodes.h,v 1.122 2005/08/29 20:49:21 roberto Exp $
** Opcodes for Lua virtual machine
** See Copyright Notice in lua.h
*/
@@ -176,7 +176,7 @@ OP_MOD,/* A B C R(A) := RK(B) % RK(C) */
OP_POW,/* A B C R(A) := RK(B) ^ RK(C) */
OP_UNM,/* A B R(A) := -R(B) */
OP_NOT,/* A B R(A) := not R(B) */
-OP_SIZ,/* A B R(A) := size of R(B) */
+OP_LEN,/* A B R(A) := length of R(B) */
OP_CONCAT,/* A B C R(A) := R(B).. ... ..R(C) */
@@ -186,7 +186,8 @@ OP_EQ,/* A B C if ((RK(B) == RK(C)) ~= A) then pc++ */
OP_LT,/* A B C if ((RK(B) < RK(C)) ~= A) then pc++ */
OP_LE,/* A B C if ((RK(B) <= RK(C)) ~= A) then pc++ */
-OP_TEST,/* A B C if (R(B) <=> C) then R(A) := R(B) else pc++ */
+OP_TEST,/* A C if not (R(A) <=> C) then pc++ */
+OP_TESTSET,/* A B C if (R(B) <=> C) then R(A) := R(B) else pc++ */
OP_CALL,/* A B C R(A), ... ,R(A+C-2) := R(A)(R(A+1), ... ,R(A+B-1)) */
OP_TAILCALL,/* A B C return R(A)(R(A+1), ... ,R(A+B-1)) */
@@ -248,7 +249,7 @@ enum OpArgMask {
OpArgK /* argument is a constant or register/constant */
};
-extern const lu_byte luaP_opmodes[NUM_OPCODES];
+LUAI_DATA const lu_byte luaP_opmodes[NUM_OPCODES];
#define getOpMode(m) (cast(enum OpMode, luaP_opmodes[m] & 3))
#define getBMode(m) (cast(enum OpArgMask, (luaP_opmodes[m] >> 4) & 3))
@@ -257,7 +258,7 @@ extern const lu_byte luaP_opmodes[NUM_OPCODES];
#define testTMode(m) (luaP_opmodes[m] & (1 << 7))
-extern const char *const luaP_opnames[NUM_OPCODES+1]; /* opcode names */
+LUAI_DATA const char *const luaP_opnames[NUM_OPCODES+1]; /* opcode names */
/* number of list items to accumulate before a SETLIST instruction */
diff --git a/src/loslib.c b/src/loslib.c
index 52532143..4cee7ba5 100644
--- a/src/loslib.c
+++ b/src/loslib.c
@@ -1,5 +1,5 @@
/*
-** $Id: loslib.c,v 1.9 2005/05/17 19:49:15 roberto Exp $
+** $Id: loslib.c,v 1.13 2005/09/09 18:22:46 roberto Exp $
** Standard Operating System library
** See Copyright Notice in lua.h
*/
@@ -93,6 +93,8 @@ static void setfield (lua_State *L, const char *key, int value) {
}
static void setboolfield (lua_State *L, const char *key, int value) {
+ if (value < 0) /* undefined? */
+ return; /* does not set field */
lua_pushboolean(L, value);
lua_setfield(L, -2, key);
}
@@ -197,9 +199,8 @@ static int io_setloc (lua_State *L) {
static const char *const catnames[] = {"all", "collate", "ctype", "monetary",
"numeric", "time", NULL};
const char *l = lua_tostring(L, 1);
- int op = luaL_findstring(luaL_optstring(L, 2, "all"), catnames);
+ int op = luaL_checkoption(L, 2, "all", catnames);
luaL_argcheck(L, l || lua_isnoneornil(L, 1), 1, "string expected");
- luaL_argcheck(L, op != -1, 2, "invalid option");
lua_pushstring(L, setlocale(cat[op], l));
return 1;
}
@@ -210,7 +211,7 @@ static int io_exit (lua_State *L) {
return 0; /* to avoid warnings */
}
-static const luaL_reg syslib[] = {
+static const luaL_Reg syslib[] = {
{"clock", io_clock},
{"date", io_date},
{"difftime", io_difftime},
@@ -230,7 +231,7 @@ static const luaL_reg syslib[] = {
LUALIB_API int luaopen_os (lua_State *L) {
- luaL_openlib(L, LUA_OSLIBNAME, syslib, 0);
+ luaL_register(L, LUA_OSLIBNAME, syslib);
return 1;
}
diff --git a/src/lparser.c b/src/lparser.c
index 54facfc4..91dc4fff 100644
--- a/src/lparser.c
+++ b/src/lparser.c
@@ -1,5 +1,5 @@
/*
-** $Id: lparser.c,v 2.27 2005/05/17 19:49:15 roberto Exp $
+** $Id: lparser.c,v 2.35 2005/08/29 20:49:21 roberto Exp $
** Lua Parser
** See Copyright Notice in lua.h
*/
@@ -239,35 +239,35 @@ static void markupval (FuncState *fs, int level) {
}
-static void singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) {
- if (fs == NULL) /* no more levels? */
+static int singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) {
+ if (fs == NULL) { /* no more levels? */
init_exp(var, VGLOBAL, NO_REG); /* default is global variable */
+ return VGLOBAL;
+ }
else {
int v = searchvar(fs, n); /* look up at current level */
if (v >= 0) {
init_exp(var, VLOCAL, v);
if (!base)
markupval(fs, v); /* local will be used as an upval */
+ return VLOCAL;
}
else { /* not found at current level; try upper one */
- singlevaraux(fs->prev, n, var, 0);
- if (var->k == VGLOBAL) {
- if (base)
- var->info = luaK_stringK(fs, n); /* info points to global name */
- }
- else { /* LOCAL or UPVAL */
- var->info = indexupvalue(fs, n, var);
- var->k = VUPVAL; /* upvalue in this level */
- }
+ if (singlevaraux(fs->prev, n, var, 0) == VGLOBAL)
+ return VGLOBAL;
+ var->info = indexupvalue(fs, n, var); /* else was LOCAL or UPVAL */
+ var->k = VUPVAL; /* upvalue in this level */
+ return VUPVAL;
}
}
}
-static TString *singlevar (LexState *ls, expdesc *var, int base) {
+static void singlevar (LexState *ls, expdesc *var) {
TString *varname = str_checkname(ls);
- singlevaraux(ls->fs, varname, var, base);
- return varname;
+ FuncState *fs = ls->fs;
+ if (singlevaraux(fs, varname, var, 1) == VGLOBAL)
+ var->info = luaK_stringK(fs, varname); /* info points to global name */
}
@@ -300,7 +300,7 @@ static void enterlevel (LexState *ls) {
#define leavelevel(ls) ((ls)->L->nCcalls--)
-static void enterblock (FuncState *fs, BlockCnt *bl, int isbreakable) {
+static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isbreakable) {
bl->breaklist = NO_JUMP;
bl->isbreakable = isbreakable;
bl->nactvar = fs->nactvar;
@@ -317,6 +317,7 @@ static void leaveblock (FuncState *fs) {
removevars(fs->ls, bl->nactvar);
if (bl->upval)
luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0);
+ lua_assert(!bl->isbreakable || !bl->upval); /* loops have no body */
lua_assert(bl->nactvar == fs->nactvar);
fs->freereg = fs->nactvar; /* free registers */
luaK_patchtohere(fs, bl->breaklist);
@@ -374,7 +375,7 @@ static void close_func (LexState *ls) {
FuncState *fs = ls->fs;
Proto *f = fs->f;
removevars(ls, 0);
- luaK_codeABC(fs, OP_RETURN, 0, 1, 0); /* final return */
+ luaK_ret(fs, 0, 0); /* final return */
luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction);
f->sizecode = fs->pc;
luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->pc, int);
@@ -402,7 +403,7 @@ Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, const char *name) {
lexstate.buff = buff;
luaX_setinput(L, &lexstate, z, luaS_new(L, name));
open_func(&lexstate, &funcstate);
- funcstate.f->is_vararg = NEWSTYLEVARARG;
+ funcstate.f->is_vararg = VARARG_ISVARARG; /* main func. is always vararg */
next(&lexstate); /* read first token */
chunk(&lexstate);
check(&lexstate, TK_EOS);
@@ -525,7 +526,6 @@ static void constructor (LexState *ls, expdesc *t) {
checknext(ls, '{');
do {
lua_assert(cc.v.k == VVOID || cc.tostore > 0);
- testnext(ls, ';'); /* compatibility only */
if (ls->t.token == '}') break;
closelistfield(fs, &cc);
switch(ls->t.token) {
@@ -572,9 +572,12 @@ static void parlist (LexState *ls) {
}
case TK_DOTS: { /* param -> `...' */
next(ls);
+#if defined(LUA_COMPAT_VARARG)
/* use `arg' as default name */
new_localvarliteral(ls, "arg", nparams++);
- f->is_vararg = 1;
+ f->is_vararg = VARARG_HASARG | VARARG_NEEDSARG;
+#endif
+ f->is_vararg |= VARARG_ISVARARG;
break;
}
default: luaX_syntaxerror(ls, "<name> or " LUA_QL("...") " expected");
@@ -582,7 +585,7 @@ static void parlist (LexState *ls) {
} while (!f->is_vararg && testnext(ls, ','));
}
adjustlocalvars(ls, nparams);
- f->numparams = fs->nactvar - f->is_vararg;
+ f->numparams = fs->nactvar - (f->is_vararg & VARARG_HASARG);
luaK_reserveregs(fs, fs->nactvar); /* reserve register for parameters */
}
@@ -690,7 +693,7 @@ static void prefixexp (LexState *ls, expdesc *v) {
return;
}
case TK_NAME: {
- singlevar(ls, v, 1);
+ singlevar(ls, v);
return;
}
default: {
@@ -766,7 +769,7 @@ static void simpleexp (LexState *ls, expdesc *v) {
FuncState *fs = ls->fs;
check_condition(ls, fs->f->is_vararg,
"cannot use " LUA_QL("...") " outside a vararg function");
- fs->f->is_vararg = NEWSTYLEVARARG;
+ fs->f->is_vararg &= ~VARARG_NEEDSARG; /* don't need 'arg' */
init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 1, 0));
break;
}
@@ -792,7 +795,7 @@ static UnOpr getunopr (int op) {
switch (op) {
case TK_NOT: return OPR_NOT;
case '-': return OPR_MINUS;
- case '*': return OPR_SIZE;
+ case '#': return OPR_LEN;
default: return OPR_NOUNOPR;
}
}
@@ -979,78 +982,68 @@ static int cond (LexState *ls) {
expr(ls, &v); /* read condition */
if (v.k == VNIL) v.k = VFALSE; /* `falses' are all equal here */
luaK_goiftrue(ls->fs, &v);
- luaK_patchtohere(ls->fs, v.t);
return v.f;
}
-/*
-** The while statement optimizes its code by coding the condition
-** after its body (and thus avoiding one jump in the loop).
-*/
-
+static void breakstat (LexState *ls) {
+ FuncState *fs = ls->fs;
+ BlockCnt *bl = fs->bl;
+ int upval = 0;
+ while (bl && !bl->isbreakable) {
+ upval |= bl->upval;
+ bl = bl->previous;
+ }
+ if (!bl)
+ luaX_syntaxerror(ls, "no loop to break");
+ if (upval)
+ luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0);
+ luaK_concat(fs, &bl->breaklist, luaK_jump(fs));
+}
-/*
-** the call `luaK_goiffalse' may grow the size of an expression by
-** at most this:
-*/
-#define EXTRAEXP 5
static void whilestat (LexState *ls, int line) {
/* whilestat -> WHILE cond DO block END */
- Instruction codeexp[LUAI_MAXEXPWHILE + EXTRAEXP];
- int lineexp;
- int i;
- int sizeexp;
FuncState *fs = ls->fs;
- int whileinit, blockinit, expinit;
- expdesc v;
+ int whileinit;
+ int condexit;
BlockCnt bl;
next(ls); /* skip WHILE */
- whileinit = luaK_jump(fs); /* jump to condition (which will be moved) */
- expinit = luaK_getlabel(fs);
- expr(ls, &v); /* parse condition */
- if (v.k == VK) v.k = VTRUE; /* `trues' are all equal here */
- lineexp = ls->linenumber;
- luaK_goiffalse(fs, &v);
- luaK_concat(fs, &v.f, fs->jpc);
- fs->jpc = NO_JUMP;
- sizeexp = fs->pc - expinit; /* size of expression code */
- if (sizeexp > LUAI_MAXEXPWHILE)
- luaX_syntaxerror(ls, LUA_QL("while") " condition too complex");
- for (i = 0; i < sizeexp; i++) /* save `exp' code */
- codeexp[i] = fs->f->code[expinit + i];
- fs->pc = expinit; /* remove `exp' code */
+ whileinit = luaK_getlabel(fs);
+ condexit = cond(ls);
enterblock(fs, &bl, 1);
checknext(ls, TK_DO);
- blockinit = luaK_getlabel(fs);
block(ls);
- luaK_patchtohere(fs, whileinit); /* initial jump jumps to here */
- /* move `exp' back to code */
- if (v.t != NO_JUMP) v.t += fs->pc - expinit;
- if (v.f != NO_JUMP) v.f += fs->pc - expinit;
- for (i=0; i<sizeexp; i++)
- luaK_code(fs, codeexp[i], lineexp);
+ luaK_patchlist(fs, luaK_jump(fs), whileinit);
check_match(ls, TK_END, TK_WHILE, line);
leaveblock(fs);
- luaK_patchlist(fs, v.t, blockinit); /* true conditions go back to loop */
- luaK_patchtohere(fs, v.f); /* false conditions finish the loop */
+ luaK_patchtohere(fs, condexit); /* false conditions finish the loop */
}
static void repeatstat (LexState *ls, int line) {
/* repeatstat -> REPEAT block UNTIL cond */
+ int condexit;
FuncState *fs = ls->fs;
int repeat_init = luaK_getlabel(fs);
- int flist;
- BlockCnt bl;
- enterblock(fs, &bl, 1);
- next(ls);
- block(ls);
+ BlockCnt bl1, bl2;
+ enterblock(fs, &bl1, 1); /* loop block */
+ enterblock(fs, &bl2, 0); /* scope block */
+ next(ls); /* skip REPEAT */
+ chunk(ls);
check_match(ls, TK_UNTIL, TK_REPEAT, line);
- flist = cond(ls);
- luaK_patchlist(fs, flist, repeat_init);
- leaveblock(fs);
+ condexit = cond(ls); /* read condition (inside scope block) */
+ if (!bl2.upval) { /* no upvalues? */
+ leaveblock(fs); /* finish scope */
+ luaK_patchlist(ls->fs, condexit, repeat_init); /* close the loop */
+ }
+ else { /* complete semantics when there are upvalues */
+ breakstat(ls); /* if condition then break */
+ luaK_patchtohere(ls->fs, condexit); /* else... */
+ leaveblock(fs); /* finish scope... */
+ luaK_patchlist(ls->fs, luaK_jump(fs), repeat_init); /* and repeat */
+ }
+ leaveblock(fs); /* finish loop */
}
@@ -1150,12 +1143,12 @@ static void forstat (LexState *ls, int line) {
static int test_then_block (LexState *ls) {
/* test_then_block -> [IF | ELSEIF] cond THEN block */
- int flist;
+ int condexit;
next(ls); /* skip IF or ELSEIF */
- flist = cond(ls);
+ condexit = cond(ls);
checknext(ls, TK_THEN);
block(ls); /* `then' part */
- return flist;
+ return condexit;
}
@@ -1219,7 +1212,7 @@ static void localstat (LexState *ls) {
static int funcname (LexState *ls, expdesc *v) {
/* funcname -> NAME {field} [`:' NAME] */
int needself = 0;
- singlevar(ls, v, 1);
+ singlevar(ls, v);
while (ls->t.token == '.')
field(ls, v);
if (ls->t.token == ':') {
@@ -1285,25 +1278,7 @@ static void retstat (LexState *ls) {
}
}
}
- luaK_codeABC(fs, OP_RETURN, first, nret+1, 0);
-}
-
-
-static void breakstat (LexState *ls) {
- /* stat -> BREAK */
- FuncState *fs = ls->fs;
- BlockCnt *bl = fs->bl;
- int upval = 0;
- next(ls); /* skip BREAK */
- while (bl && !bl->isbreakable) {
- upval |= bl->upval;
- bl = bl->previous;
- }
- if (!bl)
- luaX_syntaxerror(ls, "no loop to break");
- if (upval)
- luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0);
- luaK_concat(fs, &bl->breaklist, luaK_jump(fs));
+ luaK_ret(fs, first, nret);
}
@@ -1349,6 +1324,7 @@ static int statement (LexState *ls) {
return 1; /* must be last statement */
}
case TK_BREAK: { /* stat -> breakstat */
+ next(ls); /* skip BREAK */
breakstat(ls);
return 1; /* must be last statement */
}
diff --git a/src/lstate.c b/src/lstate.c
index 41162dac..2a4ace12 100644
--- a/src/lstate.c
+++ b/src/lstate.c
@@ -1,5 +1,5 @@
/*
-** $Id: lstate.c,v 2.31 2005/05/05 15:34:03 roberto Exp $
+** $Id: lstate.c,v 2.33 2005/08/25 15:39:16 roberto Exp $
** Global State
** See Copyright Notice in lua.h
*/
@@ -72,7 +72,6 @@ static void f_luaopen (lua_State *L, void *ud) {
UNUSED(ud);
stack_init(L, L); /* init stack */
sethvalue(L, gt(L), luaH_new(L, 0, 20)); /* table of globals */
- hvalue(gt(L))->metatable = luaH_new(L, 0, 0); /* globals metatable */
sethvalue(L, registry(L), luaH_new(L, 6, 20)); /* registry */
luaS_resize(L, MINSTRTABSIZE); /* initial size of string table */
luaT_init(L);
@@ -83,7 +82,7 @@ static void f_luaopen (lua_State *L, void *ud) {
static void preinit_state (lua_State *L, global_State *g) {
- L->l_G = g;
+ G(L) = g;
L->stack = NULL;
L->stacksize = 0;
L->errorJmp = NULL;
diff --git a/src/lstate.h b/src/lstate.h
index 7dafa4d5..e8bc15ab 100644
--- a/src/lstate.h
+++ b/src/lstate.h
@@ -1,5 +1,5 @@
/*
-** $Id: lstate.h,v 2.21 2005/05/05 15:34:03 roberto Exp $
+** $Id: lstate.h,v 2.23 2005/07/09 13:22:34 roberto Exp $
** Global State
** See Copyright Notice in lua.h
*/
@@ -19,10 +19,10 @@ struct lua_longjmp; /* defined in ldo.c */
/* table of globals */
-#define gt(L) (&L->_gt)
+#define gt(L) (&L->l_gt)
/* registry */
-#define registry(L) (&G(L)->_registry)
+#define registry(L) (&G(L)->l_registry)
/* extra stack space to handle TM calls and some other extras */
@@ -86,7 +86,7 @@ typedef struct global_State {
int gcpause; /* size of pause between successive GCs */
int gcstepmul; /* GC `granularity' */
lua_CFunction panic; /* to be called in unprotected errors */
- TValue _registry;
+ TValue l_registry;
struct lua_State *mainthread;
UpVal uvhead; /* head of double-linked list of all open upvalues */
struct Table *mt[NUM_TAGS]; /* metatables for basic types */
@@ -117,7 +117,7 @@ struct lua_State {
int basehookcount;
int hookcount;
lua_Hook hook;
- TValue _gt; /* table of globals */
+ TValue l_gt; /* table of globals */
TValue env; /* temporary place for environments */
GCObject *openupval; /* list of open upvalues in this stack */
GCObject *gclist;
diff --git a/src/lstrlib.c b/src/lstrlib.c
index 4929a27c..4cf5836a 100644
--- a/src/lstrlib.c
+++ b/src/lstrlib.c
@@ -1,5 +1,5 @@
/*
-** $Id: lstrlib.c,v 1.115 2005/05/17 19:49:15 roberto Exp $
+** $Id: lstrlib.c,v 1.123 2005/08/26 17:36:32 roberto Exp $
** Standard library for string operations and pattern-matching
** See Copyright Notice in lua.h
*/
@@ -58,7 +58,7 @@ static int str_reverse (lua_State *L) {
luaL_Buffer b;
const char *s = luaL_checklstring(L, 1, &l);
luaL_buffinit(L, &b);
- while (l--) luaL_putchar(&b, s[l]);
+ while (l--) luaL_addchar(&b, s[l]);
luaL_pushresult(&b);
return 1;
}
@@ -71,7 +71,7 @@ static int str_lower (lua_State *L) {
const char *s = luaL_checklstring(L, 1, &l);
luaL_buffinit(L, &b);
for (i=0; i<l; i++)
- luaL_putchar(&b, tolower(uchar(s[i])));
+ luaL_addchar(&b, tolower(uchar(s[i])));
luaL_pushresult(&b);
return 1;
}
@@ -84,7 +84,7 @@ static int str_upper (lua_State *L) {
const char *s = luaL_checklstring(L, 1, &l);
luaL_buffinit(L, &b);
for (i=0; i<l; i++)
- luaL_putchar(&b, toupper(uchar(s[i])));
+ luaL_addchar(&b, toupper(uchar(s[i])));
luaL_pushresult(&b);
return 1;
}
@@ -127,7 +127,7 @@ static int str_char (lua_State *L) {
for (i=1; i<=n; i++) {
int c = luaL_checkint(L, i);
luaL_argcheck(L, uchar(c) == c, i, "invalid value");
- luaL_putchar(&b, uchar(c));
+ luaL_addchar(&b, uchar(c));
}
luaL_pushresult(&b);
return 1;
@@ -461,7 +461,7 @@ static const char *lmemfind (const char *s1, size_t l1,
static void push_onecapture (MatchState *ms, int i) {
- int l = ms->capture[i].len;
+ ptrdiff_t l = ms->capture[i].len;
if (l == CAP_UNFINISHED) luaL_error(ms->L, "unfinished capture");
if (l == CAP_POSITION)
lua_pushinteger(ms->L, ms->capture[i].init - ms->src_init + 1);
@@ -485,15 +485,15 @@ static int push_captures (MatchState *ms, const char *s, const char *e) {
}
-static int str_find (lua_State *L) {
+static int str_find_aux (lua_State *L, int find) {
size_t l1, l2;
const char *s = luaL_checklstring(L, 1, &l1);
const char *p = luaL_checklstring(L, 2, &l2);
ptrdiff_t init = posrelat(luaL_optinteger(L, 3, 1), l1) - 1;
if (init < 0) init = 0;
else if ((size_t)(init) > l1) init = (ptrdiff_t)l1;
- if (lua_toboolean(L, 4) || /* explicit request? */
- strpbrk(p, SPECIALS) == NULL) { /* or no special characters? */
+ if (find && (lua_toboolean(L, 4) || /* explicit request? */
+ strpbrk(p, SPECIALS) == NULL)) { /* or no special characters? */
/* do a plain search */
const char *s2 = lmemfind(s+init, l1-init, p, l2);
if (s2) {
@@ -513,18 +513,37 @@ static int str_find (lua_State *L) {
const char *res;
ms.level = 0;
if ((res=match(&ms, s1, p)) != NULL) {
- lua_pushinteger(L, s1-s+1); /* start */
- lua_pushinteger(L, res-s); /* end */
- return push_captures(&ms, NULL, 0) + 2;
+ if (find) {
+ lua_pushinteger(L, s1-s+1); /* start */
+ lua_pushinteger(L, res-s); /* end */
+#if defined(LUA_COMPAT_FIND)
+ return push_captures(&ms, NULL, 0) + 2;
+#else
+ return 2;
+#endif
+
+ }
+ else
+ return push_captures(&ms, s1, res);
}
- } while (s1++<ms.src_end && !anchor);
+ } while (s1++ < ms.src_end && !anchor);
}
lua_pushnil(L); /* not found */
return 1;
}
-static int gfind_aux (lua_State *L) {
+static int str_find (lua_State *L) {
+ return str_find_aux(L, 1);
+}
+
+
+static int str_match (lua_State *L) {
+ return str_find_aux(L, 0);
+}
+
+
+static int gmatch_aux (lua_State *L) {
MatchState ms;
size_t ls;
const char *s = lua_tolstring(L, lua_upvalueindex(1), &ls);
@@ -539,7 +558,7 @@ static int gfind_aux (lua_State *L) {
const char *e;
ms.level = 0;
if ((e = match(&ms, src, p)) != NULL) {
- int newstart = e-s;
+ lua_Integer newstart = e-s;
if (e == src) newstart++; /* empty match? go at least one position */
lua_pushinteger(L, newstart);
lua_replace(L, lua_upvalueindex(3));
@@ -550,16 +569,22 @@ static int gfind_aux (lua_State *L) {
}
-static int gfind (lua_State *L) {
+static int gmatch (lua_State *L) {
luaL_checkstring(L, 1);
luaL_checkstring(L, 2);
lua_settop(L, 2);
lua_pushinteger(L, 0);
- lua_pushcclosure(L, gfind_aux, 3);
+ lua_pushcclosure(L, gmatch_aux, 3);
return 1;
}
+static int gfind_nodef (lua_State *L) {
+ return luaL_error(L, LUA_QL("string.gfind") " was renamed to "
+ LUA_QL("string.gmatch"));
+}
+
+
static void add_s (MatchState *ms, luaL_Buffer *b,
const char *s, const char *e) {
lua_State *L = ms->L;
@@ -569,14 +594,18 @@ static void add_s (MatchState *ms, luaL_Buffer *b,
size_t i;
for (i=0; i<l; i++) {
if (news[i] != L_ESC)
- luaL_putchar(b, news[i]);
+ luaL_addchar(b, news[i]);
else {
i++; /* skip ESC */
if (!isdigit(uchar(news[i])))
- luaL_putchar(b, news[i]);
+ luaL_addchar(b, news[i]);
else {
- int level = check_capture(ms, news[i]);
- push_onecapture(ms, level);
+ if (news[i] == '0')
+ lua_pushlstring(L, s, e - s); /* add whole match */
+ else {
+ int level = check_capture(ms, news[i]);
+ push_onecapture(ms, level);
+ }
luaL_addvalue(b); /* add capture to accumulated result */
}
}
@@ -622,7 +651,7 @@ static int str_gsub (lua_State *L) {
if (e && e>src) /* non empty match? */
src = e; /* skip it */
else if (src < ms.src_end)
- luaL_putchar(&b, *src++);
+ luaL_addchar(&b, *src++);
else break;
if (anchor) break;
}
@@ -644,12 +673,12 @@ static int str_gsub (lua_State *L) {
static void addquoted (lua_State *L, luaL_Buffer *b, int arg) {
size_t l;
const char *s = luaL_checklstring(L, arg, &l);
- luaL_putchar(b, '"');
+ luaL_addchar(b, '"');
while (l--) {
switch (*s) {
case '"': case '\\': case '\n': {
- luaL_putchar(b, '\\');
- luaL_putchar(b, *s);
+ luaL_addchar(b, '\\');
+ luaL_addchar(b, *s);
break;
}
case '\0': {
@@ -657,13 +686,13 @@ static void addquoted (lua_State *L, luaL_Buffer *b, int arg) {
break;
}
default: {
- luaL_putchar(b, *s);
+ luaL_addchar(b, *s);
break;
}
}
s++;
}
- luaL_putchar(b, '"');
+ luaL_addchar(b, '"');
}
@@ -699,9 +728,9 @@ static int str_format (lua_State *L) {
luaL_buffinit(L, &b);
while (strfrmt < strfrmt_end) {
if (*strfrmt != L_ESC)
- luaL_putchar(&b, *strfrmt++);
+ luaL_addchar(&b, *strfrmt++);
else if (*++strfrmt == L_ESC)
- luaL_putchar(&b, *strfrmt++); /* %% */
+ luaL_addchar(&b, *strfrmt++); /* %% */
else { /* format item */
char form[MAX_FORMAT]; /* to store the format (`%...') */
char buff[MAX_ITEM]; /* to store the formatted item */
@@ -753,20 +782,22 @@ static int str_format (lua_State *L) {
}
-static const luaL_reg strlib[] = {
- {"len", str_len},
- {"sub", str_sub},
- {"reverse", str_reverse},
- {"lower", str_lower},
- {"upper", str_upper},
- {"char", str_char},
- {"rep", str_rep},
+static const luaL_Reg strlib[] = {
{"byte", str_byte},
- {"format", str_format},
+ {"char", str_char},
{"dump", str_dump},
{"find", str_find},
- {"gfind", gfind},
+ {"format", str_format},
+ {"gfind", gfind_nodef},
+ {"gmatch", gmatch},
{"gsub", str_gsub},
+ {"len", str_len},
+ {"lower", str_lower},
+ {"match", str_match},
+ {"rep", str_rep},
+ {"reverse", str_reverse},
+ {"sub", str_sub},
+ {"upper", str_upper},
{NULL, NULL}
};
@@ -779,8 +810,6 @@ static void createmetatable (lua_State *L) {
lua_pop(L, 1); /* pop dummy string */
lua_pushvalue(L, -2); /* string library... */
lua_setfield(L, -2, "__index"); /* ...is the __index metamethod */
- lua_getfield(L, -2, "len");
- lua_setfield(L, -2, "__siz");
lua_pop(L, 1); /* pop metatable */
}
@@ -789,7 +818,11 @@ static void createmetatable (lua_State *L) {
** Open string library
*/
LUALIB_API int luaopen_string (lua_State *L) {
- luaL_openlib(L, LUA_STRLIBNAME, strlib, 0);
+ luaL_register(L, LUA_STRLIBNAME, strlib);
+#if defined(LUA_COMPAT_GFIND)
+ lua_getfield(L, -1, "gmatch");
+ lua_setfield(L, -2, "gfind");
+#endif
createmetatable(L);
return 1;
}
diff --git a/src/ltable.c b/src/ltable.c
index d0ba365b..979cc5ca 100644
--- a/src/ltable.c
+++ b/src/ltable.c
@@ -1,5 +1,5 @@
/*
-** $Id: ltable.c,v 2.23 2005/05/17 19:49:15 roberto Exp $
+** $Id: ltable.c,v 2.26 2005/07/11 14:01:37 roberto Exp $
** Lua tables (hash)
** See Copyright Notice in lua.h
*/
@@ -120,7 +120,7 @@ static int arrayindex (const TValue *key) {
lua_Number n = nvalue(key);
int k;
lua_number2int(k, n);
- if (luai_numeq(cast(lua_Number, k), nvalue(key)))
+ if (luai_numeq(L, cast(lua_Number, k), nvalue(key)))
return k;
}
return -1; /* `key' did not match some condition */
@@ -145,7 +145,7 @@ static int findindex (lua_State *L, Table *t, StkId key) {
if (luaO_rawequalObj(key2tval(n), key) ||
(ttype(gkey(n)) == LUA_TDEADKEY && iscollectable(key) &&
gcvalue(gkey(n)) == gcvalue(key))) {
- i = n - gnode(t, 0); /* key index in hash table */
+ i = cast(int, n - gnode(t, 0)); /* key index in hash table */
/* hash elements are numbered after array ones */
return i + t->sizearray;
}
@@ -376,7 +376,7 @@ void luaH_free (lua_State *L, Table *t) {
}
-static Node *getfreepos (lua_State *L, Table *t) {
+static Node *getfreepos (Table *t) {
while (t->lastfree-- > t->node) {
if (ttisnil(gkey(t->lastfree)))
return t->lastfree;
@@ -397,7 +397,7 @@ static TValue *newkey (lua_State *L, Table *t, const TValue *key) {
Node *mp = luaH_mainposition(t, key);
if (!ttisnil(gval(mp)) || mp == &luaH_dummynode) {
Node *othern;
- Node *n = getfreepos(L, t); /* get a free place */
+ Node *n = getfreepos(t); /* get a free place */
if (n == NULL) { /* cannot find a free place? */
rehash(L, t, key); /* grow table */
return luaH_set(L, t, key); /* re-insert key into grown table */
@@ -437,7 +437,7 @@ const TValue *luaH_getnum (Table *t, int key) {
lua_Number nk = cast(lua_Number, key);
Node *n = hashnum(t, nk);
do { /* check whether `key' is somewhere in the chain */
- if (ttisnumber(gkey(n)) && luai_numeq(nvalue(gkey(n)), nk))
+ if (ttisnumber(gkey(n)) && luai_numeq(L, nvalue(gkey(n)), nk))
return gval(n); /* that's it */
else n = gnext(n);
} while (n);
@@ -471,7 +471,7 @@ const TValue *luaH_get (Table *t, const TValue *key) {
int k;
lua_Number n = nvalue(key);
lua_number2int(k, n);
- if (luai_numeq(cast(lua_Number, k), nvalue(key))) /* index is integer? */
+ if (luai_numeq(L, cast(lua_Number, k), nvalue(key))) /* index is int? */
return luaH_getnum(t, k); /* use specialized version */
/* else go through */
}
@@ -495,7 +495,7 @@ TValue *luaH_set (lua_State *L, Table *t, const TValue *key) {
return cast(TValue *, p);
else {
if (ttisnil(key)) luaG_runerror(L, "table index is nil");
- else if (ttisnumber(key) && !luai_numeq(nvalue(key), nvalue(key)))
+ else if (ttisnumber(key) && !luai_numeq(L, nvalue(key), nvalue(key)))
luaG_runerror(L, "table index is NaN");
return newkey(L, t, key);
}
diff --git a/src/ltable.h b/src/ltable.h
index 1a798262..14a20448 100644
--- a/src/ltable.h
+++ b/src/ltable.h
@@ -1,5 +1,5 @@
/*
-** $Id: ltable.h,v 2.7 2005/04/25 19:24:10 roberto Exp $
+** $Id: ltable.h,v 2.8 2005/06/06 13:30:25 roberto Exp $
** Lua tables (hash)
** See Copyright Notice in lua.h
*/
@@ -18,7 +18,7 @@
#define key2tval(n) (cast(const TValue *, gkey(n)))
-extern const Node luaH_dummynode;
+LUAI_DATA const Node luaH_dummynode;
LUAI_FUNC const TValue *luaH_getnum (Table *t, int key);
LUAI_FUNC TValue *luaH_setnum (lua_State *L, Table *t, int key);
diff --git a/src/ltablib.c b/src/ltablib.c
index ab4d5db2..348b6ed5 100644
--- a/src/ltablib.c
+++ b/src/ltablib.c
@@ -1,5 +1,5 @@
/*
-** $Id: ltablib.c,v 1.31 2005/05/17 19:49:15 roberto Exp $
+** $Id: ltablib.c,v 1.35 2005/08/26 17:36:32 roberto Exp $
** Library for Table Manipulation
** See Copyright Notice in lua.h
*/
@@ -109,7 +109,7 @@ static int tremove (lua_State *L) {
}
-static int str_concat (lua_State *L) {
+static int tconcat (lua_State *L) {
luaL_Buffer b;
size_t lsep;
const char *sep = luaL_optlstring(L, 2, "", &lsep);
@@ -236,21 +236,21 @@ static int sort (lua_State *L) {
/* }====================================================== */
-static const luaL_reg tab_funcs[] = {
- {"concat", str_concat},
+static const luaL_Reg tab_funcs[] = {
+ {"concat", tconcat},
{"foreach", foreach},
{"foreachi", foreachi},
{"getn", getn},
- {"setn", setn},
- {"sort", sort},
{"insert", tinsert},
{"remove", tremove},
+ {"setn", setn},
+ {"sort", sort},
{NULL, NULL}
};
LUALIB_API int luaopen_table (lua_State *L) {
- luaL_openlib(L, LUA_TABLIBNAME, tab_funcs, 0);
+ luaL_register(L, LUA_TABLIBNAME, tab_funcs);
return 1;
}
diff --git a/src/ltm.c b/src/ltm.c
index 6f2223a7..591134da 100644
--- a/src/ltm.c
+++ b/src/ltm.c
@@ -1,5 +1,5 @@
/*
-** $Id: ltm.c,v 2.5 2005/05/05 15:34:03 roberto Exp $
+** $Id: ltm.c,v 2.6 2005/05/20 15:53:42 roberto Exp $
** Tag methods
** See Copyright Notice in lua.h
*/
@@ -32,7 +32,7 @@ void luaT_init (lua_State *L) {
"__index", "__newindex",
"__gc", "__mode", "__eq",
"__add", "__sub", "__mul", "__div", "__mod",
- "__pow", "__unm", "__siz", "__lt", "__le",
+ "__pow", "__unm", "__len", "__lt", "__le",
"__concat", "__call"
};
int i;
diff --git a/src/ltm.h b/src/ltm.h
index 1622b781..866c7966 100644
--- a/src/ltm.h
+++ b/src/ltm.h
@@ -1,5 +1,5 @@
/*
-** $Id: ltm.h,v 2.4 2005/05/05 15:34:03 roberto Exp $
+** $Id: ltm.h,v 2.6 2005/06/06 13:30:25 roberto Exp $
** Tag methods
** See Copyright Notice in lua.h
*/
@@ -28,7 +28,7 @@ typedef enum {
TM_MOD,
TM_POW,
TM_UNM,
- TM_SIZ,
+ TM_LEN,
TM_LT,
TM_LE,
TM_CONCAT,
@@ -43,7 +43,7 @@ typedef enum {
#define fasttm(l,et,e) gfasttm(G(l), et, e)
-extern const char *const luaT_typenames[];
+LUAI_DATA const char *const luaT_typenames[];
LUAI_FUNC const TValue *luaT_gettm (Table *events, TMS event, TString *ename);
diff --git a/src/lua.c b/src/lua.c
index a942c741..14c5e20d 100644
--- a/src/lua.c
+++ b/src/lua.c
@@ -1,5 +1,5 @@
/*
-** $Id: lua.c,v 1.144 2005/05/17 19:49:15 roberto Exp $
+** $Id: lua.c,v 1.150 2005/09/06 17:19:33 roberto Exp $
** Lua stand-alone interpreter
** See Copyright Notice in lua.h
*/
@@ -48,15 +48,16 @@ static void print_usage (void) {
" -i enter interactive mode after executing " LUA_QL("script") "\n"
" -l name require library " LUA_QL("name") "\n"
" -v show version information\n"
- " -w trap access to undefined globals\n"
" -- stop handling options\n" ,
progname);
+ fflush(stderr);
}
static void l_message (const char *pname, const char *msg) {
if (pname) fprintf(stderr, "%s: ", pname);
fprintf(stderr, "%s\n", msg);
+ fflush(stderr);
}
@@ -72,14 +73,19 @@ static int report (lua_State *L, int status) {
static int traceback (lua_State *L) {
- luaL_getfield(L, LUA_GLOBALSINDEX, "debug.traceback");
- if (!lua_isfunction(L, -1))
+ lua_getfield(L, LUA_GLOBALSINDEX, "debug");
+ if (!lua_istable(L, -1)) {
lua_pop(L, 1);
- else {
- lua_pushvalue(L, 1); /* pass error message */
- lua_pushinteger(L, 2); /* skip this function and traceback */
- lua_call(L, 2, 1); /* call debug.traceback */
+ return 1;
+ }
+ lua_getfield(L, -1, "traceback");
+ if (!lua_isfunction(L, -1)) {
+ lua_pop(L, 2);
+ return 1;
}
+ lua_pushvalue(L, 1); /* pass error message */
+ lua_pushinteger(L, 2); /* skip this function and traceback */
+ lua_call(L, 2, 1); /* call debug.traceback */
return 1;
}
@@ -138,8 +144,7 @@ static int dolibrary (lua_State *L, const char *name) {
static const char *get_prompt (lua_State *L, int firstline) {
const char *p;
- lua_pushstring(L, firstline ? "_PROMPT" : "_PROMPT2");
- lua_rawget(L, LUA_GLOBALSINDEX);
+ lua_getfield(L, LUA_GLOBALSINDEX, firstline ? "_PROMPT" : "_PROMPT2");
p = lua_tostring(L, -1);
if (p == NULL) p = (firstline ? LUA_PROMPT : LUA_PROMPT2);
lua_pop(L, 1); /* remove global */
@@ -148,13 +153,16 @@ static const char *get_prompt (lua_State *L, int firstline) {
static int incomplete (lua_State *L, int status) {
- if (status == LUA_ERRSYNTAX &&
- strstr(lua_tostring(L, -1), "<eof>") != NULL) {
- lua_pop(L, 1);
- return 1;
+ if (status == LUA_ERRSYNTAX) {
+ size_t lmsg;
+ const char *msg = lua_tolstring(L, -1, &lmsg);
+ const char *tp = msg + lmsg - (sizeof(LUA_QL("<eof>")) - 1);
+ if (strstr(msg, LUA_QL("<eof>")) == tp) {
+ lua_pop(L, 1);
+ return 1;
+ }
}
- else
- return 0;
+ return 0; /* else... */
}
@@ -216,18 +224,11 @@ static void dotty (lua_State *L) {
}
lua_settop(L, 0); /* clear stack */
fputs("\n", stdout);
+ fflush(stdout);
progname = oldprogname;
}
-static int checkvar (lua_State *L) {
- const char *name = lua_tostring(L, 2);
- if (name)
- luaL_error(L, "attempt to access undefined variable " LUA_QS, name);
- return 0;
-}
-
-
#define clearinteractive(i) (*i &= 2)
static int handle_argv (lua_State *L, int argc, char **argv, int *interactive) {
@@ -265,13 +266,6 @@ static int handle_argv (lua_State *L, int argc, char **argv, int *interactive) {
print_version();
break;
}
- case 'w': {
- if (lua_getmetatable(L, LUA_GLOBALSINDEX)) {
- lua_pushcfunction(L, checkvar);
- lua_setfield(L, -2, "__index");
- }
- break;
- }
case 'e': {
const char *chunk = argv[i] + 2;
clearinteractive(interactive);
diff --git a/src/lua.h b/src/lua.h
index 1028e5ea..339e076f 100644
--- a/src/lua.h
+++ b/src/lua.h
@@ -1,8 +1,7 @@
/*
-** $Id: lua.h,v 1.208 2005/05/17 19:49:15 roberto Exp $
+** $Id: lua.h,v 1.212 2005/08/25 20:02:08 roberto Exp $
** Lua - An Extensible Extension Language
-** Tecgraf: Computer Graphics Technology Group, PUC-Rio, Brazil
-** http://www.lua.org
+** Lua.org, PUC-Rio, Brazil (http://www.lua.org)
** See Copyright Notice at the end of this file
*/
@@ -17,9 +16,9 @@
#include "luaconf.h"
-#define LUA_VERSION "Lua 5.1 (work6)"
+#define LUA_VERSION "Lua 5.1 (alpha)"
#define LUA_VERSION_NUM 501
-#define LUA_COPYRIGHT "Copyright (C) 1994-2005 Tecgraf, PUC-Rio"
+#define LUA_COPYRIGHT "Copyright (C) 1994-2005 Lua.org, PUC-Rio"
#define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo & W. Celes"
@@ -39,7 +38,7 @@
#define lua_upvalueindex(i) (LUA_GLOBALSINDEX-(i))
-/* return codes for `lua_pcall', `lua_resume', and `lua_status' */
+/* thread status; 0 is OK */
#define LUA_YIELD 1
#define LUA_ERRRUN 2
#define LUA_ERRSYNTAX 3
@@ -147,7 +146,7 @@ LUA_API lua_Number (lua_tonumber) (lua_State *L, int idx);
LUA_API lua_Integer (lua_tointeger) (lua_State *L, int idx);
LUA_API int (lua_toboolean) (lua_State *L, int idx);
LUA_API const char *(lua_tolstring) (lua_State *L, int idx, size_t *len);
-LUA_API size_t (lua_objsize) (lua_State *L, int idx);
+LUA_API size_t (lua_objlen) (lua_State *L, int idx);
LUA_API lua_CFunction (lua_tocfunction) (lua_State *L, int idx);
LUA_API void *(lua_touserdata) (lua_State *L, int idx);
LUA_API lua_State *(lua_tothread) (lua_State *L, int idx);
@@ -257,7 +256,7 @@ LUA_API lua_Alloc (lua_getallocf) (lua_State *L, void **ud);
#define lua_pushcfunction(L,f) lua_pushcclosure(L, (f), 0)
-#define lua_strlen(L,i) lua_objsize(L, (i))
+#define lua_strlen(L,i) lua_objlen(L, (i))
#define lua_isfunction(L,n) (lua_type(L, (n)) == LUA_TFUNCTION)
#define lua_istable(L,n) (lua_type(L, (n)) == LUA_TTABLE)
@@ -357,7 +356,7 @@ struct lua_Debug {
/******************************************************************************
-* Copyright (C) 1994-2005 Tecgraf, PUC-Rio. All rights reserved.
+* Copyright (C) 1994-2005 Lua.org, PUC-Rio. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
diff --git a/src/luac.c b/src/luac.c
index cfe00c7b..374ea3ac 100644
--- a/src/luac.c
+++ b/src/luac.c
@@ -1,5 +1,5 @@
/*
-** $Id: luac.c,v 1.50 2005/05/12 00:26:50 lhf Exp $
+** $Id: luac.c,v 1.51 2005/06/02 13:39:23 lhf Exp $
** Lua compiler (saves bytecodes to files; also list bytecodes)
** See Copyright Notice in lua.h
*/
@@ -53,7 +53,7 @@ static void cannot(const char* what)
static void usage(const char* message)
{
if (*message=='-')
- fprintf(stderr,"%s: unrecognized option `%s'\n",progname,message);
+ fprintf(stderr,"%s: unrecognized option " LUA_QS "\n",progname,message);
else
fprintf(stderr,"%s: %s\n",progname,message);
fprintf(stderr,
@@ -61,7 +61,7 @@ static void usage(const char* message)
"Available options are:\n"
" - process stdin\n"
" -l list\n"
- " -o name output to file `name' (default is \"%s\")\n"
+ " -o name output to file " LUA_QL("name") " (default is \"%s\")\n"
" -p parse only\n"
" -s strip debug information\n"
" -v show version information\n"
@@ -92,7 +92,7 @@ static int doargs(int argc, char* argv[])
else if (IS("-o")) /* output file */
{
output=argv[++i];
- if (output==NULL || *output==0) usage("`-o' needs argument");
+ if (output==NULL || *output==0) usage(LUA_QL("-o") " needs argument");
if (IS("-")) output=NULL;
}
else if (IS("-p")) /* parse only */
diff --git a/src/luaconf.h b/src/luaconf.h
index bc211cd3..d6d4a2a7 100644
--- a/src/luaconf.h
+++ b/src/luaconf.h
@@ -1,5 +1,5 @@
/*
-** $Id: luaconf.h,v 1.49a 2005/05/17 19:49:15 roberto Exp $
+** $Id: luaconf.h,v 1.65 2005/09/09 18:24:42 roberto Exp $
** Configuration file for Lua
** See Copyright Notice in lua.h
*/
@@ -22,6 +22,16 @@
/*
+@@ LUA_ANSI controls the use of non-ansi features.
+** CHANGE it (define it) if you want Lua to avoid the use of any
+** non-ansi feature or library.
+*/
+#if defined(__STRICT_ANSI__)
+#define LUA_ANSI
+#endif
+
+
+/*
@@ LUA_PATH_DEFAULT is the default path that Lua uses to look for
@* Lua libraries.
@@ LUA_CPATH_DEFAULT is the default path that Lua uses to look for
@@ -31,22 +41,27 @@
** non-conventional directories.
*/
#if defined(_WIN32)
-#define LUA_ROOT "C:\\Program Files\\Lua51"
-#define LUA_LDIR LUA_ROOT "\\lua"
-#define LUA_CDIR LUA_ROOT "\\dll"
+/*
+** In Windows, any exclamation mark ('!') in the path is replaced by the
+** path of the directory of the executable file of the current process.
+*/
+#define LUA_LDIR "!\\lua\\"
+#define LUA_CDIR "!\\"
#define LUA_PATH_DEFAULT \
- "?.lua;" LUA_LDIR"\\?.lua;" LUA_LDIR"\\?\\init.lua"
-#define LUA_CPATH_DEFAULT \
- "?.dll;" "l?.dll;" LUA_CDIR"\\?.dll;" LUA_CDIR"\\l?.dll"
+ ".\\?.lua;" LUA_LDIR"?.lua;" LUA_LDIR"?\\init.lua;" \
+ LUA_CDIR"?.lua;" LUA_CDIR"?\\init.lua"
+#define LUA_CPATH_DEFAULT \
+ ".\\?.dll;" LUA_CDIR"?.dll;" LUA_CDIR"loadall.dll"
#else
-#define LUA_ROOT "/usr/local"
-#define LUA_LDIR LUA_ROOT "/share/lua/5.1"
-#define LUA_CDIR LUA_ROOT "/lib/lua/5.1"
+#define LUA_ROOT "/usr/local/"
+#define LUA_LDIR LUA_ROOT "share/lua/5.1/"
+#define LUA_CDIR LUA_ROOT "lib/lua/5.1/"
#define LUA_PATH_DEFAULT \
- "./?.lua;" LUA_LDIR"/?.lua;" LUA_LDIR"/?/init.lua"
-#define LUA_CPATH_DEFAULT \
- "./?.so;" "./l?.so;" LUA_CDIR"/?.so;" LUA_CDIR"/l?.so"
+ "./?.lua;" LUA_LDIR"?.lua;" LUA_LDIR"?/init.lua;" \
+ LUA_CDIR"?.lua;" LUA_CDIR"?/init.lua"
+#define LUA_CPATH_DEFAULT \
+ "./?.so;" LUA_CDIR"?.so;" LUA_CDIR"loadall.so"
#endif
@@ -64,21 +79,20 @@
/*
@@ LUA_PATHSEP is the character that separates templates in a path.
-** CHANGE it if for some reason your system cannot use a
-** semicolon. (E.g., if a semicolon is a common character in
-** file/directory names.) Probably you do not need to change this.
-*/
-#define LUA_PATHSEP ';'
-
-
-/*
@@ LUA_PATH_MARK is the string that marks the substitution points in a
@* template.
-** CHANGE it if for some reason your system cannot use an interrogation
-** mark. (E.g., if an interogation mark is a common character in
-** file/directory names.) Probably you do not need to change this.
-*/
+@@ LUA_EXECDIR in a Windows path is replaced by the executable's
+@* directory.
+@@ LUA_IGMARK is a mark to ignore all before it when bulding the
+@* luaopen_ function name.
+** CHANGE them if for some reason your system cannot use those
+** characters. (E.g., if one of those characters is a common character
+** in file/directory names.) Probably you do not need to change them.
+*/
+#define LUA_PATHSEP ";"
#define LUA_PATH_MARK "?"
+#define LUA_EXECDIR "!"
+#define LUA_IGMARK ":"
/*
@@ -100,9 +114,9 @@
#if defined(LUA_BUILD_AS_DLL)
#if defined(LUA_CORE) || defined(LUA_LIB)
-#define LUA_API __declspec(__dllexport)
+#define LUA_API __declspec(dllexport)
#else
-#define LUA_API __declspec(__dllimport)
+#define LUA_API __declspec(dllimport)
#endif
#else
@@ -118,19 +132,26 @@
/*
@@ LUAI_FUNC is a mark for all extern functions that are not to be
@* exported to outside modules.
-** CHANGE it if you need to mark them in some special way. Gcc (versions
-** 3.2 and later) mark them as "hidden" to optimize their call when Lua
-** is compiled as a shared library.
+@@ LUAI_DATA is a mark for all extern (const) variables that are not to
+@* be exported to outside modules.
+** CHANGE them if you need to mark them in some special way. Elf/gcc
+** (versions 3.2 and later) mark them as "hidden" to optimize access
+** when Lua is compiled as a shared library.
*/
#if defined(luaall_c)
#define LUAI_FUNC static
-#elif defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302)
-#define LUAI_FUNC __attribute__((visibility("hidden")))
+#define LUAI_DATA /* empty */
+#elif defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302) && \
+ defined(__ELF__)
+#define LUAI_FUNC __attribute__((visibility("hidden"))) extern
+#define LUAI_DATA LUAI_FUNC
#else
#define LUAI_FUNC extern
+#define LUAI_DATA extern
#endif
+
/*
@@ lua_assert describes the internal assertions in Lua.
** CHANGE that only if you need to debug Lua.
@@ -149,7 +170,7 @@
/*
@@ LUA_IDSIZE gives the maximum size for the description of the source
@* of a function in debug information.
-** CHANGE it if you a different size.
+** CHANGE it if you want a different size.
*/
#define LUA_IDSIZE 60
@@ -168,10 +189,10 @@
** CHANGE it if you have a better definition for non-POSIX/non-Windows
** systems.
*/
-#if !defined(__STRICT_ANSI__) && defined(_POSIX_C_SOURCE)
+#if !defined(LUA_ANSI) && defined(_POSIX_C_SOURCE)
#include <unistd.h>
#define lua_stdin_is_tty() isatty(0)
-#elif !defined(__STRICT_ANSI__) && defined(_WIN32)
+#elif !defined(LUA_ANSI) && defined(_WIN32)
#include <io.h>
#include <stdio.h>
#define lua_stdin_is_tty() _isatty(_fileno(stdin))
@@ -214,7 +235,7 @@
** CHANGE them if you want to improve this functionality (e.g., by using
** GNU readline and history facilities).
*/
-#if !defined(__STRICT_ANSI__) && defined(LUA_USE_READLINE)
+#if defined(LUA_USE_READLINE)
#include <stdio.h>
#include <readline/readline.h>
#include <readline/history.h>
@@ -239,49 +260,52 @@
/*
@@ LUAI_GCPAUSE defines the default pause between garbage-collector cycles
@* as a percentage.
-** CHANGE it if you want the GC to run faster or slower (higher
-** values mean larger pauses which mean slower collection.)
+** CHANGE it if you want the GC to run faster or slower (higher values
+** mean larger pauses which mean slower collection.) You can also change
+** this value dynamically.
*/
#define LUAI_GCPAUSE 200 /* 200% (wait memory to double before next GC) */
/*
-@@ LUAI_GCMUL defines the speed of garbage collection relative to
+@@ LUAI_GCMUL defines the default speed of garbage collection relative to
@* memory allocation as a percentage.
** CHANGE it if you want to change the granularity of the garbage
** collection. (Higher values mean coarser collections. 0 represents
-** infinity, where each step performs a full collection.)
+** infinity, where each step performs a full collection.) You can also
+** change this value dynamically.
*/
#define LUAI_GCMUL 200 /* GC runs 'twice the speed' of memory allocation */
+
/*
@@ LUA_COMPAT_GETN controls compatibility with old getn behavior.
-** CHANGE it to 1 if you want exact compatibility with the behavior of
-** setn/getn in Lua 5.0.
+** CHANGE it (define it) if you want exact compatibility with the
+** behavior of setn/getn in Lua 5.0.
*/
-#define LUA_COMPAT_GETN 0
+#undef LUA_COMPAT_GETN
/*
-@@ LUA_COMPAT_PATH controls compatibility about LUA_PATH.
-** CHANGE it to 1 if you want 'require' to look for global LUA_PATH
-** before checking package.path.
+@@ LUA_COMPAT_LOADLIB controls compatibility about global loadlib.
+** CHANGE it to undefined as soon as you do not need a global 'loadlib'
+** function (the function is still available as 'package.loadlib').
*/
-#define LUA_COMPAT_PATH 0
+#undef LUA_COMPAT_LOADLIB
/*
-@@ LUA_COMPAT_LOADLIB controls compatibility about global loadlib.
-** CHANGE it to 1 if you want a global 'loadlib' function (otherwise
-** the function is only available as 'package.loadlib').
+@@ LUA_COMPAT_VARARG controls compatibility with old vararg feature.
+** CHANGE it to undefined as soon as your programs use only '...' to
+** access vararg parameters (instead of the old 'arg' table).
*/
-#define LUA_COMPAT_LOADLIB 1
+#define LUA_COMPAT_VARARG
/*
-@@ LUA_COMPAT_VARARG controls compatibility with old vararg feature.
-** CHANGE it to 1 if you want vararg functions that do not use '...'
-** to get an 'arg' table with their extra arguments.
+@@ LUA_COMPAT_MOD controls compatibility with old math.mod function.
+** CHANGE it to undefined as soon as your programs use 'math.fmod' or
+** the new '%' operator instead of 'math.mod'.
*/
-#define LUA_COMPAT_VARARG 1
+#define LUA_COMPAT_MOD
/*
@@ LUA_COMPAT_LSTR controls compatibility with old long string nesting
@@ -292,6 +316,31 @@
#define LUA_COMPAT_LSTR 1
/*
+@@ LUA_COMPAT_FIND controls compatibility with old 'string.find' behavior.
+** CHANGE it to undefined as soon as your programs use 'string.find' only
+** to find patterns.
+*/
+#define LUA_COMPAT_FIND
+
+/*
+@@ LUA_COMPAT_GFIND controls compatibility with old 'string.gfind' name.
+** CHANGE it to undefined as soon as you rename 'string.gfind' to
+** 'string.gmatch'.
+*/
+#define LUA_COMPAT_GFIND
+
+
+/*
+@@ LUA_COMPAT_OPENLIB controls compatibility with old 'luaL_openlib'
+@* behavior.
+** CHANGE it to undefined as soon as you replace to 'luaL_registry'
+** your uses of 'luaL_openlib'
+*/
+#define LUA_COMPAT_OPENLIB
+
+
+
+/*
@@ luai_apicheck is the assert macro used by the Lua-C API.
** CHANGE luai_apicheck if you want Lua to perform some checks in the
** parameters it gets from API calls. This may slow down the interpreter
@@ -407,13 +456,6 @@
/*
-@@ LUAI_MAXEXPWHILE is the maximum size of code for expressions
-@* controling a 'while' loop.
-*/
-#define LUAI_MAXEXPWHILE 100
-
-
-/*
@@ LUAL_BUFFERSIZE is the buffer size used by the lauxlib buffer system.
*/
#define LUAL_BUFFERSIZE BUFSIZ
@@ -424,47 +466,25 @@
/*
@@ lua_number2int is a macro to convert lua_Number to int.
-** CHANGE that if you know a faster way to convert a lua_Number to
+@@ lua_number2integer is a macro to convert lua_Number to lua_Integer.
+** CHANGE them if you know a faster way to convert a lua_Number to
** int (with any rounding method and without throwing errors) in your
** system. In Pentium machines, a naive typecast from double to int
** in C is extremely slow, so any alternative is worth trying.
*/
-/* On a gcc/Pentium, resort to assembler */
-#if !defined(__STRICT_ANSI__) && defined(__GNUC__) && defined(__i386)
-#define lua_number2int(i,d) __asm__ ("fistpl %0":"=m"(i):"t"(d):"st")
-
-/* On Windows/Pentium, resort to assembler */
-#elif !defined(__STRICT_ANSI__) && defined(_MSC_VER) && defined(_M_IX86)
-#define lua_number2int(i,d) \
- __asm fld d \
- __asm fistp i
-
-
-/* on Pentium machines compliant with C99, you can try lrint */
-#elif defined (__i386) && defined(__STDC_VERSION__) && \
- (__STDC_VERSION__ >= 199900L)
-#define lua_number2int(i,d) ((i)=lrint(d))
-
-/* this option always works, but may be slow */
-#else
-#define lua_number2int(i,d) ((i)=(int)(d))
-
-#endif
-
-
-/*
-@@ lua_number2integer is a macro to convert lua_Number to lua_Integer.
-** CHANGE (see lua_number2int).
-*/
-/* On a gcc or Windows/Pentium, resort to assembler */
-#if (defined(__GNUC__) && defined(__i386)) || \
- (defined(_MSC_VER) && defined(_M_IX86))
+/* On a Pentium, resort to a trick */
+#if !defined(LUA_ANSI) && !defined(__SSE2__) && \
+ (defined(__i386) || defined (_M_IX86))
+union luai_Cast { double l_d; long l_l; };
+#define lua_number2int(i,d) \
+ { volatile union luai_Cast u; u.l_d = (d) + 6755399441055744.0; (i) = u.l_l; }
#define lua_number2integer(i,n) lua_number2int(i, n)
/* this option always works, but may be slow */
#else
-#define lua_number2integer(i,d) ((i)=(lua_Integer)(d))
+#define lua_number2int(i,d) ((i)=(int)(d))
+#define lua_number2integer(i,d) ((i)=(lua_Integer)(d))
#endif
@@ -479,13 +499,13 @@
** ===================================================================
*/
+#define LUA_NUMBER double
/*
@@ LUAI_UACNUMBER is the result of an 'usual argument conversion'
@* over a number.
*/
-#define LUA_NUMBER double
-#define LUAI_UACNUMBER LUA_NUMBER
+#define LUAI_UACNUMBER double
/*
@@ -505,16 +525,16 @@
/*
@@ The luai_num* macros define the primitive operations over numbers.
*/
-#define luai_numadd(a,b) ((a)+(b))
-#define luai_numsub(a,b) ((a)-(b))
-#define luai_nummul(a,b) ((a)*(b))
-#define luai_numdiv(a,b) ((a)/(b))
-#define luai_nummod(a,b) ((a) - floor((a)/(b))*(b))
-#define luai_numpow(a,b) pow(a,b)
-#define luai_numunm(a) (-(a))
-#define luai_numeq(a,b) ((a)==(b))
-#define luai_numlt(a,b) ((a)<(b))
-#define luai_numle(a,b) ((a)<=(b))
+#define luai_numadd(L,a,b) ((a)+(b))
+#define luai_numsub(L,a,b) ((a)-(b))
+#define luai_nummul(L,a,b) ((a)*(b))
+#define luai_numdiv(L,a,b) ((a)/(b))
+#define luai_nummod(L,a,b) ((a) - floor((a)/(b))*(b))
+#define luai_numpow(L,a,b) pow(a,b)
+#define luai_numunm(L,a) (-(a))
+#define luai_numeq(L,a,b) ((a)==(b))
+#define luai_numlt(L,a,b) ((a)<(b))
+#define luai_numle(L,a,b) ((a)<=(b))
/* }================================================================== */
@@ -531,11 +551,11 @@
/*
@@ LUAI_THROW/LUAI_TRY define how Lua does exception handling.
-** CHANGE them if you prefer to use longjmp/setjmp even with C++ or
-** if want/don't want to use _longjmp/_setjmp instead of regular
+** CHANGE them if you prefer to use longjmp/setjmp even with C++
+** or if want/don't to use _longjmp/_setjmp instead of regular
** longjmp/setjmp. By default, Lua handles errors with exceptions when
-** compiling as C++ code, with _longjmp/_setjmp when compiling as C code
-** in a Unix system, and with longjmp/setjmp otherwise.
+** compiling as C++ code, with _longjmp/_setjmp when asked to use them,
+** and with longjmp/setjmp otherwise.
*/
#if defined(__cplusplus)
/* C++ exceptions */
@@ -544,8 +564,7 @@
{ if ((c)->status == 0) (c)->status = -1; }
#define luai_jmpbuf int /* dummy variable */
-#elif !defined(__STRICT_ANSI__) && (defined(unix) || defined(__unix) || \
- defined(__unix__))
+#elif defined(LUA_USE_ULONGJMP)
/* in Unix, try _longjmp/_setjmp (more efficient) */
#define LUAI_THROW(L,c) _longjmp((c)->b, 1)
#define LUAI_TRY(L,c,a) if (_setjmp((c)->b) == 0) { a }
@@ -578,7 +597,7 @@
*/
#if defined(loslib_c) || defined(luaall_c)
-#if !defined(__STRICT_ANSI__) && defined(_POSIX_C_SOURCE)
+#if !defined(LUA_ANSI) && defined(_POSIX_C_SOURCE)
#include <unistd.h>
#define LUA_TMPNAMBUFSIZE 32
#define lua_tmpnam(b,e) { \
@@ -593,6 +612,30 @@
#endif
+
+/*
+@@ lua_popen spawns a new process connected to the current one through
+@* the file streams.
+** CHANGE it if you have a way to implement it in your system.
+*/
+#if !defined(LUA_ANSI) && defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 2
+
+#define lua_popen(L,c,m) popen(c,m)
+#define lua_pclose(L,file) (pclose(file) != -1)
+
+#elif !defined(LUA_ANSI) && defined(_WIN32)
+
+#define lua_popen(L,c,m) _popen(c,m)
+#define lua_pclose(L,file) (_pclose(file) != -1)
+
+#else
+
+#define lua_popen(L,c,m) \
+ ((void)c, (void)m, luaL_error(L, LUA_QL("popen") " not supported"), (FILE*)0)
+#define lua_pclose(L,file) ((void)file, 0)
+
+#endif
+
/*
@@ LUA_DL_* define which dynamic-library system Lua should use.
** CHANGE here if Lua has problems choosing the appropriate
@@ -606,7 +649,7 @@
** If you do not want any kind of dynamic library, undefine all these
** options (or just remove these definitions).
*/
-#if !defined(__STRICT_ANSI__)
+#if !defined(LUA_ANSI)
#if defined(_WIN32)
#define LUA_DL_DLL
#elif defined(__APPLE__) && defined(__MACH__)
@@ -618,29 +661,6 @@
/*
-@@ lua_lock/lua_unlock are macros for thread synchronization inside the
-@* Lua core. This is an attempt to simplify the implementation of a
-@* multithreaded version of Lua.
-** CHANGE them only if you know what you are doing. All accesses to
-** the global state and to global objects are synchronized. Because
-** threads can read the stack of other threads (when running garbage
-** collection), a thread must also synchronize any write-access to its
-** own stack. Unsynchronized accesses are allowed only when reading its
-** own stack, or when reading immutable fields from global objects (such
-** as string values and udata values).
-*/
-#define lua_lock(L) ((void) 0)
-#define lua_unlock(L) ((void) 0)
-
-
-/*
-@@ lua_threadyield allows a thread switch in appropriate places in the core.
-** CHANGE it only if you know what you are doing. (See lua_lock.)
-*/
-#define luai_threadyield(L) {lua_unlock(L); lua_lock(L);}
-
-
-/*
@@ LUAI_EXTRASPACE allows you to add user-specific data in a lua_State
@* (the data goes just *before* the lua_State pointer).
** CHANGE (define) this if you really need that. This value must be
@@ -650,11 +670,15 @@
/*
-@@ luai_userstateopen allows user-specific initialization on new threads.
-** CHANGE it if you defined LUAI_EXTRASPACE and need to initialize that
-** data whenever a new lua_State is created.
+@@ luai_userstate* allow user-specific actions on threads.
+** CHANGE them if you defined LUAI_EXTRASPACE and need to do something
+** extra when a thread is created/deleted/resumed/yielded.
*/
-#define luai_userstateopen(L) ((void)0)
+#define luai_userstateopen(L) ((void)0)
+#define luai_userstatefree(L) ((void)0)
+#define luai_userstateresume(L,n) ((void)0)
+#define luai_userstateyield(L,n) ((void)0)
+
@@ -668,3 +692,4 @@
#endif
+
diff --git a/src/lualib.h b/src/lualib.h
index e1face32..f52bb888 100644
--- a/src/lualib.h
+++ b/src/lualib.h
@@ -1,5 +1,5 @@
/*
-** $Id: lualib.h,v 1.34 2005/04/13 17:24:20 roberto Exp $
+** $Id: lualib.h,v 1.35 2005/08/10 18:06:58 roberto Exp $
** Lua standard libraries
** See Copyright Notice in lua.h
*/
@@ -37,7 +37,7 @@ LUALIB_API int (luaopen_math) (lua_State *L);
LUALIB_API int (luaopen_debug) (lua_State *L);
#define LUA_LOADLIBNAME "package"
-LUALIB_API int (luaopen_loadlib) (lua_State *L);
+LUALIB_API int (luaopen_package) (lua_State *L);
/* open all previous libraries */
diff --git a/src/lundump.c b/src/lundump.c
index 8ceb571b..726d021d 100644
--- a/src/lundump.c
+++ b/src/lundump.c
@@ -1,11 +1,10 @@
/*
-** $Id: lundump.c,v 1.55 2005/05/12 00:26:50 lhf Exp $
+** $Id: lundump.c,v 1.58 2005/09/02 01:54:47 lhf Exp $
** load pre-compiled Lua chunks
** See Copyright Notice in lua.h
*/
-#include <stdarg.h>
-#include <stddef.h>
+#include <string.h>
#define lundump_c
#define LUA_CORE
@@ -21,113 +20,89 @@
#include "lundump.h"
#include "lzio.h"
-#define LoadByte (lu_byte) ezgetc
+#ifdef LUAC_TRUST_BINARIES
+#define IF(c,s)
+#else
+#define IF(c,s) if (c) error(S,s)
+#endif
typedef struct {
lua_State* L;
ZIO* Z;
Mbuffer* b;
- int swap;
const char* name;
+#ifdef LUAC_SWAP_ON_LOAD
+ int swap;
+#endif
} LoadState;
-static void error (LoadState* S, const char* fmt, ...)
-{
- const char *msg;
- va_list argp;
- va_start(argp,fmt);
- msg=luaO_pushvfstring(S->L,fmt,argp);
- va_end(argp);
- luaO_pushfstring(S->L,"%s: %s",S->name,msg);
- luaD_throw(S->L,LUA_ERRSYNTAX);
-}
+#ifdef LUAC_SWAP_ON_LOAD
+static void LoadMem (LoadState* S, void* b, int n, size_t size);
+#else
+#define LoadMem(S,b,n,size) LoadBlock(S,b,(n)*(size))
+#endif
-static int ezgetc (LoadState* S)
-{
- int c=zgetc(S->Z);
- if (c==EOZ) error(S,"unexpected end of file");
- return c;
-}
+#define LoadByte(S) (lu_byte)LoadChar(S)
+#define LoadVar(S,x) LoadMem(S,&x,1,sizeof(x))
+#define LoadVector(S,b,n,size) LoadMem(S,b,n,size)
-static void ezread (LoadState* S, void* b, int n)
+static void error(LoadState* S, const char* why)
{
- int r=luaZ_read(S->Z,b,n);
- if (r!=0) error(S,"unexpected end of file");
+ luaO_pushfstring(S->L,"%s: %s",S->name,why);
+ luaD_throw(S->L,LUA_ERRSYNTAX);
}
-static void LoadBlock (LoadState* S, void* b, size_t size)
+static void LoadBlock(LoadState* S, void* b, size_t size)
{
- if (S->swap)
- {
- char* p=(char*) b+size-1;
- int n=size;
- while (n--) *p--=(char)ezgetc(S);
- }
- else
- ezread(S,b,size);
+ size_t r=luaZ_read(S->Z,b,size);
+ IF (r!=0, "unexpected end");
}
-static void LoadVector (LoadState* S, void* b, int m, size_t size)
+static int LoadChar(LoadState* S)
{
- if (S->swap)
- {
- char* q=(char*) b;
- while (m--)
- {
- char* p=q+size-1;
- int n=size;
- while (n--) *p--=(char)ezgetc(S);
- q+=size;
- }
- }
- else
- ezread(S,b,m*size);
-}
-
-static int LoadInt (LoadState* S)
-{
- int x;
- LoadBlock(S,&x,sizeof(x));
- if (x<0) error(S,"bad integer");
+ char x;
+ LoadVar(S,x);
return x;
}
-static size_t LoadSize (LoadState* S)
+static int LoadInt(LoadState* S)
{
- size_t x;
- LoadBlock(S,&x,sizeof(x));
+ int x;
+ LoadVar(S,x);
+ IF (x<0, "bad integer");
return x;
}
-static lua_Number LoadNumber (LoadState* S)
+static lua_Number LoadNumber(LoadState* S)
{
lua_Number x;
- LoadBlock(S,&x,sizeof(x));
+ LoadVar(S,x);
return x;
}
-static TString* LoadString (LoadState* S)
+static TString* LoadString(LoadState* S)
{
- size_t size=LoadSize(S);
+ size_t size;
+ LoadVar(S,size);
if (size==0)
return NULL;
else
{
char* s=luaZ_openspace(S->L,S->b,size);
- ezread(S,s,size);
+ LoadBlock(S,s,size);
return luaS_newlstr(S->L,s,size-1); /* remove trailing '\0' */
}
}
-static void LoadCode (LoadState* S, Proto* f)
+static void LoadCode(LoadState* S, Proto* f)
{
- int size=LoadInt(S);
- f->code=luaM_newvector(S->L,size,Instruction);
- f->sizecode=size;
- LoadVector(S,f->code,size,sizeof(Instruction));
+ int n=LoadInt(S);
+ f->code=luaM_newvector(S->L,n,Instruction);
+ f->sizecode=n;
+ LoadVector(S,f->code,n,sizeof(Instruction));
}
-static void LoadLocals (LoadState* S, Proto* f)
+static void LoadLocals(LoadState* S, Proto* f)
{
int i,n;
n=LoadInt(S);
@@ -142,29 +117,27 @@ static void LoadLocals (LoadState* S, Proto* f)
}
}
-static void LoadLines (LoadState* S, Proto* f)
+static void LoadLines(LoadState* S, Proto* f)
{
- int size=LoadInt(S);
- f->lineinfo=luaM_newvector(S->L,size,int);
- f->sizelineinfo=size;
- LoadVector(S,f->lineinfo,size,sizeof(int));
+ int n=LoadInt(S);
+ f->lineinfo=luaM_newvector(S->L,n,int);
+ f->sizelineinfo=n;
+ LoadVector(S,f->lineinfo,n,sizeof(int));
}
-static void LoadUpvalues (LoadState* S, Proto* f)
+static void LoadUpvalues(LoadState* S, Proto* f)
{
int i,n;
n=LoadInt(S);
- if (n!=0 && n!=f->nups)
- error(S,"bad nupvalues (read %d; expected %d)",n,f->nups);
f->upvalues=luaM_newvector(S->L,n,TString*);
f->sizeupvalues=n;
for (i=0; i<n; i++) f->upvalues[i]=NULL;
for (i=0; i<n; i++) f->upvalues[i]=LoadString(S);
}
-static Proto* LoadFunction (LoadState* S, TString* p);
+static Proto* LoadFunction(LoadState* S, TString* p);
-static void LoadConstants (LoadState* S, Proto* f)
+static void LoadConstants(LoadState* S, Proto* f)
{
int i,n;
n=LoadInt(S);
@@ -174,14 +147,14 @@ static void LoadConstants (LoadState* S, Proto* f)
for (i=0; i<n; i++)
{
TValue* o=&f->k[i];
- int t=LoadByte(S);
+ int t=LoadChar(S);
switch (t)
{
case LUA_TNIL:
setnilvalue(o);
break;
case LUA_TBOOLEAN:
- setbvalue(o,LoadByte(S));
+ setbvalue(o,LoadChar(S));
break;
case LUA_TNUMBER:
setnvalue(o,LoadNumber(S));
@@ -190,7 +163,7 @@ static void LoadConstants (LoadState* S, Proto* f)
setsvalue2n(S->L,o,LoadString(S));
break;
default:
- error(S,"bad constant type (%d)",t);
+ IF (1, "bad constant");
break;
}
}
@@ -201,7 +174,7 @@ static void LoadConstants (LoadState* S, Proto* f)
for (i=0; i<n; i++) f->p[i]=LoadFunction(S,f->source);
}
-static Proto* LoadFunction (LoadState* S, TString* p)
+static Proto* LoadFunction(LoadState* S, TString* p)
{
Proto* f=luaF_newproto(S->L);
setptvalue2s(S->L,S->L->top,f); incr_top(S->L);
@@ -217,46 +190,21 @@ static Proto* LoadFunction (LoadState* S, TString* p)
LoadUpvalues(S,f);
LoadConstants(S,f);
LoadCode(S,f);
-#ifndef TRUST_BINARIES
- if (!luaG_checkcode(f)) error(S,"bad code");
-#endif
+ IF (!luaG_checkcode(f), "bad code");
S->L->top--;
return f;
}
-static void LoadSignature (LoadState* S)
-{
- const char* s=LUA_SIGNATURE;
- while (*s!=0 && ezgetc(S)==*s)
- ++s;
- if (*s!=0) error(S,"bad signature");
-}
-
-static void TestSize (LoadState* S, int s, const char* what)
-{
- int r=LoadByte(S);
- if (r!=s)
- error(S,"bad size of %s (read %d; expected %d)",what,r,s);
-}
-
-#define V(v) v/16,v%16
-
-static void LoadHeader (LoadState* S)
+static void LoadHeader(LoadState* S)
{
- int version;
- lua_Number x,tx=TEST_NUMBER;
- LoadSignature(S);
- version=LoadByte(S);
- if (version!=VERSION)
- error(S,"bad version (read %d.%d; expected %d.%d)",V(version),V(VERSION));
- S->swap=(luaU_endianness()!=LoadByte(S)); /* need to swap bytes? */
- TestSize(S,sizeof(int),"int");
- TestSize(S,sizeof(size_t),"size_t");
- TestSize(S,sizeof(Instruction),"instruction");
- TestSize(S,sizeof(lua_Number),"number");
- x=LoadNumber(S);
- if (x!=tx)
- error(S,"unknown number format");
+ char h[LUAC_HEADERSIZE];
+ char s[LUAC_HEADERSIZE];
+ luaU_header(h);
+ LoadBlock(S,s,LUAC_HEADERSIZE);
+#ifdef LUAC_SWAP_ON_LOAD
+ S->swap=(s[6]!=h[6]); s[6]=h[6];
+#endif
+ IF (memcmp(h,s,LUAC_HEADERSIZE)!=0, "bad header");
}
/*
@@ -279,10 +227,64 @@ Proto* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff, const char* name)
}
/*
-** find byte order
+* make header
*/
-int luaU_endianness (void)
+void luaU_header (char* h)
{
int x=1;
- return *(char*)&x;
+ memcpy(h,LUA_SIGNATURE,sizeof(LUA_SIGNATURE)-1);
+ h+=sizeof(LUA_SIGNATURE)-1;
+ *h++=(char)LUAC_VERSION;
+ *h++=(char)LUAC_FORMAT;
+ *h++=(char)*(char*)&x;
+ *h++=(char)sizeof(int);
+ *h++=(char)sizeof(size_t);
+ *h++=(char)sizeof(Instruction);
+ *h++=(char)sizeof(lua_Number);
+ *h++=(char)(((lua_Number)0.5)==0);
}
+
+#ifdef LUAC_SWAP_ON_LOAD
+static void LoadMem (LoadState* S, void* b, int n, size_t size)
+{
+ LoadBlock(S,b,n*size);
+ if (S->swap)
+ {
+ char* p=(char*) b;
+ char c;
+ switch (size)
+ {
+ case 1:
+ break;
+ case 2:
+ while (n--)
+ {
+ c=p[0]; p[0]=p[1]; p[1]=c;
+ p+=2;
+ }
+ break;
+ case 4:
+ while (n--)
+ {
+ c=p[0]; p[0]=p[3]; p[3]=c;
+ c=p[1]; p[1]=p[2]; p[2]=c;
+ p+=4;
+ }
+ break;
+ case 8:
+ while (n--)
+ {
+ c=p[0]; p[0]=p[7]; p[7]=c;
+ c=p[1]; p[1]=p[6]; p[6]=c;
+ c=p[2]; p[2]=p[5]; p[5]=c;
+ c=p[3]; p[3]=p[4]; p[4]=c;
+ p+=8;
+ }
+ break;
+ default:
+ IF(1, "bad size");
+ break;
+ }
+ }
+}
+#endif
diff --git a/src/lundump.h b/src/lundump.h
index 924cfb01..5de3c46e 100644
--- a/src/lundump.h
+++ b/src/lundump.h
@@ -1,5 +1,5 @@
/*
-** $Id: lundump.h,v 1.35 2005/05/12 00:26:50 lhf Exp $
+** $Id: lundump.h,v 1.38 2005/09/02 01:54:47 lhf Exp $
** load pre-compiled Lua chunks
** See Copyright Notice in lua.h
*/
@@ -10,22 +10,53 @@
#include "lobject.h"
#include "lzio.h"
+/* make it work with Lua 5.0 */
+#ifndef LUA_VERSION_NUM
+#define LUAI_FUNC
+#define lua_Writer lua_Chunkwriter
+#endif
+
/* load one chunk; from lundump.c */
-LUAI_FUNC Proto* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff, const char *name);
+LUAI_FUNC Proto* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff, const char* name);
-/* find byte order; from lundump.c */
-LUAI_FUNC int luaU_endianness (void);
+/* make header; from lundump.c */
+LUAI_FUNC void luaU_header (char* h);
/* dump one chunk; from ldump.c */
-LUAI_FUNC int luaU_dump (lua_State* L, const Proto* f, lua_Chunkwriter w, void* data, int strip);
+LUAI_FUNC int luaU_dump (lua_State* L, const Proto* f, lua_Writer w, void* data, int strip);
/* print one chunk; from print.c */
LUAI_FUNC void luaU_print (const Proto* f, int full);
/* for header of binary files -- this is Lua 5.1 */
-#define VERSION 0x51
-
-/* for testing native format of lua_Numbers */
-#define TEST_NUMBER ((lua_Number)31415926.0)
+#define LUAC_VERSION 0x51
+
+/* for header of binary files -- this is the official format */
+#define LUAC_FORMAT 0
+
+/* size of header of binary files */
+#define LUAC_HEADERSIZE 12
+
+/* make it work with Lua 5.0 */
+#ifndef LUA_VERSION_NUM
+#define LUA_SIGNATURE "\033Lua"
+#define TValue TObject
+#define rawtsvalue tsvalue
+#define linedefined lineDefined
+#define lastlinedefined lineDefined
+#define setptvalue2s(L,t,f)
+#undef setsvalue2n
+#define setsvalue2n(L,x,y) setsvalue(x,y)
+#define LUA_QL(x) "'" x "'"
+#define LUA_QS LUA_QL("%s")
+#undef LUAC_VERSION
+#define LUAC_VERSION 0x50
+#ifdef lapi_c
+#define luaU_dump(L,f,w,d) (luaU_dump)(L,f,w,d,0)
+#endif
+#ifdef ldo_c
+#define luaU_undump(L,z,b) (luaU_undump)(L,z,b,z->name)
+#endif
+#endif
#endif
diff --git a/src/lvm.c b/src/lvm.c
index f591a35f..92c853b2 100644
--- a/src/lvm.c
+++ b/src/lvm.c
@@ -1,5 +1,5 @@
/*
-** $Id: lvm.c,v 2.44 2005/05/17 19:49:15 roberto Exp $
+** $Id: lvm.c,v 2.55 2005/09/09 18:23:35 roberto Exp $
** Lua virtual machine
** See Copyright Notice in lua.h
*/
@@ -226,7 +226,7 @@ int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r) {
if (ttype(l) != ttype(r))
return luaG_ordererror(L, l, r);
else if (ttisnumber(l))
- return luai_numlt(nvalue(l), nvalue(r));
+ return luai_numlt(L, nvalue(l), nvalue(r));
else if (ttisstring(l))
return l_strcmp(rawtsvalue(l), rawtsvalue(r)) < 0;
else if ((res = call_orderTM(L, l, r, TM_LT)) != -1)
@@ -240,7 +240,7 @@ static int lessequal (lua_State *L, const TValue *l, const TValue *r) {
if (ttype(l) != ttype(r))
return luaG_ordererror(L, l, r);
else if (ttisnumber(l))
- return luai_numle(nvalue(l), nvalue(r));
+ return luai_numle(L, nvalue(l), nvalue(r));
else if (ttisstring(l))
return l_strcmp(rawtsvalue(l), rawtsvalue(r)) <= 0;
else if ((res = call_orderTM(L, l, r, TM_LE)) != -1) /* first try `le' */
@@ -256,7 +256,7 @@ int luaV_equalval (lua_State *L, const TValue *t1, const TValue *t2) {
lua_assert(ttype(t1) == ttype(t2));
switch (ttype(t1)) {
case LUA_TNIL: return 1;
- case LUA_TNUMBER: return luai_numeq(nvalue(t1), nvalue(t2));
+ case LUA_TNUMBER: return luai_numeq(L, nvalue(t1), nvalue(t2));
case LUA_TBOOLEAN: return bvalue(t1) == bvalue(t2); /* true must be 1 !! */
case LUA_TLIGHTUSERDATA: return pvalue(t1) == pvalue(t2);
case LUA_TUSERDATA: {
@@ -311,26 +311,26 @@ void luaV_concat (lua_State *L, int total, int last) {
}
-static StkId Arith (lua_State *L, StkId ra, const TValue *rb,
- const TValue *rc, TMS op) {
+static void Arith (lua_State *L, StkId ra, const TValue *rb,
+ const TValue *rc, TMS op) {
TValue tempb, tempc;
const TValue *b, *c;
if ((b = luaV_tonumber(rb, &tempb)) != NULL &&
(c = luaV_tonumber(rc, &tempc)) != NULL) {
lua_Number nb = nvalue(b), nc = nvalue(c);
switch (op) {
- case TM_ADD: setnvalue(ra, luai_numadd(nb, nc)); break;
- case TM_SUB: setnvalue(ra, luai_numsub(nb, nc)); break;
- case TM_MUL: setnvalue(ra, luai_nummul(nb, nc)); break;
- case TM_DIV: setnvalue(ra, luai_numdiv(nb, nc)); break;
- case TM_MOD: setnvalue(ra, luai_nummod(nb, nc)); break;
- case TM_POW: setnvalue(ra, luai_numpow(nb, nc)); break;
+ case TM_ADD: setnvalue(ra, luai_numadd(L, nb, nc)); break;
+ case TM_SUB: setnvalue(ra, luai_numsub(L, nb, nc)); break;
+ case TM_MUL: setnvalue(ra, luai_nummul(L, nb, nc)); break;
+ case TM_DIV: setnvalue(ra, luai_numdiv(L, nb, nc)); break;
+ case TM_MOD: setnvalue(ra, luai_nummod(L, nb, nc)); break;
+ case TM_POW: setnvalue(ra, luai_numpow(L, nb, nc)); break;
+ case TM_UNM: setnvalue(ra, luai_numunm(L, nb)); break;
default: lua_assert(0); break;
}
}
else if (!call_binTM(L, rb, rc, ra, op))
luaG_aritherror(L, rb, rc);
- return L->base;
}
@@ -358,15 +358,12 @@ static StkId Arith (lua_State *L, StkId ra, const TValue *rb,
#define Protect(x) { L->savedpc = pc; {x;}; base = L->base; }
-StkId luaV_execute (lua_State *L, int nexeccalls) {
+void luaV_execute (lua_State *L, int nexeccalls) {
LClosure *cl;
StkId base;
TValue *k;
const Instruction *pc;
- callentry: /* entry point when calling new functions */
- if (L->hookmask & LUA_MASKCALL)
- luaD_callhook(L, LUA_HOOKCALL, -1);
- retentry: /* entry point when returning to old functions */
+ reentry: /* entry point */
pc = L->savedpc;
cl = &clvalue(L->ci->func)->l;
base = L->base;
@@ -380,7 +377,7 @@ StkId luaV_execute (lua_State *L, int nexeccalls) {
traceexec(L, pc);
if (L->status == LUA_YIELD) { /* did hook yield? */
L->savedpc = pc - 1;
- return NULL;
+ return;
}
base = L->base;
}
@@ -462,7 +459,7 @@ StkId luaV_execute (lua_State *L, int nexeccalls) {
TValue *rc = RKC(i);
if (ttisnumber(rb) && ttisnumber(rc)) {
lua_Number nb = nvalue(rb), nc = nvalue(rc);
- setnvalue(ra, luai_numadd(nb, nc));
+ setnvalue(ra, luai_numadd(L, nb, nc));
}
else
Protect(Arith(L, ra, rb, rc, TM_ADD));
@@ -473,7 +470,7 @@ StkId luaV_execute (lua_State *L, int nexeccalls) {
TValue *rc = RKC(i);
if (ttisnumber(rb) && ttisnumber(rc)) {
lua_Number nb = nvalue(rb), nc = nvalue(rc);
- setnvalue(ra, luai_numsub(nb, nc));
+ setnvalue(ra, luai_numsub(L, nb, nc));
}
else
Protect(Arith(L, ra, rb, rc, TM_SUB));
@@ -484,7 +481,7 @@ StkId luaV_execute (lua_State *L, int nexeccalls) {
TValue *rc = RKC(i);
if (ttisnumber(rb) && ttisnumber(rc)) {
lua_Number nb = nvalue(rb), nc = nvalue(rc);
- setnvalue(ra, luai_nummul(nb, nc));
+ setnvalue(ra, luai_nummul(L, nb, nc));
}
else
Protect(Arith(L, ra, rb, rc, TM_MUL));
@@ -495,7 +492,7 @@ StkId luaV_execute (lua_State *L, int nexeccalls) {
TValue *rc = RKC(i);
if (ttisnumber(rb) && ttisnumber(rc)) {
lua_Number nb = nvalue(rb), nc = nvalue(rc);
- setnvalue(ra, luai_numdiv(nb, nc));
+ setnvalue(ra, luai_numdiv(L, nb, nc));
}
else
Protect(Arith(L, ra, rb, rc, TM_DIV));
@@ -506,7 +503,7 @@ StkId luaV_execute (lua_State *L, int nexeccalls) {
TValue *rc = RKC(i);
if (ttisnumber(rb) && ttisnumber(rc)) {
lua_Number nb = nvalue(rb), nc = nvalue(rc);
- setnvalue(ra, luai_nummod(nb, nc));
+ setnvalue(ra, luai_nummod(L, nb, nc));
}
else
Protect(Arith(L, ra, rb, rc, TM_MOD));
@@ -517,25 +514,20 @@ StkId luaV_execute (lua_State *L, int nexeccalls) {
TValue *rc = RKC(i);
if (ttisnumber(rb) && ttisnumber(rc)) {
lua_Number nb = nvalue(rb), nc = nvalue(rc);
- setnvalue(ra, luai_numpow(nb, nc));
+ setnvalue(ra, luai_numpow(L, nb, nc));
}
else
Protect(Arith(L, ra, rb, rc, TM_POW));
continue;
}
case OP_UNM: {
- const TValue *rb = RB(i);
- TValue temp;
- if (tonumber(rb, &temp)) {
+ TValue *rb = RB(i);
+ if (ttisnumber(rb)) {
lua_Number nb = nvalue(rb);
- setnvalue(ra, luai_numunm(nb));
+ setnvalue(ra, luai_numunm(L, nb));
}
else {
- rb = RB(i); /* `tonumber' erased `rb' */
- Protect(
- if (!call_binTM(L, rb, &luaO_nilobject, ra, TM_UNM))
- luaG_aritherror(L, rb, &luaO_nilobject);
- )
+ Protect(Arith(L, ra, rb, rb, TM_UNM));
}
continue;
}
@@ -544,16 +536,23 @@ StkId luaV_execute (lua_State *L, int nexeccalls) {
setbvalue(ra, res);
continue;
}
- case OP_SIZ: {
+ case OP_LEN: {
const TValue *rb = RB(i);
- if (ttype(rb) == LUA_TTABLE) {
- setnvalue(ra, cast(lua_Number, luaH_getn(hvalue(rb))));
- }
- else { /* try metamethod */
- Protect(
- if (!call_binTM(L, rb, &luaO_nilobject, ra, TM_SIZ))
- luaG_typeerror(L, rb, "get size of");
- )
+ switch (ttype(rb)) {
+ case LUA_TTABLE: {
+ setnvalue(ra, cast(lua_Number, luaH_getn(hvalue(rb))));
+ break;
+ }
+ case LUA_TSTRING: {
+ setnvalue(ra, cast(lua_Number, tsvalue(rb)->len));
+ break;
+ }
+ default: { /* try metamethod */
+ Protect(
+ if (!call_binTM(L, rb, &luaO_nilobject, ra, TM_LEN))
+ luaG_typeerror(L, rb, "get length of");
+ )
+ }
}
continue;
}
@@ -569,8 +568,10 @@ StkId luaV_execute (lua_State *L, int nexeccalls) {
continue;
}
case OP_EQ: {
+ TValue *rb = RKB(i);
+ TValue *rc = RKC(i);
Protect(
- if (equalobj(L, RKB(i), RKC(i)) == GETARG_A(i))
+ if (equalobj(L, rb, rc) == GETARG_A(i))
dojump(L, pc, GETARG_sBx(*pc));
)
pc++;
@@ -593,6 +594,12 @@ StkId luaV_execute (lua_State *L, int nexeccalls) {
continue;
}
case OP_TEST: {
+ if (l_isfalse(ra) == GETARG_C(i)) pc++;
+ else
+ dojump(L, pc, GETARG_sBx(*pc) + 1);
+ continue;
+ }
+ case OP_TESTSET: {
TValue *rb = RB(i);
if (l_isfalse(rb) == GETARG_C(i)) pc++;
else {
@@ -609,7 +616,7 @@ StkId luaV_execute (lua_State *L, int nexeccalls) {
switch (luaD_precall(L, ra, nresults)) {
case PCRLUA: {
nexeccalls++;
- goto callentry; /* restart luaV_execute over new Lua function */
+ goto reentry; /* restart luaV_execute over new Lua function */
}
case PCRC: {
/* it was a C function (`precall' called it); adjust results */
@@ -618,7 +625,7 @@ StkId luaV_execute (lua_State *L, int nexeccalls) {
continue;
}
default: {
- return NULL;
+ return; /* yield */
}
}
}
@@ -643,15 +650,14 @@ StkId luaV_execute (lua_State *L, int nexeccalls) {
ci->savedpc = L->savedpc;
ci->tailcalls++; /* one more call lost */
L->ci--; /* remove new frame */
- goto callentry;
+ goto reentry;
}
- case PCRC: {
- /* it was a C function (`precall' called it) */
+ case PCRC: { /* it was a C function (`precall' called it) */
base = L->base;
continue;
}
default: {
- return NULL;
+ return; /* yield */
}
}
}
@@ -660,22 +666,21 @@ StkId luaV_execute (lua_State *L, int nexeccalls) {
if (b != 0) L->top = ra+b-1;
if (L->openupval) luaF_close(L, base);
L->savedpc = pc;
+ b = luaD_poscall(L, ra);
if (--nexeccalls == 0) /* was previous function running `here'? */
- return ra; /* no: return */
+ return; /* no: return */
else { /* yes: continue its execution */
- int nresults = L->ci->nresults;
- lua_assert(isLua(L->ci - 1));
- lua_assert(GET_OPCODE(*((L->ci - 1)->savedpc - 1)) == OP_CALL);
- luaD_poscall(L, nresults, ra);
- if (nresults >= 0) L->top = L->ci->top;
- goto retentry;
+ if (b) L->top = L->ci->top;
+ lua_assert(isLua(L->ci));
+ lua_assert(GET_OPCODE(*((L->ci)->savedpc - 1)) == OP_CALL);
+ goto reentry;
}
}
case OP_FORLOOP: {
lua_Number step = nvalue(ra+2);
- lua_Number idx = luai_numadd(nvalue(ra), step); /* increment index */
+ lua_Number idx = luai_numadd(L, nvalue(ra), step); /* increment index */
lua_Number limit = nvalue(ra+1);
- if (step > 0 ? luai_numle(idx, limit) : luai_numle(limit, idx)) {
+ if (step > 0 ? luai_numle(L, idx, limit) : luai_numle(L, limit, idx)) {
dojump(L, pc, GETARG_sBx(i)); /* jump back */
setnvalue(ra, idx); /* update internal index... */
setnvalue(ra+3, idx); /* ...and external index */
@@ -693,7 +698,7 @@ StkId luaV_execute (lua_State *L, int nexeccalls) {
luaG_runerror(L, LUA_QL("for") " limit must be a number");
else if (!tonumber(pstep, ra+2))
luaG_runerror(L, LUA_QL("for") " step must be a number");
- setnvalue(ra, luai_numsub(nvalue(ra), nvalue(pstep)));
+ setnvalue(ra, luai_numsub(L, nvalue(ra), nvalue(pstep)));
dojump(L, pc, GETARG_sBx(i));
continue;
}
@@ -720,7 +725,7 @@ StkId luaV_execute (lua_State *L, int nexeccalls) {
int last;
Table *h;
if (n == 0) {
- n = L->top - ra - 1;
+ n = cast(int, L->top - ra) - 1;
L->top = L->ci->top;
}
if (c == 0) c = cast(int, *pc++);
@@ -764,15 +769,21 @@ StkId luaV_execute (lua_State *L, int nexeccalls) {
int b = GETARG_B(i) - 1;
int j;
CallInfo *ci = L->ci;
- int n = ci->base - ci->func - cl->p->numparams - 1;
+ int n = cast(int, ci->base - ci->func) - cl->p->numparams - 1;
if (b == LUA_MULTRET) {
+ Protect(luaD_checkstack(L, n));
+ ra = RA(i); /* previous call may change the stack */
b = n;
L->top = ra + n;
}
- for (j=0; j<b && j<n; j++)
- setobjs2s(L, ra+j, ci->base - n + j);
- for (; j<b; j++)
- setnilvalue(ra+j);
+ for (j = 0; j < b; j++) {
+ if (j < n) {
+ setobjs2s(L, ra + j, ci->base - n + j);
+ }
+ else {
+ setnilvalue(ra + j);
+ }
+ }
continue;
}
}
diff --git a/src/lvm.h b/src/lvm.h
index b00cb8f2..788423f8 100644
--- a/src/lvm.h
+++ b/src/lvm.h
@@ -1,5 +1,5 @@
/*
-** $Id: lvm.h,v 2.4 2005/04/25 19:24:10 roberto Exp $
+** $Id: lvm.h,v 2.5 2005/08/22 18:54:49 roberto Exp $
** Lua virtual machine
** See Copyright Notice in lua.h
*/
@@ -30,7 +30,7 @@ LUAI_FUNC void luaV_gettable (lua_State *L, const TValue *t, TValue *key,
StkId val);
LUAI_FUNC void luaV_settable (lua_State *L, const TValue *t, TValue *key,
StkId val);
-LUAI_FUNC StkId luaV_execute (lua_State *L, int nexeccalls);
+LUAI_FUNC void luaV_execute (lua_State *L, int nexeccalls);
LUAI_FUNC void luaV_concat (lua_State *L, int total, int last);
#endif
diff --git a/src/lzio.c b/src/lzio.c
index abe086b4..5121ada8 100644
--- a/src/lzio.c
+++ b/src/lzio.c
@@ -1,5 +1,5 @@
/*
-** $Id: lzio.c,v 1.30 2005/05/17 19:49:15 roberto Exp $
+** $Id: lzio.c,v 1.31 2005/06/03 20:15:29 roberto Exp $
** a generic input stream interface
** See Copyright Notice in lua.h
*/
@@ -34,10 +34,12 @@ int luaZ_fill (ZIO *z) {
int luaZ_lookahead (ZIO *z) {
if (z->n == 0) {
- int c = luaZ_fill(z);
- if (c == EOZ) return c;
- z->n++;
- z->p--;
+ if (luaZ_fill(z) == EOZ)
+ return EOZ;
+ else {
+ z->n++; /* luaZ_fill removed first byte; put back it */
+ z->p--;
+ }
}
return char2int(*z->p);
}
@@ -56,14 +58,8 @@ void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data) {
size_t luaZ_read (ZIO *z, void *b, size_t n) {
while (n) {
size_t m;
- if (z->n == 0) {
- if (luaZ_fill(z) == EOZ)
- return n; /* return number of missing bytes */
- else {
- ++z->n; /* filbuf removed first byte; put back it */
- --z->p;
- }
- }
+ if (luaZ_lookahead(z) == EOZ)
+ return n; /* return number of missing bytes */
m = (n <= z->n) ? n : z->n; /* min. between n and z->n */
memcpy(b, z->p, m);
z->n -= m;
diff --git a/src/print.c b/src/print.c
index 85308705..8090a2d5 100644
--- a/src/print.c
+++ b/src/print.c
@@ -1,5 +1,5 @@
/*
-** $Id: print.c,v 1.50 2005/05/12 00:26:50 lhf Exp $
+** $Id: print.c,v 1.52 2005/06/08 14:40:44 lhf Exp $
** print bytecodes
** See Copyright Notice in lua.h
*/
@@ -135,6 +135,10 @@ static void PrintCode(const Proto* f)
case OP_CLOSURE:
printf("\t; %p",VOID(f->p[bx]));
break;
+ case OP_SETLIST:
+ if (c==0) printf("\t; %d",(int)code[++pc]);
+ else printf("\t; %d",c);
+ break;
default:
break;
}
@@ -158,7 +162,7 @@ static void PrintHeader(const Proto* f)
(f->linedefined==0)?"main":"function",s,
f->linedefined,f->lastlinedefined,
S(f->sizecode),f->sizecode*Sizeof(Instruction),VOID(f));
- printf("%d%s param%s, %d stack%s, %d upvalue%s, ",
+ printf("%d%s param%s, %d slot%s, %d upvalue%s, ",
f->numparams,f->is_vararg?"+":"",SS(f->numparams),
S(f->maxstacksize),S(f->nups));
printf("%d local%s, %d constant%s, %d function%s\n",
diff --git a/test/luac.lua b/test/luac.lua
index adae1b29..96a0a97c 100644
--- a/test/luac.lua
+++ b/test/luac.lua
@@ -4,4 +4,4 @@
assert(arg[1]~=nil and arg[2]==nil,"usage: lua luac.lua file.lua")
f=assert(io.open("luac.out","wb"))
assert(f:write(string.dump(assert(loadfile(arg[1])))))
-assert(io.close(f))
+assert(f:close())
diff --git a/test/trace-calls.lua b/test/trace-calls.lua
index 5613c2cb..6d7a7b3b 100644
--- a/test/trace-calls.lua
+++ b/test/trace-calls.lua
@@ -1,5 +1,5 @@
-- trace calls
--- example: lua -ltrace-calls.lua bisect.lua
+-- example: lua -ltrace-calls bisect.lua
local level=0